feat(service): custom product, lịch sử giám sát VM và mã hoá response theo phiên

- Dịch vụ custom: bảng custom_products + services.custom_product_id; createService nhận
  custom{} thay product_id, giá = đơn giá tháng x số tháng chu kỳ (1/3/6/12/24/36),
  gia hạn tính theo cùng đơn giá, ServiceClientDetailResource trả custom_product và specs.
- Giám sát VM: GET v1/system/vm-metrics/history gom lịch sử về tối đa 240 điểm;
  lỗi lấy dung lượng đĩa không còn làm hỏng cả thẻ metrics.
- SealResponse: AES-256-GCM theo khoá phiên do proxy Next cấp qua header x-seal-key
  (HMAC của session id). Client opt-in bằng x-seal; chi tiết dịch vụ, mật khẩu VM và
  console ticket luôn được mã hoá. Body gửi lên dạng {enc} được giải mã trước validate;
  khoá lệch trả 428 để client lấy khoá mới. Đây là che mắt DevTools, không phải bảo mật
  chống chính chủ tài khoản.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
baodev0
2026-10-27 13:58:50 +07:00
co-authored by Claude Sonnet 5.5
parent 8108e8fe53
commit 6315a392c0
19 changed files with 549 additions and 33 deletions
@@ -3,6 +3,7 @@
namespace App\Http\Controllers\Api\Admin\Customer\Concerns;
use App\Models\ActivityLog;
use App\Models\CustomProduct;
use App\Models\Invoice;
use App\Models\InvoiceAttachment;
use App\Models\Service;
@@ -46,6 +47,7 @@ trait ManagesCustomerServices
{
$data = $request->validate([
'server_name' => 'nullable|string|max:255',
'product_id' => 'nullable|integer|exists:products,id',
'status' => 'nullable|in:pending,active,suspended,expired,cancelled,terminated',
'auto_renew' => 'nullable|boolean',
'started_at' => 'nullable|date',
@@ -206,7 +208,19 @@ trait ManagesCustomerServices
public function createService(string $uuid, Request $request): JsonResponse
{
$data = $request->validate([
'product_id' => 'required|integer|exists:products,id',
'product_id' => 'required_without:custom|nullable|integer|exists:products,id',
'custom' => 'nullable|array',
'custom.name' => 'required_with:custom|string|max:255',
'custom.category' => ['required_with:custom', Rule::in(CustomProduct::CATEGORIES)],
'custom.unit_price' => 'required_with:custom|numeric|min:0',
'custom.cpu' => 'nullable|integer|min:1',
'custom.ram_mb' => 'nullable|integer|min:1',
'custom.disk_gb' => 'nullable|integer|min:1',
'custom.bandwidth_gb' => 'nullable|integer|min:0',
'custom.description' => 'nullable|string|max:5000',
'custom.specs' => 'nullable|array|max:20',
'custom.specs.*.label' => 'required|string|max:100',
'custom.specs.*.value' => 'required|string|max:255',
'virtual_machine_id' => 'nullable|integer|exists:virtual_machines,id',
'server_name' => 'nullable|string|max:255',
'status' => 'nullable|in:pending,active,suspended,expired,cancelled,terminated',
@@ -3,6 +3,7 @@
namespace App\Http\Controllers\Api\Service\Concerns;
use App\Models\VirtualMachines;
use Illuminate\Support\Carbon;
use App\Services\VmMetricsService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
@@ -38,4 +39,34 @@ trait ManagesVmMetrics
return response()->json(['success' => true, 'data' => $metrics]);
}
public function metricsHistory(Request $request, VmMetricsService $metricsService): JsonResponse
{
$data = $request->validate([
'product' => 'required|string',
'from' => 'nullable|date',
'to' => 'nullable|date|after:from',
]);
$to = isset($data['to']) ? Carbon::parse($data['to']) : now();
$from = isset($data['from']) ? Carbon::parse($data['from']) : $to->copy()->subDay();
if ($from->diffInDays($to) > 31) {
return response()->json(['success' => false, 'message' => 'Chỉ xem được tối đa 31 ngày mỗi lần.'], 422);
}
$vm = $this->resolveVmById($data['product'], $request, requireActiveService: false);
if ($vm instanceof JsonResponse) {
return $vm;
}
try {
$points = $metricsService->history((string) $vm->vmware_id, $from, $to);
} catch (RuntimeException $exception) {
$status = $exception->getCode() === 404 ? 404 : 502;
return response()->json(['success' => false, 'message' => 'Không thể tải lịch sử giám sát VM.'], $status);
}
return response()->json(['success' => true, 'data' => $points]);
}
}
+2
View File
@@ -17,6 +17,7 @@ class Kernel extends HttpKernel
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\SealResponse::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\Illuminate\Http\Middleware\HandleCors::class
@@ -88,6 +89,7 @@ class Kernel extends HttpKernel
'perm' => \App\Http\Middleware\CheckPermission::class,
'restrict.local' => \App\Http\Middleware\RestrictToLocalEnvironment::class,
'portal-monitor.service' => \App\Http\Middleware\AuthenticatePortalMonitor::class,
'seal.response' => \App\Http\Middleware\SealResponse::class,
'turnstile' => \App\Http\Middleware\VerifyTurnstile::class,
];
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Http\Middleware;
use App\Support\ResponseCipher;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class SealResponse
{
public const KEY_HEADER = 'x-seal-key';
public const OPT_IN_HEADER = 'x-seal';
private const SEALED_ATTRIBUTE = 'response_sealed';
public function handle(Request $request, Closure $next, ?string $mode = null)
{
$key = ResponseCipher::keyFrom($request->headers->get(self::KEY_HEADER));
if ($this->openRequest($request, $key) === false) {
return new JsonResponse(['message' => 'Khoá phiên không khớp, vui lòng thử lại.'], 428);
}
$response = $next($request);
$wanted = $mode === 'always' || $request->headers->get(self::OPT_IN_HEADER) === '1';
if (! $key || ! $wanted || $request->attributes->has(self::SEALED_ATTRIBUTE) || ! $response instanceof JsonResponse) {
return $response;
}
$request->attributes->set(self::SEALED_ATTRIBUTE, true);
$response->setData(['enc' => ResponseCipher::seal($response->getContent(), $key)]);
return $response;
}
private function openRequest(Request $request, ?string $key): ?bool
{
$sealed = $request->isJson() ? $request->json('enc') : null;
if (! is_string($sealed)) {
return null;
}
$data = $key ? json_decode((string) ResponseCipher::open($sealed, $key), true) : null;
if (! is_array($data)) {
return false;
}
$request->json()->replace($data);
$request->request->replace($data);
return true;
}
}
@@ -47,8 +47,17 @@ class ServiceClientDetailResource extends JsonResource
*
* @return array<string, mixed>
*/
private function resolveSpecs($vm, $product): ?array
private function resolveSpecs($vm, $product, $custom = null): ?array
{
if ($custom) {
return [
'cpu' => (int) ($custom->cpu ?? 0),
'ram' => round(($custom->ram_mb ?? 0) / 1024, 2),
'disk' => (int) ($custom->disk_gb ?? 0),
'bandwidth' => (int) ($custom->bandwidth_gb ?? 0),
];
}
if ($vm && ($vm->cpu !== null || $vm->ram_mb !== null || $vm->disk_gb !== null)) {
return [
'cpu' => (int) ($vm->cpu ?? 0),
@@ -85,6 +94,8 @@ class ServiceClientDetailResource extends JsonResource
$order = $orderItem?->order;
$vm = $this->resource->vmware;
$product = $orderItem?->product ?? $this->resource->product;
$custom = $this->resource->customProduct;
$renewalSource = $custom ?? $product;
$hosting = $this->resource->hostingAccount;
$pleskCredentials = $hosting ? $this->resolvePleskCredentials($hosting) : null;
$dnsZone = $this->resolveDnsZone();
@@ -102,18 +113,21 @@ class ServiceClientDetailResource extends JsonResource
'version' => $orderItem?->os?->version ?? $vm?->os?->version,
'group' => $orderItem?->os?->osGroup?->name ?? $vm?->os?->osGroup?->name,
],
'specs' => $this->type === 'hosting' ? null : $this->resolveSpecs($vm, $product),
'specs' => $this->type === 'hosting' ? null : $this->resolveSpecs($vm, $product, $custom),
'service_plan' => $this->type === 'hosting' ? $product?->servicePlan?->summary() : null,
'custom_product' => $custom?->summary(),
'order' => $order ? [
'total' => (float) $order->total,
'months' => (int) $orderItem->months,
'billing_label' => $orderItem->billing_label,
'cycle_price' => (float) ($product?->pricings()
->where('billing_cycle', $orderItem->billing_cycle)
->where('is_active', 1)
->value('price') ?? 0),
'cycle_price' => $custom
? (float) $custom->unit_price * (int) $orderItem->months
: (float) ($product?->pricings()
->where('billing_cycle', $orderItem->billing_cycle)
->where('is_active', 1)
->value('price') ?? 0),
'addon_total' => \App\Support\RenewalPricing::addonTotal($this->resource, 1),
'renewal_options' => \App\Support\RenewalPricing::options($product),
'renewal_options' => \App\Support\RenewalPricing::options($renewalSource),
] : null,
'vm' => $vm ? [
'ip_address' => $vm->ipAddress?->ip ?? $vm->ip,