games_app/backend/dist-test-faq/scripts/rotateDepositAddresses.js

228 lines
9.2 KiB
JavaScript

"use strict";
/**
* Replace deposit addresses so they derive from the current PLATFORM_MNEMONIC.
*
* Supports USDT_TRC20 (TRON) and USDT_BEP20 (BSC). Does NOT touch hot/cold wallets or ledger.
*
* WARNING: Any funds still on OLD on-chain addresses become unreachable without the previous mnemonic.
*
* VPS:
* sudo docker compose run --rm --no-deps --build backend \
* node dist/scripts/rotateDepositAddresses.js \
* --confirm=ROTATE_DEPOSIT_ADDRESSES \
* --scope=existing \
* --wallet-type=ALL
*
* --wallet-type=USDT_TRC20 | USDT_BEP20 | ALL (default ALL)
* --scope=existing | --scope=all | --email=a@b.com
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
require("./loadEnv");
const bip39 = __importStar(require("bip39"));
const crypto_1 = require("../utils/crypto");
const connection_1 = require("../db/connection");
const hdWallet_1 = require("../services/hdWallet");
const userRepository = __importStar(require("../repositories/userRepository"));
const walletRepository = __importStar(require("../repositories/walletRepository"));
const auditLogRepository = __importStar(require("../repositories/auditLogRepository"));
const walletCapabilities_1 = require("../services/walletCapabilities");
const CONFIRM_PHRASE = 'ROTATE_DEPOSIT_ADDRESSES';
function printUsageAndExit(code = 1) {
console.error(`Usage:
node dist/scripts/rotateDepositAddresses.js \\
--confirm=${CONFIRM_PHRASE} \\
(--scope=existing | --scope=all | --email=user@example.com) \\
[--wallet-type=ALL|USDT_TRC20|USDT_BEP20]
`);
process.exit(code);
}
function parseArgs(argv) {
const map = new Map();
for (const raw of argv) {
if (!raw.startsWith('--'))
continue;
const eq = raw.indexOf('=');
if (eq <= 2)
continue;
map.set(raw.slice(2, eq).trim(), raw.slice(eq + 1).trim());
}
const confirm = (map.get('confirm') || '').trim();
const scopeRaw = (map.get('scope') || '').trim().toLowerCase();
const email = (map.get('email') || '').trim().toLowerCase() || null;
const scope = scopeRaw === 'existing' || scopeRaw === 'all' ? scopeRaw : null;
const wtRaw = (map.get('wallet-type') || 'ALL').trim().toUpperCase();
let walletTypes;
if (wtRaw === 'ALL')
walletTypes = [walletCapabilities_1.USDT_TRC20_CODE, walletCapabilities_1.USDT_BEP20_CODE];
else if (wtRaw === walletCapabilities_1.USDT_TRC20_CODE || wtRaw === walletCapabilities_1.USDT_BEP20_CODE)
walletTypes = [wtRaw];
else
printUsageAndExit(1);
if (!confirm || (!scope && !email) || (scope && email))
printUsageAndExit(1);
return { confirm, scope, email, walletTypes };
}
function requireCurrentMnemonic() {
const raw = (process.env.PLATFORM_MNEMONIC || '').trim();
if (!raw || raw.split(/\s+/).length < 12) {
throw new Error('PLATFORM_MNEMONIC is missing or too short in the environment.');
}
if (!bip39.validateMnemonic(raw)) {
throw new Error('PLATFORM_MNEMONIC is not a valid BIP39 mnemonic.');
}
return raw;
}
function deriveAddress(mnemonic, code, index) {
if (code === walletCapabilities_1.USDT_BEP20_CODE)
return (0, hdWallet_1.deriveEvmFromMnemonic)(mnemonic, index);
return (0, hdWallet_1.deriveTronFromMnemonic)(mnemonic, index);
}
async function rotateOne(opts) {
const wt = await walletRepository.getWalletTypeByCode(opts.code);
if (!wt) {
console.log(`[${opts.code}] wallet type not found — skip (run migrations).`);
return;
}
const before = await (0, connection_1.query)(`SELECT user_id, address, derivation_index
FROM user_wallets
WHERE wallet_type_id = $1 AND user_id = ANY($2::uuid[])
ORDER BY derivation_index ASC`, [wt.id, opts.userIds]);
console.log(`\n[${opts.code}] Users: ${opts.userIds.length}; addresses to replace: ${before.length}`);
for (const row of before.slice(0, 10)) {
console.log(` old index=${row.derivation_index} user=${row.user_id} ${row.address}`);
}
if (before.length > 10)
console.log(` … and ${before.length - 10} more`);
await (0, connection_1.query)(`DELETE FROM user_wallets WHERE wallet_type_id = $1 AND user_id = ANY($2::uuid[])`, [
wt.id,
opts.userIds,
]);
let nextIndex = await walletRepository.getNextDerivationIndex(wt.id);
const created = [];
for (const userId of opts.userIds) {
const derived = deriveAddress(opts.mnemonic, opts.code, nextIndex);
await walletRepository.createUserWallet({
userId,
walletTypeId: wt.id,
address: derived.address,
derivationIndex: nextIndex,
});
created.push({ userId, address: derived.address, index: nextIndex });
nextIndex += 1;
}
await auditLogRepository.create({
userId: null,
action: 'deposit_addresses_rotated',
resourceType: 'user_wallets',
metadata: {
channel: 'cli_rotate_deposit_addresses',
walletType: opts.code,
scope: opts.scope ?? 'email',
email: opts.email,
usersProcessed: opts.userIds.length,
addressesReplaced: before.length,
oldAddressesSample: before.slice(0, 10).map((r) => r.address),
newAddressesSample: created.slice(0, 10).map((c) => c.address),
},
});
console.log(`[${opts.code}] Created ${created.length} new deposit address(es).`);
for (const row of created.slice(0, 15)) {
console.log(` new index=${row.index} user=${row.userId} ${row.address}`);
}
if (created.length > 15)
console.log(` … and ${created.length - 15} more`);
}
async function main() {
const args = parseArgs(process.argv.slice(2));
if (args.confirm !== CONFIRM_PHRASE) {
throw new Error(`--confirm must be exactly ${CONFIRM_PHRASE}`);
}
const mnemonic = requireCurrentMnemonic();
let userIds = [];
if (args.email) {
const user = await userRepository.findByEmailHash((0, crypto_1.hashForIndex)(args.email));
if (!user)
throw new Error(`No active user for email: ${args.email}`);
userIds = [user.id];
}
else if (args.scope === 'existing') {
// Users who have at least one deposit address for any selected type
const typeIds = [];
for (const code of args.walletTypes) {
const wt = await walletRepository.getWalletTypeByCode(code);
if (wt)
typeIds.push(wt.id);
}
if (typeIds.length === 0) {
console.log('No wallet types found. Nothing to do.');
return;
}
const rows = await (0, connection_1.query)(`SELECT DISTINCT uw.user_id
FROM user_wallets uw
JOIN users u ON u.id = uw.user_id
WHERE uw.wallet_type_id = ANY($1::int[]) AND u.deleted_at IS NULL
ORDER BY uw.user_id`, [typeIds]);
userIds = rows.map((r) => r.user_id);
}
else {
const rows = await (0, connection_1.query)(`SELECT id FROM users WHERE deleted_at IS NULL ORDER BY created_at ASC`);
userIds = rows.map((r) => r.id);
}
if (userIds.length === 0) {
console.log('No users to rotate. Nothing to do.');
return;
}
console.log(`PLATFORM_MNEMONIC: valid (${mnemonic.split(/\s+/).length} words)`);
console.log('\nWARNING: Do not send real USDT to old addresses after this rotation.\n');
for (const code of args.walletTypes) {
await rotateOne({
mnemonic,
code,
userIds,
scope: args.scope,
email: args.email,
});
}
console.log('\nHot wallets unchanged. Ledger balances unchanged.');
console.log('Open Deposit in the app and verify the new address for each network.');
}
main()
.then(() => process.exit(0))
.catch((e) => {
console.error(e instanceof Error ? e.message : e);
process.exit(1);
});
//# sourceMappingURL=rotateDepositAddresses.js.map