revert: non-custodial — client supplies addresses+paths to POST /wallets/create

This commit is contained in:
ZOMBIIIIIII
2026-05-11 19:51:10 +03:00
parent 8d91dbeb14
commit c8bc40af97
20 changed files with 122 additions and 1475 deletions

View File

@@ -1,21 +1,15 @@
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 } from '../services/wallet-ops.service';
import { getBalance, getTransactions, buildSend } 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>(ALL_CHAINS);
const ALLOWED_CHAINS = new Set<ChainCode>(['ETH', 'BTC', 'SOL', 'TRX', 'BSC']);
const MAX_WALLETS_PER_REQUEST = 20;
const MAX_DERIVATION_PATH = 64;
const MAX_TX_LIMIT = 100;
class ConflictError extends Error {
constructor() { super('Wallet already exists'); }
}
const BIP32_PATH_RE = /^m(\/[0-9]+'?)*$/;
function isChain(value: unknown): value is ChainCode {
return typeof value === 'string' && ALLOWED_CHAINS.has(value as ChainCode);
@@ -23,7 +17,7 @@ function isChain(value: unknown): value is ChainCode {
export const WalletController = {
/**
* GET /api/wallets — все адреса юзера (chain + address + derivationPath).
* GET /api/wallets — все адреса юзера.
*/
async getWallets(req: Request, res: Response) {
try {
@@ -43,155 +37,69 @@ export const WalletController = {
},
/**
* 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 клиенту не отдаём.
* POST /api/wallets/create — non-custodial upsert.
* Клиент сам деривит mnemonic и шлёт массив { chain, address, derivationPath }.
* Сервер валидирует и сохраняет (upsert по user_id+chain).
*/
async createWallet(req: Request, res: Response) {
async createWallets(req: Request, res: Response) {
const userId = req.auth!.userId;
const { wallets } = req.body ?? {};
if (!isCryptoReady()) {
res.status(503).json({ success: false, error: 'Crypto service not ready' });
if (!Array.isArray(wallets) || wallets.length === 0 || wallets.length > MAX_WALLETS_PER_REQUEST) {
res.status(400).json({
success: false,
error: `wallets must be a non-empty array (max ${MAX_WALLETS_PER_REQUEST})`,
});
return;
}
let mnemonic: string | null = null;
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 ||
!BIP32_PATH_RE.test(w.derivationPath)
) {
res.status(400).json({ success: false, error: 'Invalid derivationPath (BIP32 m/.. format expected)' });
return;
}
}
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) },
});
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: created.map((w) => ({
data: rows.map((w) => ({
chain: w.chain,
address: w.address,
derivationPath: w.derivationPath,
derivationPath: w.derivation_path,
})),
});
} 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: 'Missing or invalid confirm token. Send { "confirm": "I_UNDERSTAND_SEED_IS_SECRET" } in body.',
});
return;
}
try {
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 mnemonic = decryptMnemonic(blob);
await auditLog({
event: 'mnemonic.reveal',
userId,
ip: req.ip || null,
result: 'success',
});
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' });
logger.error(`createWallets failed for user ${userId}: ${err.stack || err.message}`);
res.status(500).json({ success: false, error: 'Internal error' });
}
},
@@ -252,9 +160,8 @@ export const WalletController = {
},
/**
* POST /api/wallets/:chain/send — custodial sign + broadcast.
* Сервер расшифровывает мнемонику, деривит privkey, подписывает, broadcast'ит.
* Возвращает { txid }.
* POST /api/wallets/:chain/send — build unsigned tx (non-custodial).
* Возвращает unsigned tx; клиент подписывает приватом и broadcast'ит сам.
*/
async sendFromChain(req: Request, res: Response) {
const userId = req.auth!.userId;
@@ -265,11 +172,6 @@ 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))) {
@@ -290,7 +192,6 @@ export const WalletController = {
normalizedToken = token.toUpperCase();
}
let mnemonic: string | null = null;
try {
const wallet = await WalletModel.findByUserAndChain(userId, chain);
if (!wallet) {
@@ -298,51 +199,21 @@ export const WalletController = {
return;
}
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({
const tx = await buildSend({
chain,
mnemonic,
from: wallet.address,
to: String(to),
amount: String(amount),
token: normalizedToken,
expectedFromAddress: wallet.address,
});
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 } });
res.json({ success: true, data: tx });
} catch (err: any) {
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';
logger.error(`buildSend ${chain} failed for user ${userId}: ${err.stack || err.message}`);
const msg = err?.message?.toLowerCase?.().includes('not supported')
? 'Token/chain combination not supported'
: 'Failed to build transaction';
res.status(502).json({ success: false, error: msg });
} finally {
// Best-effort cleanup mnemonic в RAM
mnemonic = null;
}
},
};