security: remove .env from tracking (contains secrets)
This commit is contained in:
@@ -1,21 +1,29 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { db } from '../config/database';
|
||||
import { WalletModel } from '../models/wallet.model';
|
||||
import { UserModel } from '../models/user.model';
|
||||
import { getBalance, getTransactions, buildSend } from '../services/wallet-ops.service';
|
||||
import { getBalance, getTransactions } from '../services/wallet-ops.service';
|
||||
import { isValidAddress, isValidAmount, ChainCode } from '../lib/address-validators';
|
||||
import { generateMnemonic, deriveAllAddresses, ALL_CHAINS } from '../services/wallet-generator.service';
|
||||
import { encryptMnemonic, decryptMnemonic, isCryptoReady } from '../services/crypto.service';
|
||||
import { signAndBroadcast } from '../services/wallet-signer.service';
|
||||
import { auditLog } from '../lib/audit-log';
|
||||
import { logger } from '../lib/logger';
|
||||
|
||||
const ALLOWED_CHAINS = new Set<ChainCode>(['ETH', 'BTC', 'SOL', 'TRX', 'BSC']);
|
||||
const MAX_WALLETS_PER_REQUEST = 20;
|
||||
const MAX_DERIVATION_PATH = 64;
|
||||
const ALLOWED_CHAINS = new Set<ChainCode>(ALL_CHAINS);
|
||||
const MAX_TX_LIMIT = 100;
|
||||
|
||||
class ConflictError extends Error {
|
||||
constructor() { super('Wallet already exists'); }
|
||||
}
|
||||
|
||||
function isChain(value: unknown): value is ChainCode {
|
||||
return typeof value === 'string' && ALLOWED_CHAINS.has(value as ChainCode);
|
||||
}
|
||||
|
||||
export const WalletController = {
|
||||
/**
|
||||
* GET /api/wallets — все кошельки юзера
|
||||
* GET /api/wallets — все адреса юзера (chain + address + derivationPath).
|
||||
*/
|
||||
async getWallets(req: Request, res: Response) {
|
||||
try {
|
||||
@@ -28,76 +36,167 @@ export const WalletController = {
|
||||
derivationPath: w.derivation_path,
|
||||
})),
|
||||
});
|
||||
} catch {
|
||||
} catch (err: any) {
|
||||
logger.error(`getWallets failed for user ${req.auth!.userId}: ${err.stack || err.message}`);
|
||||
res.status(500).json({ success: false, error: 'Internal error' });
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* POST /api/wallets — upsert массива кошельков для юзера из JWT.
|
||||
* POST /api/wallets/create — custodial wallet bootstrap.
|
||||
*
|
||||
* 1) Проверка: у юзера ещё нет коша (иначе 409)
|
||||
* 2) Генерим BIP39 mnemonic (128 bit, 12 слов)
|
||||
* 3) Деривим адреса для всех 5 chains
|
||||
* 4) Шифруем mnemonic AES-GCM (master-key из Vault)
|
||||
* 5) Транзакционно пишем encrypted_mnemonic + wallets
|
||||
* 6) Возвращаем ТОЛЬКО адреса. Mnemonic клиенту не отдаём.
|
||||
*/
|
||||
async createWallets(req: Request, res: Response) {
|
||||
async createWallet(req: Request, res: Response) {
|
||||
const userId = req.auth!.userId;
|
||||
const { wallets } = req.body ?? {};
|
||||
|
||||
if (!Array.isArray(wallets) || wallets.length === 0 || wallets.length > MAX_WALLETS_PER_REQUEST) {
|
||||
if (!isCryptoReady()) {
|
||||
res.status(503).json({ success: false, error: 'Crypto service not ready' });
|
||||
return;
|
||||
}
|
||||
|
||||
let mnemonic: string | null = null;
|
||||
try {
|
||||
await UserModel.ensureExists(userId);
|
||||
|
||||
// Сначала проверка для быстрого 409 (не атомарна — реальная защита ниже)
|
||||
if (await UserModel.hasMnemonic(userId)) {
|
||||
res.status(409).json({ success: false, error: 'Wallet already exists' });
|
||||
return;
|
||||
}
|
||||
|
||||
mnemonic = generateMnemonic();
|
||||
const derived = await deriveAllAddresses(mnemonic);
|
||||
const blob = encryptMnemonic(mnemonic);
|
||||
|
||||
// ── АТОМАРНО: UPDATE users WHERE encrypted_mnemonic IS NULL + INSERT wallets ──
|
||||
// Защита от funds-loss race: если параллельный запрос успел проставить mnemonic,
|
||||
// наш UPDATE вернёт affected=0 → откатываем транзакцию, возвращаем 409.
|
||||
const created = await db.transaction(async (trx) => {
|
||||
const claimed = await UserModel.setEncryptedMnemonicIfAbsent(userId, blob, trx);
|
||||
if (!claimed) {
|
||||
// Кто-то другой выиграл race — наш mnemonic становится бессмысленным
|
||||
throw new ConflictError();
|
||||
}
|
||||
await WalletModel.createMany(
|
||||
derived.map((w) => ({
|
||||
user_id: userId,
|
||||
chain: w.chain,
|
||||
address: w.address,
|
||||
derivation_path: w.derivationPath,
|
||||
})),
|
||||
trx,
|
||||
);
|
||||
return derived;
|
||||
});
|
||||
|
||||
await auditLog({
|
||||
event: 'wallet.create',
|
||||
userId,
|
||||
ip: req.ip || null,
|
||||
result: 'success',
|
||||
meta: { chains: created.map((w) => w.chain) },
|
||||
});
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
data: created.map((w) => ({
|
||||
chain: w.chain,
|
||||
address: w.address,
|
||||
derivationPath: w.derivationPath,
|
||||
})),
|
||||
});
|
||||
} catch (err: any) {
|
||||
if (err instanceof ConflictError) {
|
||||
res.status(409).json({ success: false, error: 'Wallet already exists' });
|
||||
return;
|
||||
}
|
||||
logger.error(`createWallet failed for user ${userId}: ${err.message}`);
|
||||
await auditLog({
|
||||
event: 'wallet.create',
|
||||
userId,
|
||||
ip: req.ip || null,
|
||||
result: 'failure',
|
||||
errorCode: err.code || 'INTERNAL',
|
||||
});
|
||||
res.status(500).json({ success: false, error: 'Failed to create wallet' });
|
||||
} finally {
|
||||
mnemonic = null; // best-effort GC hint
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* POST /api/wallets/mnemonic/reveal — reveal mnemonic для settings-страницы.
|
||||
*
|
||||
* Защита (defense-in-depth):
|
||||
* 1. POST (CSRF token обязателен)
|
||||
* 2. Тело должно содержать { confirm: "I_UNDERSTAND_SEED_IS_SECRET" } — защита
|
||||
* от случайного XHR / image-tag / CSRF-attack which forge только URL
|
||||
* 3. Rate-limit 5/час per-user
|
||||
* 4. Audit-log на каждый вызов (success + failure)
|
||||
*/
|
||||
async revealMnemonic(req: Request, res: Response) {
|
||||
const userId = req.auth!.userId;
|
||||
|
||||
if (!isCryptoReady()) {
|
||||
res.status(503).json({ success: false, error: 'Crypto service not ready' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Confirmation token защищает от случайных XHR из чужих origin (даже если CSRF
|
||||
// фронтенд сломан, атакующему нужно знать секретную фразу — она задокументирована в API)
|
||||
if (req.body?.confirm !== 'I_UNDERSTAND_SEED_IS_SECRET') {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: `wallets must be a non-empty array (max ${MAX_WALLETS_PER_REQUEST})`,
|
||||
error: 'Missing or invalid confirm token. Send { "confirm": "I_UNDERSTAND_SEED_IS_SECRET" } in body.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
for (const w of wallets) {
|
||||
if (!w || typeof w !== 'object') {
|
||||
res.status(400).json({ success: false, error: 'Invalid wallet entry' });
|
||||
return;
|
||||
}
|
||||
if (!isChain(w.chain)) {
|
||||
res.status(400).json({ success: false, error: 'Invalid chain' });
|
||||
return;
|
||||
}
|
||||
if (!isValidAddress(w.chain, w.address)) {
|
||||
res.status(400).json({ success: false, error: 'Invalid address format for chain' });
|
||||
return;
|
||||
}
|
||||
if (
|
||||
typeof w.derivationPath !== 'string' ||
|
||||
w.derivationPath.length === 0 ||
|
||||
w.derivationPath.length > MAX_DERIVATION_PATH ||
|
||||
!/^m(\/[0-9]+'?)*$/.test(w.derivationPath)
|
||||
) {
|
||||
res.status(400).json({ success: false, error: 'Invalid derivationPath (BIP32 m/.. format expected)' });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await UserModel.ensureExists(userId);
|
||||
const blob = await UserModel.getEncryptedMnemonic(userId);
|
||||
if (!blob) {
|
||||
await auditLog({
|
||||
event: 'mnemonic.reveal',
|
||||
userId,
|
||||
ip: req.ip || null,
|
||||
result: 'failure',
|
||||
errorCode: 'NOT_FOUND',
|
||||
});
|
||||
res.status(404).json({ success: false, error: 'Wallet not created yet' });
|
||||
return;
|
||||
}
|
||||
|
||||
const rows = await WalletModel.upsertMany(
|
||||
wallets.map((w: { chain: ChainCode; address: string; derivationPath: string }) => ({
|
||||
user_id: userId,
|
||||
chain: w.chain,
|
||||
address: w.address,
|
||||
derivation_path: w.derivationPath,
|
||||
}))
|
||||
);
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
data: rows.map((w) => ({
|
||||
chain: w.chain,
|
||||
address: w.address,
|
||||
derivationPath: w.derivation_path,
|
||||
})),
|
||||
const mnemonic = decryptMnemonic(blob);
|
||||
|
||||
await auditLog({
|
||||
event: 'mnemonic.reveal',
|
||||
userId,
|
||||
ip: req.ip || null,
|
||||
result: 'success',
|
||||
});
|
||||
} catch {
|
||||
res.status(500).json({ success: false, error: 'Internal error' });
|
||||
|
||||
res.json({ success: true, data: { mnemonic } });
|
||||
} catch (err: any) {
|
||||
logger.error(`revealMnemonic failed for user ${userId}: ${err.message}`);
|
||||
await auditLog({
|
||||
event: 'mnemonic.reveal',
|
||||
userId,
|
||||
ip: req.ip || null,
|
||||
result: 'failure',
|
||||
errorCode: 'INTERNAL',
|
||||
});
|
||||
res.status(500).json({ success: false, error: 'Failed to reveal mnemonic' });
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* GET /api/wallets/:chain/balance — баланс для адреса юзера в данной chain.
|
||||
* GET /api/wallets/:chain/balance
|
||||
*/
|
||||
async getChainBalance(req: Request, res: Response) {
|
||||
const userId = req.auth!.userId;
|
||||
@@ -117,7 +216,8 @@ export const WalletController = {
|
||||
|
||||
const balance = await getBalance(chain, wallet.address);
|
||||
res.json({ success: true, data: balance });
|
||||
} catch {
|
||||
} catch (err: any) {
|
||||
logger.error(`getChainBalance ${chain} failed for user ${userId}: ${err.stack || err.message}`);
|
||||
res.status(502).json({ success: false, error: 'Upstream RPC error' });
|
||||
}
|
||||
},
|
||||
@@ -145,13 +245,16 @@ export const WalletController = {
|
||||
|
||||
const txs = await getTransactions(chain, wallet.address, limit);
|
||||
res.json({ success: true, data: txs });
|
||||
} catch {
|
||||
} catch (err: any) {
|
||||
logger.error(`getChainTransactions ${chain} failed for user ${userId}: ${err.stack || err.message}`);
|
||||
res.status(502).json({ success: false, error: 'Upstream RPC error' });
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* POST /api/wallets/:chain/send — build unsigned транзакцию.
|
||||
* POST /api/wallets/:chain/send — custodial sign + broadcast.
|
||||
* Сервер расшифровывает мнемонику, деривит privkey, подписывает, broadcast'ит.
|
||||
* Возвращает { txid }.
|
||||
*/
|
||||
async sendFromChain(req: Request, res: Response) {
|
||||
const userId = req.auth!.userId;
|
||||
@@ -162,6 +265,11 @@ export const WalletController = {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isCryptoReady()) {
|
||||
res.status(503).json({ success: false, error: 'Crypto service not ready' });
|
||||
return;
|
||||
}
|
||||
|
||||
const { to, amount, token } = req.body ?? {};
|
||||
|
||||
if (!isValidAddress(chain, String(to))) {
|
||||
@@ -182,6 +290,7 @@ export const WalletController = {
|
||||
normalizedToken = token.toUpperCase();
|
||||
}
|
||||
|
||||
let mnemonic: string | null = null;
|
||||
try {
|
||||
const wallet = await WalletModel.findByUserAndChain(userId, chain);
|
||||
if (!wallet) {
|
||||
@@ -189,21 +298,51 @@ export const WalletController = {
|
||||
return;
|
||||
}
|
||||
|
||||
const tx = await buildSend({
|
||||
const blob = await UserModel.getEncryptedMnemonic(userId);
|
||||
if (!blob) {
|
||||
res.status(404).json({ success: false, error: 'Encrypted mnemonic not found' });
|
||||
return;
|
||||
}
|
||||
|
||||
mnemonic = decryptMnemonic(blob);
|
||||
|
||||
const result = await signAndBroadcast({
|
||||
chain,
|
||||
from: wallet.address,
|
||||
to,
|
||||
amount,
|
||||
mnemonic,
|
||||
to: String(to),
|
||||
amount: String(amount),
|
||||
token: normalizedToken,
|
||||
expectedFromAddress: wallet.address,
|
||||
});
|
||||
|
||||
res.json({ success: true, data: tx });
|
||||
await auditLog({
|
||||
event: 'wallet.send',
|
||||
userId,
|
||||
ip: req.ip || null,
|
||||
result: 'success',
|
||||
meta: { chain, hasToken: !!normalizedToken, txid: result.txid },
|
||||
});
|
||||
|
||||
res.json({ success: true, data: { txid: result.txid, chain } });
|
||||
} catch (err: any) {
|
||||
// Не возвращаем raw upstream message — может содержать sensitive info
|
||||
const safeMsg = err?.message?.toLowerCase().includes('not implemented')
|
||||
? 'Send not supported for this chain/token combination'
|
||||
: 'Failed to build transaction';
|
||||
res.status(502).json({ success: false, error: safeMsg });
|
||||
logger.error(`send failed for user ${userId} chain ${chain}: ${err.message}`);
|
||||
await auditLog({
|
||||
event: 'wallet.send',
|
||||
userId,
|
||||
ip: req.ip || null,
|
||||
result: 'failure',
|
||||
meta: { chain },
|
||||
errorCode: 'BROADCAST_FAILED',
|
||||
});
|
||||
const msg = err?.message?.toLowerCase?.().includes('insufficient')
|
||||
? 'Insufficient balance'
|
||||
: err?.message?.toLowerCase?.().includes('not supported')
|
||||
? 'Token/chain combination not supported'
|
||||
: 'Failed to broadcast transaction';
|
||||
res.status(502).json({ success: false, error: msg });
|
||||
} finally {
|
||||
// Best-effort cleanup mnemonic в RAM
|
||||
mnemonic = null;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user