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.

BESC Logo

Team and KYC Verification

The team has securely submitted their personal information to SolidProof.io for verification.

In the event of any fraudulent activities, this information will be promptly reported to the relevant authorities to ensure accountability and compliance.

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.

100.00
Poor Excellent

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

"Static Analysis Dynamic Analysis Symbolic Execution SWC Check Manual Review API Pentesting"
Contract address
N/A
Network N/A
License N/A
Compiler N/A
Type N/A
Language JavaScript / TypeScript
Onboard date 2025/04/25
Revision date 2025/04/25

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:

  1. Automated Tool Analysis: Run our proprietary, optimized scanner across the entire JS/TS codebase to detect common vulnerabilities, insecure patterns, and dependency issues.
  2. 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.
  3. Architectural & Dependency Assessment: Verify that project structure, module boundaries, and third-party libraries follow best-practice patterns for maintainability and minimal attack surface.
  4. Specification Alignment: Confirm that implemented functionality matches customer requirements and design documents, with no hidden or undocumented features.
  5. Static Analysis Coverage Review: Evaluate existing unit and integration tests for coverage gaps; recommend additional tests for untested or under-tested paths.
  6. Dynamic & Symbolic Execution: Exercise edge cases via symbolic analysis to validate input handling, boundary conditions, and error paths in critical functions.
  7. API Pentesting: Perform authenticated and unauthenticated penetration tests against all REST/WebSocket endpoints, including fuzzing, rate-limit bypass, and business-logic abuse scenarios.
  8. Best Practices Evaluation: Benchmark against JavaScript/TypeScript security guidelines (OWASP Top 10, Snyk recommendations, Node.js hardening) to improve resilience, performance, and maintainability.
  9. 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 Error throws; 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
  1. JWT & 2FA Security:
    • Migrate to asymmetric JWT signing (RS256/ES256).
    • Encrypt TOTP/2FA secrets at rest; never store or return plaintext keys.
  2. Web & API Protection:
    • Implement CSRF tokens end-to-end (cookie + header verification).
    • Sanitize every use of dangerouslySetInnerHTML with a library like DOMPurify.
    • Configure CORS origins via environment-driven allowlists.
  3. Financial Transaction Integrity:
    • Use sequelize.transaction with FOR UPDATE locks for all balance updates.
    • Replace file-based vesting/presale data stores with transactional database tables or distributed locks.
  4. Error Handling & Observability:
    • Introduce a shared error framework with custom exception types.
    • Instrument structured logging (user IDs, request IDs, error contexts).
  5. 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
package.json, package-lock.json
-
Description

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
package.json, backend/utils/passwords.ts, backend/utils/token.ts, backend/api/auth/otp/
-
Description

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
backend/utils/token.ts
L86,102,126,145,191,209,228
Description

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
backend/api/auth/otp/save.post.ts, backend/api/auth/otp/login.post.ts
L92-108,111-128
Description

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
backend/blockchains/sol.ts
L108-131
Description

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)
backend/utils/encrypt.ts, backend/blockchains/sol.ts
-
Description

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
backend/utils/exchange.ts
-
Description

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
backend/api/auth/register/index.post.ts, backend/api/auth/register/google.post.ts
L130-132
Description

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
backend/blockchains/ton.ts
L373-397
Description

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
backend/blockchains/tron.ts
L125-146
Description

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
backend/api/admin/system/utils.ts
L321-389,391-394
Description

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
backend/api/admin/system/database/backup/index.post.ts, backend/api/admin/system/database/restore/index.post.ts
LMultiple
Description

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
backend/handler/Middleware.js, src/utils/api.ts
L237-270
Description

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
src/components/builder/editor/Editor.tsx, src/components/elements/base/content.tsx
LMultiple
Description

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
backend/api/auth/session.get.ts
-
Description

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
backend/api/finance/withdraw/spot/index.post.ts
-
Description

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
backend/server.ts
-
Description

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)
seeders/*, backend/api/finance/currency/[type]/[code]/index.get.ts, backend/api/finance/investment/[id]/index.del.ts, backend/api/ext/ecommerce/order/index.post.ts, backend/api/ext/p2p/trade/[id]/cancel.post.ts, backend/utils/eco/wallet.ts
LMultiple
Description

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
backend/api/finance/withdraw/spot/index.post.ts, backend/api/finance/deposit/spot/index.post.ts
LMultiple
Description

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
backend/api/upload/index.post.ts
L141-151
Description

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)
backend/blockchains/ton.ts
-
Description

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
backend/blockchains/xmr.ts
-
Description

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
backend/server.ts
-
Description

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
backend/api/finance/deposit/fiat/index.post.ts, backend/api/finance/withdraw/fiat/index.post.ts
-
Description

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
backend/api/finance/deposit/fiat/index.post.ts, backend/api/finance/withdraw/fiat/index.post.ts
-
Description

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
backend/api/auth/delete/confirm.post.ts
L101
Description

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
backend/api/finance/transfer/index.post.ts
LMultiple
Description

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
backend/api/admin/finance/transaction/status.put.ts
-
Description

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
backend/api/admin/crm/user/index.post.ts, backend/api/admin/crm/user/utils.ts
L51
Description

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
backend/utils/query.ts
-
Description

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
src/middleware.ts
-
Description

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
src/middleware.ts, backend/api/auth/role.get.ts
-
Description

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
src/middleware.ts, src/utils/gate.ts
-
Description

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
backend/api/auth/role.get.ts
-
Description

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
backend/utils/ajv.ts
-
Description

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
backend/api/auth/otp/login.post.ts
-
Description

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
backend/utils/index.ts
L354-412
Description

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
backend/api/finance/withdraw/spot/index.post.ts
-
Description

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
backend/api/finance/withdraw/spot/index.post.ts
-
Description

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
backend/api/auth/otp/generate.post.ts
-
Description

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
backend/utils/validation.ts
L17-27
Description

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
backend/utils/token.ts, backend/api/auth/utils.ts
-
Description

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
backend/blockchains/sol.ts
L82
Description

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
backend/api/finance/withdraw/spot/index.post.ts
LOverall
Description

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
backend/api/auth/register/index.post.ts
-
Description

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
backend/api/auth/register/index.post.ts
-
Description

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)
backend/blockchains/ton.ts
L105-122
Description

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
backend/api/auth/register/index.post.ts
-
Description

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
backend/blockchains/tron.ts
L95
Description

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
backend/api/upload/index.post.ts
-
Description

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
backend/api/auth/login/google.post.ts
-
Description

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
backend/blockchains/tron.ts, backend/blockchains/xmr.ts
-
Description

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
backend/api/auth/delete/index.post.ts
L75
Description

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
backend/api/admin/system/utils.ts, backend/api/admin/system/database/backup/index.post.ts, backend/api/admin/system/database/restore/index.post.ts
LMultiple
Description

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
src/stores/trade/ws.ts
-
Description

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
src/components/builder/editor/Editor.tsx
-
Description

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
backend/api/ext/ico/utils.ts
-
Description

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
backend/utils/crons/wallet.ts, backend/utils/crons/staking.ts
-
Description

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
models/user.ts
-
Description

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
.env*, backend/server.ts
-
Description

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
backend/utils/token.ts
-
Description

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
backend/utils/token.ts
-
Description

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)
backend/utils/index.ts
-
Description

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
src/stores/user/wallet/index.ts
-
Description

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)
backend/utils/passwords.ts, backend/api/auth/utils.ts
-
Description

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.