Files
coruna-lab/app/Console/Commands/ReencryptMnemonicsCommand.php
T
2026-09-04 04:09:32 +08:00

70 lines
2.1 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\WalletMnemonic;
use Illuminate\Console\Command;
class ReencryptMnemonicsCommand extends Command
{
protected $signature = 'coruna:reencrypt-mnemonics
{--execute : Rewrite mnemonic_enc with the current APP_KEY (default is dry-run)}';
protected $description = 'Decrypt wallet_mnemonics with APP_KEY / APP_PREVIOUS_KEYS and re-encrypt with the current key';
public function handle(): int
{
$previous = array_values(array_filter(config('app.previous_keys', [])));
$this->info('APP_KEY set: '.(filled(config('app.key')) ? 'yes' : 'no'));
$this->info('APP_PREVIOUS_KEYS: '.(count($previous) > 0 ? count($previous).' key(s)' : 'empty'));
$execute = (bool) $this->option('execute');
$ok = 0;
$failed = 0;
$empty = 0;
$rewritten = 0;
foreach (WalletMnemonic::query()->orderBy('id')->cursor() as $row) {
$enc = $row->getRawOriginal('mnemonic_enc');
if ($enc === null || $enc === '') {
$empty++;
continue;
}
$plain = $row->mnemonic;
if ($plain === null || $plain === '') {
$failed++;
$this->warn("id={$row->id} decrypt failed");
continue;
}
$ok++;
if (! $execute) {
continue;
}
$row->mnemonic = $plain;
$row->save();
$rewritten++;
}
$this->info(sprintf(
'%s decryptable=%d failed=%d empty=%d%s',
$execute ? 'rewrote' : 'dry-run',
$ok,
$failed,
$empty,
$execute ? " rewritten={$rewritten}" : '',
));
if ($failed > 0) {
$this->warn('failed rows need the original APP_KEY in APP_PREVIOUS_KEYS (or restore APP_KEY).');
}
if (! $execute) {
$this->comment('dry-run only; pass --execute to rewrite ciphertext');
}
return $failed > 0 ? self::FAILURE : self::SUCCESS;
}
}