feat(vikon): rewrite VikonIntegration from scratch — OAuth + core update

- HttpTask: Laravel Http facade with SSL enabled, retry, timeout
- ValidateTokenTask: token check via auth.db-nica.ru
- RefreshTokenTask: token refresh via db-nica.ru
- FilesystemTask: path traversal protection, blocked extensions (PHP/ASP/etc)
- AuthenticateAction: OAuth2 code→token exchange
- CheckAccessAction: token validation + filesystem writability check
- CheckVersionAction: version comparison against remote API
- UpdateCoreAction: ZIP download, Zip Slip protection, atomic sync with rollback
- VikonController: thin controller, 7 endpoints with Session-based token storage
- Routes: access-check, dashboard.auth, throttle:30,1 middleware
- Vue 3 Composition API frontend with progress bar
- Config: all secrets in .env via config/vikon.php
- vikon_core kept as fallback (not deleted)
This commit is contained in:
F4ilji
2026-07-04 12:53:28 +05:00
parent 82df1210c2
commit f4f8bc8e77
15 changed files with 990 additions and 1 deletions
@@ -0,0 +1,39 @@
<?php
namespace App\Containers\VikonIntegration\Actions\Auth;
use App\Containers\VikonIntegration\Tasks\HttpTask;
class AuthenticateAction
{
public function __construct(
private readonly HttpTask $http,
private readonly string $clientId,
private readonly string $clientSecret,
) {}
/**
* @return array{access_token: string, refresh_token: string}
*/
public function run(string $code, string $redirectUri): array
{
$response = $this->http->post('oauth2/authorize/token', [
'code' => $code,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'redirect_uri' => $redirectUri,
'grant_type' => 'authorization_code',
], 'auth');
$body = $response->json();
if (!isset($body['access_token'], $body['refresh_token'])) {
throw new \RuntimeException('Auth failed: ' . ($body['message'] ?? 'Unknown error'));
}
return [
'access_token' => $body['access_token'],
'refresh_token' => $body['refresh_token'],
];
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Containers\VikonIntegration\Actions;
use App\Containers\VikonIntegration\Tasks\HttpTask;
use App\Containers\VikonIntegration\Tasks\ValidateTokenTask;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
class CheckAccessAction
{
public function __construct(
private readonly ValidateTokenTask $validateToken,
private readonly HttpTask $http,
private readonly string $publicPath,
) {}
public function run(string $accessToken): array
{
if (!$this->validateToken->run($accessToken)) {
return ['has_access' => false, 'error' => 'Токен недействителен. Выполните повторную авторизацию.'];
}
$nonWritable = $this->findNonWritable($this->publicPath);
if (!empty($nonWritable)) {
return [
'has_access' => false,
'error' => 'Нет прав на запись: ' . implode(', ', array_slice($nonWritable, 0, 3)),
];
}
return ['has_access' => true, 'error' => null];
}
private function findNonWritable(string $path, int $depth = 0): array
{
if ($depth > 3 || !is_dir($path)) return [];
if (!is_writable($path)) {
return [str_replace(base_path() . '/', '', $path)];
}
$result = [];
foreach (File::directories($path) as $dir) {
$result = array_merge($result, $this->findNonWritable($dir, $depth + 1));
}
return $result;
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Containers\VikonIntegration\Actions;
use App\Containers\VikonIntegration\Tasks\HttpTask;
use Illuminate\Support\Facades\Log;
class CheckVersionAction
{
public function __construct(
private readonly HttpTask $http,
private readonly string $currentVersion,
) {}
public function run(string $accessToken): array
{
try {
$response = $this->http->getWithToken('pull_updates/getLatestVersion', $accessToken);
$body = $response->json();
$latest = $body['version'] ?? null;
return [
'current_version' => $this->currentVersion,
'latest_version' => $latest,
'has_update' => $latest && version_compare($latest, $this->currentVersion, '>'),
];
} catch (\Throwable $e) {
Log::warning('Version check failed', ['error' => $e->getMessage()]);
return [
'current_version' => $this->currentVersion,
'latest_version' => null,
'has_update' => false,
'error' => 'Не удалось проверить обновления',
];
}
}
}
@@ -0,0 +1,160 @@
<?php
namespace App\Containers\VikonIntegration\Actions;
use App\Containers\VikonIntegration\Tasks\HttpTask;
use App\Containers\VikonIntegration\Tasks\FilesystemTask;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use ZipArchive;
class UpdateCoreAction
{
private const NEW_SUFFIX = '_new';
private const OLD_SUFFIX = '_old';
public function __construct(
private readonly HttpTask $http,
private readonly FilesystemTask $fs,
private readonly array $modulesConfig,
private readonly string $storagePath,
private readonly string $basePath,
) {}
public function run(int $moduleId, string $accessToken): string
{
$config = $this->modulesConfig[$moduleId] ?? throw new \RuntimeException('Неизвестный модуль');
$modulePath = $this->basePath . '/' . $config['path'];
$tempPath = $this->storagePath . '/temp/' . $config['path'];
try {
Log::info('Vikon: downloading module core', ['module' => $moduleId]);
$zipContent = $this->http->downloadWithToken(
'pull_updates/generateEmptyModuleCore/' . $moduleId,
$accessToken
);
if (File::exists($tempPath)) File::deleteDirectory($tempPath);
File::makeDirectory($tempPath, 0755, true, true);
$zipFile = $tempPath . '/module.zip';
file_put_contents($zipFile, $zipContent);
$this->extractZip($zipFile, $tempPath);
$blocked = $this->fs->validateFileTypes($tempPath);
if (!empty($blocked)) {
throw new \RuntimeException(
'Запрещённые файлы: ' . implode(', ', $blocked) . '. Обновление отклонено.'
);
}
$vikonCorePath = $tempPath . '/vikon_core';
if (File::isDirectory($vikonCorePath)) {
File::deleteDirectory($vikonCorePath);
}
File::delete($zipFile);
$this->syncFiles($tempPath, $modulePath);
$this->cleanModule($modulePath, $config['allowed_folders']);
File::put($modulePath . '/.vikon', date('Y-m-d H:i:s'));
File::deleteDirectory($tempPath);
Log::info('Vikon: module updated', ['module' => $config['name']]);
return 'Модуль "' . $config['name'] . '" обновлён.';
} catch (\Throwable $e) {
Log::error('Vikon update failed', ['module' => $moduleId, 'error' => $e->getMessage()]);
$this->rollback($modulePath);
throw new \RuntimeException('Ошибка обновления: ' . $e->getMessage());
}
}
private function extractZip(string $zipPath, string $destination): void
{
$zip = new ZipArchive;
if ($zip->open($zipPath) !== true) {
throw new \RuntimeException('Не удалось открыть ZIP');
}
$realDest = realpath($destination);
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
if (str_contains($name, '..')) {
$zip->close();
throw new \RuntimeException("Zip Slip: {$name}");
}
$full = realpath($realDest . '/' . $name);
if ($full !== false && !str_starts_with($full, $realDest)) {
$zip->close();
throw new \RuntimeException("Path escape: {$name}");
}
}
$zip->extractTo($destination);
$zip->close();
}
private function syncFiles(string $source, string $target): void
{
foreach (File::files($source) as $file) {
$name = $file->getFilename();
$targetPath = $target . '/' . $name;
if (File::exists($targetPath)) {
$oldPath = $targetPath . self::OLD_SUFFIX;
File::delete($oldPath);
rename($targetPath, $oldPath);
}
copy($file->getPathname(), $targetPath);
}
foreach (File::directories($source) as $dir) {
$name = basename($dir);
$targetPath = $target . '/' . $name;
if (File::exists($targetPath)) {
$oldPath = $targetPath . self::OLD_SUFFIX;
File::deleteDirectory($oldPath);
File::move($targetPath, $oldPath);
}
File::copyDirectory($dir, $targetPath);
}
}
private function cleanModule(string $modulePath, array $allowed): void
{
foreach (File::directories($modulePath) as $dir) {
$name = basename($dir);
if (!in_array($name, $allowed, true) && !is_link($dir)) {
File::deleteDirectory($dir);
}
}
foreach (File::files($modulePath) as $file) {
$name = $file->getFilename();
if (!in_array($name, $allowed, true) && !in_array($name, ['.vikon', '.htaccess'], true)) {
File::delete($file);
}
}
}
private function rollback(string $modulePath): void
{
foreach (File::directories($modulePath) as $dir) {
$old = $dir . self::OLD_SUFFIX;
if (File::exists($old)) {
File::deleteDirectory($dir);
File::move($old, $dir);
}
}
foreach (File::files($modulePath) as $file) {
$old = $file->getPathname() . self::OLD_SUFFIX;
if (File::exists($old)) {
File::delete($file);
rename($old, $file->getPathname());
}
}
}
}