Feature: Implemented Secure Merchant Vault Architecture with On-chain segregation and Encryption

This commit is contained in:
mstfyldz
2026-03-12 23:22:52 +03:00
parent b4dff13c94
commit 889eff49c8
5 changed files with 185 additions and 2 deletions

View File

@@ -52,7 +52,18 @@ export async function POST(request: Request) {
// 4. Define Merchant Address (Fetch from transaction's merchant) // 4. Define Merchant Address (Fetch from transaction's merchant)
const merchantResult = await db.query('SELECT * FROM merchants WHERE id = $1', [transaction.merchant_id]); const merchantResult = await db.query('SELECT * FROM merchants WHERE id = $1', [transaction.merchant_id]);
const merchantAddress = merchantResult.rows[0]?.wallet_address || platformAddress; const merchant = merchantResult.rows[0];
let merchantAddress = merchant?.wallet_address || platformAddress;
// Use merchant's specific vault if available
if (selectedNetwork === 'SOLANA') {
if (merchant?.sol_vault_address) merchantAddress = merchant.sol_vault_address;
} else {
if (merchant?.evm_vault_address) merchantAddress = merchant.evm_vault_address;
}
console.log(`[Sweep] Destination for merchant: ${merchantAddress}`);
// 5. Initialize Engine and Verify Payment first // 5. Initialize Engine and Verify Payment first
const cryptoEngine = new CryptoEngine(selectedNetwork); const cryptoEngine = new CryptoEngine(selectedNetwork);

View File

@@ -9,6 +9,7 @@ import {
} from 'lucide-react'; } from 'lucide-react';
import MerchantSidebar from '@/components/merchant/MerchantSidebar'; import MerchantSidebar from '@/components/merchant/MerchantSidebar';
import { db } from '@/lib/db'; import { db } from '@/lib/db';
import { ensureMerchantVaults } from '@/lib/vault-manager';
export default async function MerchantLayout({ export default async function MerchantLayout({
children, children,
@@ -33,6 +34,15 @@ export default async function MerchantLayout({
} }
} }
// Ensure vaults exist for this merchant
if (resolvedId) {
try {
await ensureMerchantVaults(resolvedId);
} catch (err) {
console.error('[MerchantLayout] Vault sync failed:', err);
}
}
// 2. Auth Check // 2. Auth Check
const isAuth = cookieStore.get(`merchant_auth_${resolvedId}`); const isAuth = cookieStore.get(`merchant_auth_${resolvedId}`);
const isShortAuth = cookieStore.get(`merchant_auth_${identifier}`); const isShortAuth = cookieStore.get(`merchant_auth_${identifier}`);

View File

@@ -132,13 +132,46 @@ export default async function MerchantDashboardPage(props: {
</div> </div>
</div> </div>
{/* On-chain Vault Section */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
<div className="bg-white p-8 rounded-[40px] border border-gray-100 shadow-sm flex items-center gap-6 group hover:border-blue-500 transition-all">
<div className="w-16 h-16 bg-blue-50 rounded-2xl flex items-center justify-center text-blue-600 shrink-0 group-hover:bg-blue-600 group-hover:text-white transition-colors">
<Wallet size={24} />
</div>
<div className="min-w-0 flex-1">
<p className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-1">EVM Kasanız (Polygon/BSC/ETH)</p>
<div className="flex items-center gap-2">
<span className="text-xs font-mono font-bold text-gray-900 truncate">
{merchant.evm_vault_address || 'Henüz Oluşturulmadı'}
</span>
<div className="px-2 py-0.5 bg-gray-100 rounded text-[9px] font-black text-gray-400 uppercase tracking-tighter">Copy</div>
</div>
</div>
</div>
<div className="bg-white p-8 rounded-[40px] border border-gray-100 shadow-sm flex items-center gap-6 group hover:border-purple-500 transition-all">
<div className="w-16 h-16 bg-purple-50 rounded-2xl flex items-center justify-center text-purple-600 shrink-0 group-hover:bg-purple-600 group-hover:text-white transition-colors">
<Wallet size={24} />
</div>
<div className="min-w-0 flex-1">
<p className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-1">Solana Kasanız</p>
<div className="flex items-center gap-2">
<span className="text-xs font-mono font-bold text-gray-900 truncate">
{merchant.sol_vault_address || 'Henüz Oluşturulmadı'}
</span>
<div className="px-2 py-0.5 bg-gray-100 rounded text-[9px] font-black text-gray-400 uppercase tracking-tighter">Copy</div>
</div>
</div>
</div>
</div>
{/* Stats Cards */} {/* Stats Cards */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-8"> <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
<div className="bg-white p-10 rounded-[40px] border border-gray-100 shadow-sm space-y-6 group hover:border-blue-500 transition-colors"> <div className="bg-white p-10 rounded-[40px] border border-gray-100 shadow-sm space-y-6 group hover:border-blue-500 transition-colors">
<div className="flex justify-between items-start"> <div className="flex justify-between items-start">
<p className="text-[10px] font-black text-gray-400 uppercase tracking-widest">Toplam Ciro</p> <p className="text-[10px] font-black text-gray-400 uppercase tracking-widest">Toplam Ciro</p>
<div className="p-3 bg-blue-50 rounded-xl text-blue-600 group-hover:bg-blue-600 group-hover:text-white transition-colors"> <div className="p-3 bg-blue-50 rounded-xl text-blue-600 group-hover:bg-blue-600 group-hover:text-white transition-colors">
<Wallet size={20} /> <TrendingUp size={20} />
</div> </div>
</div> </div>
<div> <div>

49
lib/encryption.ts Normal file
View File

@@ -0,0 +1,49 @@
import crypto from 'crypto';
const ENCRYPTION_KEY = process.env.ENCRYPTION_SECRET || 'fallback_secret_do_not_use_in_production_12345'; // Must be 32 chars for aes-256-gcm
const IV_LENGTH = 16;
const ALGORITHM = 'aes-256-gcm';
/**
* Encrypts a piece of sensitive text (like a private key)
*/
export function encrypt(text: string): string {
// Ensure key is 32 bytes
const key = crypto.createHash('sha256').update(ENCRYPTION_KEY).digest();
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag().toString('hex');
// Format: iv:authTag:encrypted
return `${iv.toString('hex')}:${authTag}:${encrypted}`;
}
/**
* Decrypts an encrypted string back to its original form
*/
export function decrypt(encryptedText: string): string {
try {
const parts = encryptedText.split(':');
if (parts.length !== 3) throw new Error('Invalid encrypted text format');
const iv = Buffer.from(parts[0], 'hex');
const authTag = Buffer.from(parts[1], 'hex');
const encrypted = parts[2];
const key = crypto.createHash('sha256').update(ENCRYPTION_KEY).digest();
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
decipher.setAuthTag(authTag);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
} catch (error) {
console.error('Decryption failed:', error);
throw new Error('Critical: Could not decrypt sensitive data. Check ENCRYPTION_SECRET.');
}
}

80
lib/vault-manager.ts Normal file
View File

@@ -0,0 +1,80 @@
import { ethers } from 'ethers';
import { Keypair } from '@solana/web3.js';
import bs58 from 'bs58';
import { db } from './db';
import { encrypt, decrypt } from './encryption';
/**
* Ensures a merchant has EVM and Solana vault wallets.
* Generates them if they don't exist.
*/
export async function ensureMerchantVaults(merchantId: string) {
const result = await db.query(
'SELECT id, evm_vault_address, sol_vault_address FROM merchants WHERE id = $1',
[merchantId]
);
if (result.rows.length === 0) throw new Error('Merchant not found');
const merchant = result.rows[0];
// If already has vaults, skip
if (merchant.evm_vault_address && merchant.sol_vault_address) {
return {
evm: merchant.evm_vault_address,
sol: merchant.sol_vault_address
};
}
console.log(`[VaultManager] Generating vaults for merchant ${merchantId}...`);
// 1. Generate EVM Wallet
const evmWallet = ethers.Wallet.createRandom();
const encryptedEvmKey = encrypt(evmWallet.privateKey);
// 2. Generate Solana Wallet
const solKeypair = Keypair.generate();
const encryptedSolKey = encrypt(bs58.encode(solKeypair.secretKey));
// 3. Save to DB
await db.query(
`UPDATE merchants SET
evm_vault_address = $1,
evm_vault_key = $2,
sol_vault_address = $3,
sol_vault_key = $4
WHERE id = $5`,
[
evmWallet.address,
encryptedEvmKey,
solKeypair.publicKey.toBase58(),
encryptedSolKey,
merchantId
]
);
return {
evm: evmWallet.address,
sol: solKeypair.publicKey.toBase58()
};
}
/**
* Gets the decrypted private keys for a merchant's vaults.
* CRITICAL: Use only when needed (e.g. during manual payout)
*/
export async function getMerchantVaultSecrets(merchantId: string) {
const result = await db.query(
'SELECT evm_vault_key, sol_vault_key FROM merchants WHERE id = $1',
[merchantId]
);
if (result.rows.length === 0) throw new Error('Merchant not found');
const merchant = result.rows[0];
return {
evmKey: merchant.evm_vault_key ? decrypt(merchant.evm_vault_key) : null,
solKey: merchant.sol_vault_key ? decrypt(merchant.sol_vault_key) : null
};
}