BESC Info
At Besc Crypto, we are dedicated to revolutionizing the way you trade and exchange tokens. Our platform is designed with user experience in mind, ensuring that both novice and experienced traders can navigate the world of cryptocurrency with ease. With a commitment to transparency and security, we strive to provide a reliable environment for all your trading needs.
TrustNet Score
The TrustNet Score evaluates crypto projects based on audit results, security, KYC verification, and social media presence. This score offers a quick, transparent view of a project's credibility, helping users make informed decisions in the Web3 space.
Real-Time Threat Detection
Real-time threat detection, powered by Cyvers.io,
is currently not
activated
for this project.
This advanced feature provides continuous monitoring and instant alerts to safeguard your assets from potential security threats. Real-time detection enhances your project's security by proactively identifying and mitigating risks.
For more information, click here.
Security Assessments
Summary and Final Words
No crucial issues found
The contract does not contain issues of high or medium criticality. This means that no known vulnerabilities were found in the source code.
Contract is upgradeable
The contract uses a proxy pattern or similar mechanism, enabling future upgrades. This can introduce risks if the upgrade mechanism is not securely managed.
Scope of Work
This audit covers a full security evaluation of the provided JavaScript/TypeScript codebase. All relevant files and modules were retrieved from the customer’s repository and verified for consistency with the delivered package.
The auditing process follows these systematic steps:
- Automated Tool Analysis: Run our proprietary, optimized scanner across the entire JS/TS codebase to detect common vulnerabilities, insecure patterns, and dependency issues.
- Manual Code Review: Conduct a line-by-line inspection of key modules—authentication, authorization, wallet management, API routes, and utility libraries—to uncover logic flaws and security gaps.
- Architectural & Dependency Assessment: Verify that project structure, module boundaries, and third-party libraries follow best-practice patterns for maintainability and minimal attack surface.
- Specification Alignment: Confirm that implemented functionality matches customer requirements and design documents, with no hidden or undocumented features.
- Static Analysis Coverage Review: Evaluate existing unit and integration tests for coverage gaps; recommend additional tests for untested or under-tested paths.
- Dynamic & Symbolic Execution: Exercise edge cases via symbolic analysis to validate input handling, boundary conditions, and error paths in critical functions.
- API Pentesting: Perform authenticated and unauthenticated penetration tests against all REST/WebSocket endpoints, including fuzzing, rate-limit bypass, and business-logic abuse scenarios.
- Best Practices Evaluation: Benchmark against JavaScript/TypeScript security guidelines (OWASP Top 10, Snyk recommendations, Node.js hardening) to improve resilience, performance, and maintainability.
- Actionable Recommendations: Deliver a prioritized list of clear, code-level remediation steps to secure the codebase, lock down configuration, and improve overall robustness.
If any files have been modified after this audit, their integrity and security posture should be re-validated, as unreviewed changes may introduce new vulnerabilities.
Final Words
The following provides a concise summary of the audit report, accompanied by insightful comments from the auditor. This overview captures the key findings and observations, offering valuable context and clarity.
This initial security audit of the CEX backend codebase identified 65 distinct issues spanning authentication, authorization, cryptographic configuration, input validation, transaction handling, and error management. Our goal is to ensure that both technical teams and investors understand the scope of work required to achieve a production-ready security posture.
The architecture is modular and well-structured, but without remediation these vulnerabilities expose the platform to data breaches, fund loss, and service disruption. We recommend a phased remediation plan emphasizing the highest-risk areas first.
Technical Summary
- Authentication & Tokens: Symmetric HS256 JWTs with default fallback secrets; missing nonce verification in SIWE flows; plaintext 2FA secrets
- Web Security: No end-to-end CSRF protection; numerous unsanitized uses of
dangerouslySetInnerHTML; insecure CORS origins - Transaction Handling: Multiple race conditions (withdrawals, transfers, vesting, presales) due to load-process-save patterns without locking or transactions
- Configuration & Secrets: File-based feature flags and activation checks; API keys and encryption keys stored in environment variables without vault integration
- Error Management: Inconsistent use of custom error types; widespread generic
Errorthrows; insufficient logging context
Audit Checklist
- Keypair & Token Management: HS256 → RS256/ES256; enforce secret presence at startup
- Input Validation & Sanitization: Full schema validation; sanitize all HTML and file paths
- CSRF & CORS: Implement Double-Submit-Cookie pattern; restrict allowed origins via configuration
- Transaction Security: Wrap all financial reads and writes in database transactions with row-level locks
- Error Handling & Logging: Define and throw custom error classes; capture full stack and context in logs
- Secrets Management: Migrate API keys and encryption keys into a dedicated vault; eliminate plaintext storage of cryptographic material
Recommended Remediation Roadmap
- JWT & 2FA Security:
- Migrate to asymmetric JWT signing (RS256/ES256).
- Encrypt TOTP/2FA secrets at rest; never store or return plaintext keys.
- Web & API Protection:
- Implement CSRF tokens end-to-end (cookie + header verification).
- Sanitize every use of
dangerouslySetInnerHTMLwith a library like DOMPurify. - Configure CORS origins via environment-driven allowlists.
- Financial Transaction Integrity:
- Use
sequelize.transactionwithFOR UPDATElocks for all balance updates. - Replace file-based vesting/presale data stores with transactional database tables or distributed locks.
- Use
- Error Handling & Observability:
- Introduce a shared error framework with custom exception types.
- Instrument structured logging (user IDs, request IDs, error contexts).
- Secrets & Configuration:
- Adopt a secrets manager or vault for exchange API keys and encryption keys.
- Remove file-based feature toggles; store flags in a secure configuration service.
Note: This report covers only the CEX backend code under review. No functional or unit testing was performed. We recommend integrating these findings into your development backlog and verifying remediation with follow-up audits before any production launch.
Files and details
Findings and Audit result
critical Issues | 12 findings
Resolved
#1 critical Issue
Multiple Critical and High Severity Vulnerabilities in Dependencies
The `npm audit` scan identified 30 vulnerabilities (9 critical, 18 high, 3 moderate) in project dependencies. Critical vulnerabilities exist in core components like `next` (framework v15.1.0 - DoS/Auth Bypass), `mysql2` (database driver - RCE/Prototype Pollution), and `elliptic` (used in wallet connectivity - Private Key Extraction), posing risks such as Remote Code Execution, Authorization Bypass, Denial of Service, and potential private key compromise.
Resolved
#2 critical Issue
Security-Critical Runtime Dependencies Incorrectly Listed as devDependencies
The `argon2`, `generate-password`, `uuid`, `otplib`, and `qrcode` packages are listed in `devDependencies` in `package.json`. However, they are used at runtime in backend utilities (`passwords.ts`, `token.ts`, `otp/...`) for essential security functions. If the application is deployed using standard practices that skip installing devDependencies (e.g., `npm install --production`), these packages will be missing, causing authentication, password reset, and 2FA functionality to fail critically.
Resolved
#3 critical Issue
Insecure Default JWT Secrets
The JWT generation functions (`generateAccessToken`, `generateRefreshToken`, `generateResetToken`) in `backend/utils/token.ts` fall back to using the static, predictable value `"secret"` if the corresponding environment variables (`APP_ACCESS_TOKEN_SECRET`, `APP_REFRESH_TOKEN_SECRET`, `APP_RESET_TOKEN_SECRET`) are not set. This allows anyone knowing the default secret to forge valid JWTs (access, refresh, reset tokens), leading to complete account compromise.
Resolved
#4 critical Issue
Plaintext Storage of 2FA/OTP Secrets
The `/api/auth/otp/save` endpoint stores the user's 2FA/TOTP secret directly in plaintext in the `twoFactor` database table (`secret` column). The `/api/auth/otp/login` endpoint retrieves and uses this plaintext secret for verification. TOTP secrets are sensitive cryptographic keys. Storing them unencrypted means that a database breach would compromise all users' 2FA protection, allowing attackers who also have passwords to bypass 2FA entirely.
Resolved
#5 critical Issue
Plaintext Exposure of Generated Wallet Private Key and Mnemonic
The `createWallet` function in `backend/blockchains/sol.ts` generates a new Solana keypair but returns the plaintext `privateKey` (hex) and `mnemonic` in the result object. If the caller of this function returns this object directly or stores it insecurely, the user's private key and mnemonic are compromised, leading to complete loss of funds in that wallet.
Resolved
#6 critical Issue
Key Management Security Relies on Environment Variables (Reinforcement)
The security of all Solana operations involving private keys relies on the `decrypt` function from `backend/utils/encrypt.ts`, which in turn depends on the `dynamicEncryptionKey` derived from `ENCRYPTED_ENCRYPTION_KEY` and `ENCRYPTION_KEY_PASSPHRASE` environment variables.
Resolved
#7 critical Issue
Insecure Storage/Handling of Exchange API Keys via Environment Variables
The `ExchangeManager` in `backend/utils/exchange.ts` retrieves sensitive API keys, secrets, and passphrases for crypto exchanges directly from environment variables. Storing these highly sensitive credentials solely in environment variables makes them vulnerable to exposure through various means. Compromise of these keys can lead to direct theft of funds held by the application on the configured exchanges.
Resolved
#8 critical Issue
Potential Privilege Escalation via Demo Status Environment Variable
The user registration endpoint (`backend/api/auth/register/index.post.ts`) and Google registration endpoint (`backend/api/auth/register/google.post.ts`) assign the 'Admin' role to newly registered users if the `NEXT_PUBLIC_DEMO_STATUS` environment variable is set to 'true'. If this variable is inadvertently left enabled in a production environment, any user registering through these forms can gain administrative privileges.
Resolved
#9 critical Issue
Plaintext Exposure of Generated TON Wallet Private Key and Mnemonic
The `createWallet` function in `backend/blockchains/ton.ts` generates a new TON keypair using `tonweb-mnemonic` but returns the plaintext `mnemonic` and `privateKey` (hex) in the result object. If the caller of this function returns this object directly or stores it insecurely, the user's private key and mnemonic are compromised, leading to complete loss of funds in that wallet.
Resolved
#10 critical Issue
Plaintext Storage of Tron Wallet Private Key and Mnemonic
The `createWallet` function in `backend/blockchains/tron.ts` generates a new Tron keypair but returns the plaintext `privateKey` (hex) and `mnemonic` in the result object. If the caller of this function returns this object directly or stores it insecurely, the user's private key and mnemonic are compromised, leading to complete loss of funds in that wallet.
Resolved
#11 critical Issue
Insecure License Verification System with Remote Code Execution Risk
The admin license verification system in `admin/system/utils.ts` downloads and extracts ZIP files from a remote API, then uses `AdmZip` to extract them directly to the application root path (`rootPath`). If the license server is compromised, this could lead to a remote code execution vulnerability, as malicious code in the ZIP could be executed with the application's privileges.
Resolved
#12 critical Issue
Insecure Database Backup and Restore Implementation
The database backup and restore functionality in `admin/system/database` performs highly sensitive operations with insufficient security controls. The restore endpoint accepts a file path from user input and performs `DROP DATABASE` followed by recreation, which could lead to complete data loss if exploited. The implementation lacks additional authentication specific to destructive operations.
high Issues | 18 findings
Resolved
#1 high Issue
Missing CSRF Token Verification and Frontend Implementation Renders Protection Ineffective
The application generates a `csrfToken` on the backend and likely intends to use the Double Submit Cookie pattern for CSRF protection. However, the frontend code does not appear to include this token in a custom header (e.g., `X-CSRF-Token`) on state-changing requests. Furthermore, the backend lacks the middleware or explicit checks needed to compare the token from the (missing) header against the token stored in the user's session.
Resolved
#2 high Issue
Potential Stored Cross-Site Scripting (XSS) via dangerouslySetInnerHTML
The application uses `dangerouslySetInnerHTML` in multiple locations (product descriptions, blog content, builder elements, potentially static pages and admin areas) to render HTML content. If the HTML being rendered originates from untrusted sources and is not properly sanitized, attackers could inject malicious scripts that would execute in the browsers of other users viewing the content.
Resolved
#3 high Issue
Broken or Missing Token Refresh Logic
The backend endpoint `/api/auth/session` is intended to be used by the frontend middleware to refresh expired access tokens. However, the implementation is incorrect: it does not validate any refresh token or session ID, nor does it generate a new access token. It simply returns the (potentially expired) access token from the incoming request.
Resolved
#4 high Issue
Missing Crypto Address Validation Allows Fund Loss
The spot crypto withdrawal endpoint (`/api/finance/withdraw/spot`) does not validate the format or checksum of the destination `toAddress` based on the specified `currency` and `chain`. Users can submit requests with incorrectly formatted addresses, which may be accepted by the API and potentially the downstream exchange API, leading to irreversible loss of funds.
Resolved
#5 high Issue
Lack of Backend Rate Limiting
The backend server does not appear to implement global rate limiting for incoming HTTP requests or WebSocket connections. Specific endpoints like login and OTP verification also lack targeted rate limiting beyond basic account lockout for password attempts. Without rate limiting, the application is vulnerable to Denial-of-Service attacks through resource exhaustion and brute-force attacks against authentication or other sensitive endpoints.
Resolved
#6 high Issue
Raw SQL Query Vulnerabilities (Placeholder for potential issues)
Multiple files contain direct `sequelize.query` or `sequelize.literal` usage, which could potentially allow SQL injection if user input is concatenated or interpolated directly into these queries.
Resolved
#7 high Issue
Lack of Comprehensive Error Handling in Financial Endpoints
The financial endpoints (withdraw/deposit) have incomplete error handling for various failure scenarios (e.g., exchange API errors, network timeouts, internal DB errors). This could lead to inconsistent state between the application database and the exchange, potentially causing financial discrepancies.
Resolved
#8 high Issue
Arbitrary File Deletion via Path Traversal in Upload Endpoint
The `/api/upload/` endpoint takes an optional `oldPath` parameter intended for removing a previous file (e.g., an old avatar). However, this `oldPath` is joined directly with the project's root path and `public` directory before being passed to `fs.unlink` without proper sanitization or validation. An authenticated attacker can provide a crafted path (e.g., using `../` sequences) to delete arbitrary files outside the intended `public/uploads` directory, limited only by the web server's file system permissions.
Resolved
#9 high Issue
Risk of Duplicate Deposit Processing in Clustered Environments (TON)
The TON deposit monitoring logic in `backend/blockchains/ton.ts` (`monitorTonDeposits`) uses static in-memory Maps (`TonService.monitoringAddresses`, `TonService.processedTransactions`) to track which addresses are being watched and which transactions have recently been processed. This state is not shared between different node processes or worker threads. If the backend runs multiple instances (clustering), multiple instances could simultaneously detect and attempt to process the same incoming deposit transaction, potentially leading to duplicate credits or other inconsistencies.
Resolved
#10 high Issue
Race Condition in Monero Transaction Processing
The `MoneroService` in `backend/blockchains/xmr.ts` uses in-memory Maps to track processed transactions and monitored wallets. In a clustered environment with multiple Node.js processes, this could lead to race conditions where the same transaction is processed multiple times, potentially leading to duplicate credits or processing errors.
Resolved
#11 high Issue
Insecure WebSocket Authentication Implementation
The WebSocket setup in `backend/server.ts` and related code does not provide clear authentication and authorization validation for WebSocket connections. This could allow unauthorized users to establish WebSocket connections and receive or send sensitive data.
Resolved
#12 high Issue
Missing Transaction Isolation in Fiat Operations
The fiat deposit and withdrawal endpoints don't implement proper transaction isolation for financial operations. In `withdraw/fiat/index.post.ts`, wallet balance checks and deductions are performed without proper table locking, creating potential race conditions for concurrent withdrawals from the same wallet.
Resolved
#13 high Issue
Insufficient Rate Limiting for Financial Operations
The fiat deposit and withdrawal endpoints (`deposit/fiat/index.post.ts` and `withdraw/fiat/index.post.ts`) lack rate limiting for financially sensitive operations, opening the door to potential DoS attacks against user wallets or brute force attempts with different parameters.
Resolved
#14 high Issue
Incomplete Account Deletion Logic
The account deletion implementation in `auth/delete/confirm.post.ts` uses a simple `models.user.destroy()` call that may leave orphaned data in related tables due to insufficient cleanup logic, potentially leading to privacy violations or data inconsistencies.
Resolved
#15 high Issue
Inadequate Validation in Wallet Transfer Functions
The wallet transfer functionality in `backend/api/finance/transfer/index.post.ts` lacks proper input validation for `fromCurrency`, `toCurrency`, and `amount` parameters. This could allow manipulation of transfer operations, especially when combined with the race conditions already identified. The code checks if the wallet has sufficient balance but doesn't validate currency precision or limits.
Resolved
#16 high Issue
Lack of Transaction Isolation in Admin Transaction Status Updates
The admin transaction status update endpoint in `backend/api/admin/finance/transaction/status.put.ts` lacks proper transaction isolation when updating transaction status and wallet balance. The code fetches the transaction and wallet separately and then modifies the wallet balance outside of a transaction block, creating a race condition that could lead to inconsistent financial state if multiple admins update different transactions simultaneously.
Resolved
#17 high Issue
Hardcoded Default Password in Admin User Creation
The admin user creation endpoint in `backend/api/admin/crm/user/index.post.ts` assigns a hardcoded, predictable default password ('12345678') to all newly created users. This password is not only weak but is also exposed in error messages and potentially logs, creating a significant security risk as newly created accounts could be compromised before users change their passwords.
Resolved
#18 high Issue
Potential Information Disclosure / DoS via Unrestricted Dynamic Filtering
The `getFiltered` utility (`backend/utils/query.ts`) allows filtering database records based on a JSON object provided in query parameters. This mechanism does not appear to restrict *which* fields can be filtered on or which comparison operators can be used. An attacker could potentially filter on sensitive, unindexed fields to infer data or use complex operators/patterns to cause database Denial-of-Service.
medium Issues | 31 findings
Resolved
#1 medium Issue
Missing Security Headers
The application's Next.js middleware or backend server does not set crucial HTTP security headers such as Content-Security-Policy (CSP), HTTP Strict Transport Security (HSTS), X-Content-Type-Options, Referrer-Policy, and Permissions-Policy. The absence of these headers increases the risk of various attacks, including Cross-Site Scripting, clickjacking, MIME-type sniffing, and information leakage.
Resolved
#2 medium Issue
Potential Authorization Bypass due to Stale Permissions Cache
The Next.js middleware fetches user roles and permissions from the (unauthenticated) `/api/auth/role` endpoint and caches them indefinitely in memory (`rolesCache`). If roles or permissions are updated on the backend, the middleware will continue operating with stale data until a server restart or fetch failure occurs. This could allow users to retain access they should no longer have or prevent them from accessing newly granted resources.
Resolved
#3 medium Issue
Potential Authorization Flaws in Middleware Logic
Authorization in `src/middleware.ts` relies on a static mapping in `src/utils/gate.ts` and defaults unmapped `/admin/*` routes to requiring "Access Admin Dashboard". This is brittle; new routes might be added without corresponding entries, leading to incorrect permission enforcement. The check `pathname in gate` might miss dynamic routes if not carefully managed. Relying solely on the `payload.sub.role` numeric ID from the JWT without further backend validation for the specific resource being accessed could be risky.
Resolved
#4 medium Issue
Unauthenticated Endpoint Exposes Full Role and Permission Structure
The `/api/auth/role` endpoint, which is used by the frontend middleware to determine authorization rules, is publicly accessible (`requiresAuth: false`). It returns a complete list of all roles defined in the system along with all permissions associated with each role. This leaks potentially sensitive information about the application's internal access control model to unauthenticated users, aiding attackers in understanding the privilege system.
Resolved
#5 medium Issue
Weak Ajv Configuration May Hide Schema Errors and Allow Insecure Inputs
The Ajv configuration in `backend/utils/ajv.ts` disables strict mode (`strict: "log"`), potentially hiding schema errors or ambiguities. It also uses potentially insecure custom formats for `uri` (mixing relative paths and absolute URIs) and `date` (relying on unreliable `Date.parse`). The `useDefaults: true` setting might also mask incomplete input data issues.
Resolved
#6 medium Issue
Missing Brute-Force Protection on 2FA Verification
The `/api/auth/otp/login` endpoint lacks specific protection against brute-force attacks. An attacker who has compromised a user's password could repeatedly attempt to guess the 6-digit OTP code by calling this endpoint multiple times within the code's validity window. There is no mechanism to lock the account or slow down attempts after several failures.
Resolved
#7 medium Issue
Potential DoS via Memory Exhaustion in Static File Serving
The `serveStaticFile` function in `backend/utils/index.ts` reads the entire requested file into memory using `fs.readFileSync` before sending the response. If an attacker can request legitimate but extremely large files, they could cause the server to consume excessive memory, leading to a Denial-of-Service condition.
Resolved
#8 medium Issue
Missing Withdrawal Amount/Precision Validation
The withdrawal endpoint (`/api/finance/withdraw/spot`) does not validate the requested `amount` against the currency's allowed decimal precision or minimum/maximum withdrawal limits. Submitting amounts with incorrect precision could lead to calculation errors or failures at the exchange level.
Resolved
#9 medium Issue
Potential Race Condition in Withdrawal Balance Check/Deduction
The withdrawal endpoint (`/api/finance/withdraw/spot`) checks the user's wallet balance and calculates the deduction amount *before* starting the database transaction that locks the wallet row and performs the update. Concurrent withdrawal requests for the same user/wallet could potentially both read the balance before either request deducts funds.
Resolved
#10 medium Issue
Incorrect Handling/Return of Secret in SMS/Email 2FA Setup
The `/api/auth/otp/generate` endpoint, when handling requests for SMS or Email 2FA types, generates a long-lived TOTP secret, generates a single OTP code from it, sends the code via SMS/Email, and then returns the long-lived secret back to the client in the API response. This is incorrect for typical SMS/Email code verification flows.
Resolved
#11 medium Issue
Implicit Type Coercion Weakens Input Validation
The `validateSchema` function in `backend/utils/validation.ts` uses a helper `convertBooleanStrings` to automatically convert case-insensitive `"true"` and `"false"` strings to boolean types *before* validating the input against the provided JSON schema. This implicit coercion bypasses strict type checking, allowing string inputs where booleans might be expected according to the schema.
Resolved
#12 medium Issue
Potentially Sensitive User Data in JWT Payload
The JWT generation functions in `backend/utils/token.ts` originally included the entire `user` object in the `sub` claim. Although `backend/api/auth/utils.ts` (`returnUserWithTokens`) correctly creates a `publicUser` with only `id` and `roleId` for *some* token generation flows (login/reset), other direct calls to `generateAccessToken`, `generateRefreshToken`, etc., might still embed the full user object if not refactored.
Resolved
#13 medium Issue
Insecure Chain Activation Check via Local File Existence
The `SolanaService` in `backend/blockchains/sol.ts` determines if the Solana integration is active by checking for the existence of a file named `sol.bin` within its own directory. This method is unreliable, insecure, and easily manipulated or broken by deployment configurations or file system changes. It does not provide a meaningful security or configuration control.
Resolved
#14 medium Issue
Insufficient Logging for Critical Financial Operations
The spot withdrawal endpoint lacks comprehensive logging of critical operations such as user identification, amounts, addresses, and decision points in the process flow. This impedes auditing, forensic analysis, and detection of suspicious activities or system failures.
Resolved
#15 medium Issue
Missing Rate Limiting on User Registration Endpoint
The user registration endpoint (`backend/api/auth/register/index.post.ts`) lacks rate limiting. This allows attackers to perform user enumeration by repeatedly attempting to register with different email addresses to see which ones return an 'Email already in use' error. It also enables attackers to potentially flood the system with fake user accounts, leading to resource exhaustion (database bloat, potential email sending costs) and denial of service for legitimate users.
Resolved
#16 medium Issue
Lack of Input Sanitization for User Names during Registration
The registration endpoint (`backend/api/auth/register/index.post.ts`) accepts `firstName` and `lastName` parameters but does not appear to perform explicit input sanitization before storing them in the database. If these names are displayed elsewhere in the application without proper output encoding or sanitization, this could lead to Stored Cross-Site Scripting (XSS) vulnerabilities.
Resolved
#17 medium Issue
Insecure Chain Activation Check via Local File Existence (TON)
The `TonService` in `backend/blockchains/ton.ts` determines if the TON integration is active by checking for the existence of a file named `ton.bin` within its own directory using `fs.readdirSync`. This method is unreliable, insecure, easily manipulated, and duplicates the flawed logic found in `sol.ts` (Finding #30).
Resolved
#18 medium Issue
Lack of Input Sanitization for User Names during Registration
The registration endpoint (`backend/api/auth/register/index.post.ts`) accepts `firstName` and `lastName` parameters but does not perform explicit input sanitization before storing them in the database. If these names are displayed elsewhere in the application without proper output encoding or sanitization, this could lead to Stored Cross-Site Scripting (XSS) vulnerabilities.
Resolved
#19 medium Issue
Insecure Chain Activation Check via Local File Existence in Tron Service
The `TronService` in `backend/blockchains/tron.ts` determines if the Tron integration is active by checking for the existence of a file named `tron.bin` within its own directory using `readdirSync`. This method is unreliable, insecure, and easily manipulated by simply creating the file in the appropriate directory, potentially enabling unauthorized use of blockchain features.
Resolved
#20 medium Issue
Missing File Type Validation in Upload Endpoint
The file upload endpoint in `backend/api/upload/index.post.ts` determines file type solely based on the MIME type in the base64 data. This approach is vulnerable to MIME type spoofing where an attacker can modify the MIME type string while uploading a malicious file. The endpoint does handle certain file types differently but lacks proper content validation.
Resolved
#21 medium Issue
Outdated Google Authentication Implementation
The implementation in `backend/api/auth/login/google.post.ts` attempts to verify Google tokens through both `verifyIdToken` and fetching user info with access tokens, but lacks proper error handling and validation. It also doesn't validate critical fields in the ID token such as audience and issuer.
Resolved
#22 medium Issue
Inadequate Exception Handling in Wallet Creation Functions
Both the Tron and Monero wallet creation functions in their respective services lack comprehensive exception handling, potentially leading to incomplete wallet creation, data loss, or exposing sensitive information in error messages.
Resolved
#23 medium Issue
Insecure Email Token Generation for Account Deletion
The account deletion confirmation in `auth/delete/index.post.ts` uses a potentially insecure token generation mechanism without proper expiration controls, throttling, or rate limiting on token requests. This could allow attackers to spam deletion requests or use tokens that remain valid for too long.
Resolved
#24 medium Issue
Environment Variable Leakage in Admin Error Messages
Several admin endpoints, especially in `admin/system`, expose sensitive environment variable information in error messages when configuration is incomplete. For example, the `checkEnvVariables` function in database endpoints directly names missing environment variables in error messages, which could aid attackers in understanding the system configuration.
Resolved
#25 medium Issue
WebSocket Message Handling Without Origin Validation
The WebSocket state management in `src/stores/trade/ws.ts` doesn't validate the origin of incoming messages. While WebSockets should use the browser's same-origin policy, additional validation would protect against potential message injection if the WebSocket server is compromised or if there are browser security vulnerabilities.
Resolved
#26 medium Issue
Unsafe JSON Parsing in UI Builder
The UI Builder component in `src/components/builder/editor/Editor.tsx` performs unsafe JSON parsing of user-provided template data. If the JSON parsing fails, it defaults to a template, but the try-catch block could be bypassed in certain browser environments, potentially leading to client-side code execution if malicious data is provided.
Resolved
#27 medium Issue
Missing Authorization Controls in ICO Phase Status Updates
The ICO extension in `backend/api/ext/ico/utils.ts` allows automatic updating of token phase status based on dates, but lacks explicit authorization checks before modifying phase statuses. The `updatePhaseStatus` function can be called without proper privilege verification, potentially allowing manipulation of ICO phase status through indirect means.
Resolved
#28 medium Issue
Insufficient Error Handling in Wallet Cron Jobs
The wallet cron jobs in `backend/utils/crons/wallet.ts` have insufficient error handling, particularly in `processWalletPnl` and `processSpotPendingDeposits`. When errors occur, these functions may fail silently or leave operations in an inconsistent state. The functions also lack proper retry mechanisms for transient failures in external API calls.
Resolved
#29 medium Issue
Inadequate Data Validation in User Model
The user model in `models/user.ts` has insufficient validation for critical fields like `firstName`, `lastName`, and `avatar`. The validation for names only checks that they contain letters but doesn't properly restrict potentially harmful characters. The avatar validation uses a weak regex that could potentially be bypassed.
Resolved
#30 medium Issue
Missing Environment Configuration Validation
The application lacks a centralized environment variable validation mechanism. Various components make assumptions about environment variables being present but only check them at runtime when they're already needed. This could lead to unpredictable behavior or security issues if critical environment variables are missing or improperly configured.
Resolved
#31 medium Issue
Use of Insecure Random Number Generator for Email Codes
The `generateEmailCode` function (`backend/utils/token.ts`) uses `Math.random()` to generate 6-digit verification codes. `Math.random()` is not cryptographically secure and can be predictable, potentially allowing attackers to guess valid codes more easily than expected.
low Issues | 3 findings
Resolved
#1 low Issue
Use of Symmetric Algorithm (HS256) for JWTs
All JWTs (access, refresh, reset) are signed using the symmetric HS256 algorithm. This requires the same secret to be present for both signing and verification. Asymmetric algorithms (like RS256 or ES256) provide better security posture by allowing verification using a public key that doesn't grant signing capabilities.
Resolved
#2 low Issue
Insecure CORS Configuration (Hardcoded Origins)
The `allowedOrigins` array in `backend/utils/index.ts` is hardcoded to only allow `localhost` on specific ports. This configuration is insecure for deployment environments as it will block all legitimate cross-origin requests from the deployed frontend application URL. Conversely, if modified incorrectly during deployment (e.g., to `*`), it could expose the backend to requests from unintended origins.
Resolved
#3 low Issue
Sensitive Data Exposure in Frontend Wallet Store
The `src/stores/user/wallet/index.ts` state store caches wallet balances and transaction details client-side without proper security controls. This sensitive financial data could be exposed to XSS attacks or other client-side vulnerabilities, leading to potential privacy violations.
informational Issues | 1 findings
Resolved
#1 informational Issue
Insecure Password Reset Mechanism Exposes Plaintext Passwords (Function Exists)
The `generateNewPassword` function generates a new plaintext password, hashes it, updates the user's record in the database, and then returns the plaintext password to the caller. Returning the plaintext password allows it to be potentially logged or transmitted insecurely. While this function was not found to be used in the primary user-facing password reset flow, its existence poses a risk if called from other locations.