Avant de tester le retrait et le dépôt en crypto réel2

This commit is contained in:
Your Name 2026-08-23 19:36:27 +02:00
parent cb66ee4cfc
commit b338a153eb
4 changed files with 228 additions and 1 deletions

View File

@ -30,6 +30,8 @@
"disable-admin-2fa:prod": "node dist/scripts/disableAdmin2faRequirement.js",
"break-glass-reset-2fa": "ts-node --transpile-only src/scripts/breakGlassResetAdmin2fa.ts",
"break-glass-reset-2fa:prod": "node dist/scripts/breakGlassResetAdmin2fa.js",
"rotate-deposit-addresses": "ts-node --transpile-only src/scripts/rotateDepositAddresses.ts",
"rotate-deposit-addresses:prod": "node dist/scripts/rotateDepositAddresses.js",
"verify-smtp": "ts-node --transpile-only src/scripts/verifySmtp.ts",
"verify-smtp:prod": "node dist/scripts/verifySmtp.js",
"rotate-encryption-key": "ts-node --transpile-only src/scripts/rotateEncryptionKey.ts",

View File

@ -0,0 +1,197 @@
/**
* Replace USDT deposit addresses so they derive from the current PLATFORM_MNEMONIC.
*
* Use after rotating PLATFORM_MNEMONIC when old addresses were derived from a previous phrase.
* Does NOT touch hot_wallets, cold_wallets, or ledger balances.
*
* WARNING: Any USDT still on the OLD on-chain addresses becomes unreachable unless you still
* have the previous mnemonic. Only run this when old addresses hold no real funds (or after
* sweeping them with the old mnemonic).
*
* VPS:
* sudo docker compose run --rm --no-deps --build backend \
* node dist/scripts/rotateDepositAddresses.js \
* --confirm=ROTATE_DEPOSIT_ADDRESSES \
* --scope=existing
*
* --scope=existing users who already have a USDT deposit address
* --scope=all every non-deleted user (creates addresses if missing)
* --email=a@b.com only that user
*/
import './loadEnv';
import * as bip39 from 'bip39';
import { hashForIndex } from '../utils/crypto';
import { query } from '../db/connection';
import { deriveTronFromMnemonic } from '../services/hdWallet';
import * as userRepository from '../repositories/userRepository';
import * as walletRepository from '../repositories/walletRepository';
import * as auditLogRepository from '../repositories/auditLogRepository';
import { USDT_WALLET_CODE } from '../services/walletCapabilities';
const CONFIRM_PHRASE = 'ROTATE_DEPOSIT_ADDRESSES';
type Scope = 'existing' | 'all';
type Args = {
confirm: string;
scope: Scope | null;
email: string | null;
};
type WalletRow = {
user_id: string;
address: string;
derivation_index: number;
};
function printUsageAndExit(code = 1): never {
console.error(`Usage:
node dist/scripts/rotateDepositAddresses.js \\
--confirm=${CONFIRM_PHRASE} \\
(--scope=existing | --scope=all | --email=user@example.com)
--scope=existing Rotate only users who already have a USDT deposit address
--scope=all Ensure every active user has a new address from current mnemonic
--email=... Rotate a single user
`);
process.exit(code);
}
function parseArgs(argv: string[]): Args {
const map = new Map<string, string>();
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: Scope | null =
scopeRaw === 'existing' || scopeRaw === 'all' ? (scopeRaw as Scope) : null;
if (!confirm || (!scope && !email) || (scope && email)) printUsageAndExit(1);
return { confirm, scope, email };
}
function requireCurrentMnemonic(): string {
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;
}
async function main(): Promise<void> {
const args = parseArgs(process.argv.slice(2));
if (args.confirm !== CONFIRM_PHRASE) {
throw new Error(`--confirm must be exactly ${CONFIRM_PHRASE}`);
}
const mnemonic = requireCurrentMnemonic();
const usdt = await walletRepository.getWalletTypeByCode(USDT_WALLET_CODE);
if (!usdt) throw new Error('USDT_TRC20 wallet type not found — run migrations first.');
let userIds: string[] = [];
if (args.email) {
const user = await userRepository.findByEmailHash(hashForIndex(args.email));
if (!user) throw new Error(`No active user for email: ${args.email}`);
userIds = [user.id];
} else if (args.scope === 'existing') {
const rows = await query<{ user_id: string }[]>(
`SELECT uw.user_id
FROM user_wallets uw
JOIN users u ON u.id = uw.user_id
WHERE uw.wallet_type_id = $1 AND u.deleted_at IS NULL
ORDER BY uw.derivation_index ASC, uw.created_at ASC`,
[usdt.id]
);
userIds = rows.map((r) => r.user_id);
} else {
const rows = await query<{ id: string }[]>(
`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;
}
const before = await query<WalletRow[]>(
`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`,
[usdt.id, userIds]
);
console.log(`PLATFORM_MNEMONIC: valid (${mnemonic.split(/\s+/).length} words)`);
console.log(`Users to process: ${userIds.length}`);
console.log(`Existing USDT deposit addresses that will be replaced: ${before.length}`);
for (const row of before.slice(0, 20)) {
console.log(` old index=${row.derivation_index} user=${row.user_id} ${row.address}`);
}
if (before.length > 20) console.log(` … and ${before.length - 20} more`);
console.log(
'\nWARNING: Do not send real USDT to the old addresses above after this rotation.\n'
);
await query(`DELETE FROM user_wallets WHERE wallet_type_id = $1 AND user_id = ANY($2::uuid[])`, [
usdt.id,
userIds,
]);
// Start indices after any remaining wallets (other users not in this batch).
let nextIndex = await walletRepository.getNextDerivationIndex(usdt.id);
const created: Array<{ userId: string; address: string; index: number }> = [];
for (const userId of userIds) {
const derived = deriveTronFromMnemonic(mnemonic, nextIndex);
await walletRepository.createUserWallet({
userId,
walletTypeId: usdt.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',
scope: args.scope ?? 'email',
email: args.email,
usersProcessed: 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(`Created ${created.length} new USDT deposit address(es) from current mnemonic:`);
for (const row of created.slice(0, 30)) {
console.log(` new index=${row.index} user=${row.userId} ${row.address}`);
}
if (created.length > 30) console.log(` … and ${created.length - 30} more`);
console.log('\nHot wallet unchanged. Ledger balances unchanged.');
console.log('Open Deposit in the app to verify the new address matches the list above.');
}
main()
.then(() => process.exit(0))
.catch((e) => {
console.error(e instanceof Error ? e.message : e);
process.exit(1);
});

View File

@ -132,6 +132,32 @@ npm run seed-hot-wallets
Une seule fois suffit : si le hot wallet existe déjà, le script affiche `Skipping` et ne recrée rien.
#### Rotation des adresses de dépôt (après changement de `PLATFORM_MNEMONIC`)
Si des utilisateurs ont déjà une adresse créée avec un **ancien** mnémonique, l’app continue d’afficher cette adresse (`getOrCreateDepositAddress` ne la régénère pas). Pour forcer de **nouvelles** adresses dérivées du mnémonique **actuel** :
> **Danger :** tout USDT encore sur les **anciennes** adresses on-chain devient incontrôlable sans l’ancien mnémonique. À n’utiliser que si ces adresses sont vides (ou après sweep avec l’ancien mnémonique).
```bash
cd ~/projects_repository/game-project
# Tous les users qui ont déjà une adresse USDT
sudo docker compose run --rm --no-deps --build backend \
node dist/scripts/rotateDepositAddresses.js \
--confirm=ROTATE_DEPOSIT_ADDRESSES \
--scope=existing
# Ou un seul compte de test
sudo docker compose run --rm --no-deps --build backend \
node dist/scripts/rotateDepositAddresses.js \
--confirm=ROTATE_DEPOSIT_ADDRESSES \
--email=test@example.com
```
Équivalent : `npm run phase-b:rotate-deposit-addresses -- --confirm=ROTATE_DEPOSIT_ADDRESSES --scope=existing`
Le script ne touche **pas** au hot wallet ni aux soldes ledger. Ensuite, ouvrir **Dépôt** dans l’app et n’envoyer de l’USDT réel **que** vers la nouvelle adresse affichée.
#### `JWT_SECRET` et `INITIAL_SETUP_TOKEN`
Deux valeurs **différentes**, chacune ≥ 32 caractères aléatoires :

View File

@ -26,9 +26,11 @@
"phase-b:grant-super-admin": "docker compose run --rm --no-deps --build backend node dist/scripts/grantSuperAdminToAdmins.js",
"phase-b:verify-smtp": "docker compose run --rm --no-deps --build backend node dist/scripts/verifySmtp.js",
"phase-b:break-glass-reset-2fa": "docker compose run --rm --no-deps --build backend node dist/scripts/breakGlassResetAdmin2fa.js",
"phase-b:rotate-deposit-addresses": "docker compose run --rm --no-deps --build backend node dist/scripts/rotateDepositAddresses.js",
"docker:local:grant-super-admin": "docker compose --env-file .env.docker run --rm --no-deps --build backend node dist/scripts/grantSuperAdminToAdmins.js",
"docker:local:reset-password": "docker compose --env-file .env.docker run --rm --no-deps --build backend node dist/scripts/resetDevPassword.js",
"docker:local:disable-admin-2fa": "docker compose --env-file .env.docker run --rm --no-deps --build backend node dist/scripts/disableAdmin2faRequirement.js",
"docker:local:break-glass-reset-2fa": "docker compose --env-file .env.docker run --rm --no-deps --build backend node dist/scripts/breakGlassResetAdmin2fa.js"
"docker:local:break-glass-reset-2fa": "docker compose --env-file .env.docker run --rm --no-deps --build backend node dist/scripts/breakGlassResetAdmin2fa.js",
"docker:local:rotate-deposit-addresses": "docker compose --env-file .env.docker run --rm --no-deps --build backend node dist/scripts/rotateDepositAddresses.js"
}
}