feat: improve admin virtual machine inventory and details

dev
admin 2 months ago
parent 5919dff9a9
commit 5905699742

@ -3,6 +3,9 @@
namespace App\Controllers\Admin;
use App\Controllers\AdminController;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudAdminInstanceService;
use App\Services\Cloud\CloudError;
/** Page shells only; the scoped JSON API owns authorisation and mutations. */
final class CloudPageController extends AdminController
@ -24,7 +27,32 @@ final class CloudPageController extends AdminController
public function instances($request, $response, $args)
{
return $this->view()->display('admin/cloud/instances.tpl');
$actor = CloudAccess::actor(false);
if (!($actor['is_admin'] ?? false)) {
return $response->withStatus(403)->withHeader('Cache-Control', 'private, no-store');
}
$payload = null;
$error = '';
$status = 200;
try {
$payload = CloudAdminInstanceService::page($actor, $request->getQueryParams());
} catch (CloudError $exception) {
$error = $exception->getMessage();
$status = $exception->httpStatus;
} catch (\Throwable $exception) {
error_log('Admin instance snapshot failed: ' . get_class($exception));
$error = '实例数据暂时无法读取,请稍后重试。';
$status = 503;
}
$smarty = $this->view()->assign([
'instance_page' => $payload,
'instance_error' => $error,
'instance_bootstrap_json' => json_encode($payload,
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
| JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR),
]);
$response->getBody()->write($smarty->fetch('admin/cloud/instances.tpl'));
return $response->withStatus($status)->withHeader('Cache-Control', 'private, no-store');
}
public function orders($request, $response, $args)

@ -0,0 +1,26 @@
<?php
namespace App\Controllers;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudAdminInstanceService;
/** Read-only database snapshots; live power state uses the existing VM API. */
final class CloudAdminInstanceController
{
public function index($request, $response)
{
return $response->withJson(CloudAdminInstanceService::page(
$request->getAttribute('cloud_actor') ?? CloudAccess::actor(false),
$request->getQueryParams()
))->withHeader('Cache-Control', 'private, no-store');
}
public function detail($request, $response, $args)
{
return $response->withJson(CloudAdminInstanceService::detail(
$request->getAttribute('cloud_actor') ?? CloudAccess::actor(false),
(string) ($args['id'] ?? '')
))->withHeader('Cache-Control', 'private, no-store');
}
}

@ -18,6 +18,7 @@ final class CloudApi
// cloud_sessions row.
$databaseOnly = preg_match('#^/api/v1/invoices(?:/|$)#D', $path) === 1
|| preg_match('#^/api/v1/admin/billing(?:/|$)#D', $path) === 1
|| preg_match('#^/api/v1/admin/instances(?:/|$)#D', $path) === 1
|| preg_match('#^/api/v1/ssh-keys(?:/|$)#D', $path) === 1
|| $path === '/api/v1/vms/page';
$actor = CloudAccess::actor(!$databaseOnly);

@ -0,0 +1,473 @@
<?php
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudInstance;
use App\Models\CloudInvoice;
use App\Models\CloudJob;
use App\Models\CloudOrder;
use App\Models\CloudServicePeriod;
use App\Services\AdminDataMasker;
/** Database-only administrator inventory. Never hydrate engine/session state. */
final class CloudAdminInstanceService
{
private const DETAIL_LIMIT = 20;
private const SERVICE_LABELS = [
'active' => '服务正常', 'exempt' => '免计费', 'expired' => '已到期',
'expired_grace' => '到期宽限期',
'suspending_expired' => '到期停用中', 'suspended_expired' => '到期已停用',
'suspend_failed' => '停用失败', 'resume_pending' => '等待恢复',
'resuming' => '恢复中', 'resume_failed' => '恢复失败',
'purge_stopping' => '清理前关机中', 'purge_stop_failed' => '清理前关机失败',
'purge_deleting' => '到期清理中', 'purge_failed' => '到期清理失败',
];
private const NETWORK_LABELS = [
'active' => '正常', 'blocked_traffic' => '流量耗尽已断网',
'blocking' => '正在限制网络', 'block_failed' => '限制网络失败',
'blocking_expired' => '到期断网中', 'blocked_expired' => '到期已断网',
'restore_pending' => '等待恢复网络', 'restoring' => '网络恢复中',
'restore_failed' => '网络恢复失败',
];
public static function page(array $actor, array $input = []): array
{
self::authorize($actor);
$filters = self::filters($input);
$now = time();
$query = self::baseQuery();
self::applyFilters($query, $filters, $now);
$summary = (clone $query)->selectRaw(
'COUNT(*) AS total, '
. "COALESCE(SUM(CASE WHEN cloud_instances.service_status <> 'exempt' "
. 'AND cloud_instances.expires_at > ? AND cloud_instances.expires_at <= ? '
. 'THEN 1 ELSE 0 END), 0) AS expiring, '
. "COALESCE(SUM(CASE WHEN cloud_instances.network_status <> 'active' "
. 'THEN 1 ELSE 0 END), 0) AS network_restricted, '
. 'COALESCE(SUM(CASE WHEN ' . self::attentionSql()
. ' THEN 1 ELSE 0 END), 0) AS attention',
[$now, $now + 7 * 86400, $now - 86400]
)->first();
$counts = [];
foreach (['total', 'expiring', 'network_restricted', 'attention'] as $key) {
$counts[$key] = max(0, (int) ($summary?->$key ?? 0));
}
$pages = max(1, (int) ceil($counts['total'] / $filters['per_page']));
$filters['page'] = min($filters['page'], $pages);
if ($filters['sort'] === 'expiry') {
$query->orderByRaw('CASE WHEN cloud_instances.expires_at IS NULL THEN 1 ELSE 0 END')
->orderBy('cloud_instances.expires_at')->orderBy('cloud_instances.id');
} else {
$direction = $filters['sort'] === 'oldest' ? 'asc' : 'desc';
$query->orderBy('cloud_instances.created_at', $direction)
->orderBy('cloud_instances.id', $direction);
}
$records = $query->select(self::columns())->selectRaw(
'(SELECT MAX(j.id) FROM cloud_jobs j WHERE '
. self::jobRelationSql('j')
. " AND j.status IN ('queued','running','uncertain')) AS active_job_id"
)->offset(($filters['page'] - 1) * $filters['per_page'])
->limit($filters['per_page'])->get();
$jobs = self::activeJobs($records);
$items = [];
foreach ($records as $instance) {
$items[] = self::row($instance, $actor,
$jobs[(string) $instance->active_job_id] ?? null, $now);
}
$hosts = [];
foreach (CloudHost::orderBy('name')->orderBy('id')->get(['id', 'name', 'region']) as $host) {
$hosts[] = ['id' => (string) $host->id, 'name' => (string) $host->name,
'region' => (string) $host->region];
}
$from = $counts['total'] === 0 ? 0
: ($filters['page'] - 1) * $filters['per_page'] + 1;
return [
'items' => $items,
'pagination' => ['page' => $filters['page'], 'per_page' => $filters['per_page'],
'total' => $counts['total'], 'total_pages' => $pages,
'from' => $from, 'to' => $from === 0 ? 0 : $from + count($items) - 1],
'summary' => $counts, 'filters' => $filters, 'hosts' => $hosts,
'generated_at' => $now,
];
}
public static function detail(array $actor, string $id): array
{
self::authorize($actor);
$id = self::positiveInteger($id, '实例编号');
$instance = self::baseQuery()->where('cloud_instances.id', $id)
->first(self::columns());
if ($instance === null) {
throw new CloudError('虚拟机不存在', 404);
}
// A creation task can predate the instance row. Only a verified order
// may supply that fallback; an explicit, different instance_id wins.
$orderId = null;
if ($instance->order_id !== null) {
$order = CloudOrder::where('id', $instance->order_id)
->where('user_id', $instance->user_id)
->where(static function ($query) use ($instance): void {
$query->whereNull('instance_id')->orWhere('instance_id', $instance->id);
})->first(['id']);
$orderId = $order?->id;
}
$relation = static function ($query) use ($instance, $orderId): void {
$query->where('instance_id', $instance->id);
if ($orderId !== null) {
$query->orWhere(static function ($fallback) use ($orderId): void {
$fallback->whereNull('instance_id')->where('order_id', $orderId);
});
}
};
// job.user_id is the action's actor, not necessarily the instance owner.
$jobRecords = CloudJob::where($relation)->orderByDesc('id')
->limit(self::DETAIL_LIMIT + 1)->get(self::jobColumns())->all();
$jobsTruncated = count($jobRecords) > self::DETAIL_LIMIT;
$jobs = array_map([self::class, 'jobRow'], array_slice($jobRecords, 0, self::DETAIL_LIMIT));
$active = CloudJob::where($relation)->whereIn('status', ['queued', 'running', 'uncertain'])
->orderByDesc('id')->first(self::jobColumns());
$invoiceRecords = CloudInvoice::where('user_id', $instance->user_id)
->where($relation)->orderByDesc('id')->limit(self::DETAIL_LIMIT + 1)
->get(['id', 'purpose', 'status', 'amount', 'created_at', 'due_at'])->all();
$invoicesTruncated = count($invoiceRecords) > self::DETAIL_LIMIT;
$now = time();
$invoices = [];
foreach (array_slice($invoiceRecords, 0, self::DETAIL_LIMIT) as $invoice) {
$status = (string) $invoice->status;
if ($status === 'open' && (int) $invoice->due_at <= $now) {
$status = 'overdue';
}
$invoices[] = ['id' => (string) $invoice->id,
'purpose' => (string) $invoice->purpose, 'status' => $status,
'amount' => self::money($invoice->amount),
'created_at' => max(0, (int) $invoice->created_at),
'detail_url' => '/admin/billing?detail=' . $invoice->id];
}
$row = self::row($instance, $actor, $active === null ? null : self::jobRow($active), $now);
$spec = self::spec($instance->spec_json);
$period = $instance->current_period_id === null ? null
: CloudServicePeriod::where('id', $instance->current_period_id)
->where('instance_id', $instance->id)->first(['starts_at', 'ends_at']);
$dns = is_array($spec['dns_servers'] ?? null) ? $spec['dns_servers'] : [];
$dns = array_values(array_filter(array_slice($dns, 0, 8),
static fn ($value): bool => is_string($value)
&& filter_var($value, FILTER_VALIDATE_IP) !== false));
$row += [
'public_ip_cidr' => self::text($spec['public_ip_cidr'] ?? null, 64),
'gateway' => self::ip($spec['gateway'] ?? null), 'dns_servers' => $dns,
'bandwidth_mbps' => self::positiveOrNull($spec['bandwidth_mbps'] ?? null),
'os_source' => self::text($spec['os_source'] ?? null, 32),
'login_name' => self::text($spec['login_name'] ?? null, 32),
// The engine can extend its UUID-derived name on collisions. Do
// not invent that name from a UUID when it was never persisted.
'engine_name' => self::resourceName($spec['engine_name'] ?? null),
'current_period_started_at' => $period === null ? null : (int) $period->starts_at,
'current_period_ends_at' => $period === null ? null : (int) $period->ends_at,
'renewal_price' => $instance->renewal_price === null ? null : self::money($instance->renewal_price),
'renewal_days' => max(0, (int) $instance->renewal_days),
'renewal_traffic_bytes' => max(0, (int) $instance->renewal_traffic_bytes),
'traffic_download_bytes' => max(0, (int) $instance->traffic_download_bytes),
'traffic_upload_bytes' => max(0, (int) $instance->traffic_upload_bytes),
'updated_at' => max(0, (int) $instance->updated_at),
];
return ['instance' => $row, 'jobs' => $jobs, 'jobs_truncated' => $jobsTruncated,
'invoices' => $invoices, 'invoices_truncated' => $invoicesTruncated];
}
public static function filters(array $input): array
{
$allowed = ['q', 'user_id', 'host_id', 'service_status', 'expiry', 'attention',
'sort', 'page', 'per_page'];
foreach ($input as $key => $value) {
if (!in_array($key, $allowed, true) || (!is_string($value) && !is_int($value))) {
throw new CloudError('筛选参数无效', 400);
}
}
$q = trim((string) ($input['q'] ?? ''));
if (mb_strlen($q, 'UTF-8') > 80 || preg_match('/[\x00-\x1f\x7f]/u', $q) !== 0) {
throw new CloudError('搜索关键词最多 80 个字符,且不能包含控制字符', 400);
}
$filters = ['q' => $q];
foreach (['user_id', 'host_id'] as $key) {
$value = (string) ($input[$key] ?? '');
$filters[$key] = $value === '' ? null : self::positiveInteger($value, $key);
}
foreach ([
'service_status' => array_merge([''], array_keys(self::SERVICE_LABELS)),
'expiry' => ['all', 'soon', 'expired', 'exempt'],
'attention' => ['all', 'network', 'jobs'],
'sort' => ['newest', 'oldest', 'expiry'],
] as $key => $values) {
$value = (string) ($input[$key] ?? $values[0]);
if (!in_array($value, $values, true)) {
throw new CloudError('筛选参数 ' . $key . ' 无效', 400);
}
$filters[$key] = $value;
}
$filters['page'] = self::positiveInteger((string) ($input['page'] ?? '1'), '页码');
$filters['per_page'] = self::positiveInteger((string) ($input['per_page'] ?? '20'), '每页条数');
if (!in_array($filters['per_page'], [20, 50, 100], true)) {
throw new CloudError('每页条数只能为 20、50 或 100', 400);
}
return $filters;
}
private static function authorize(array $actor): void
{
if (!($actor['is_admin'] ?? false)) {
throw new CloudError('需要管理员权限', 403);
}
}
private static function baseQuery()
{
return CloudInstance::where('cloud_instances.status', '<>', 'deleted')
->leftJoin('user as instance_user', 'instance_user.id', '=', 'cloud_instances.user_id')
->leftJoin('cloud_hosts as instance_host', 'instance_host.id', '=', 'cloud_instances.host_id')
->leftJoin('shop as instance_plan', 'instance_plan.id', '=', 'cloud_instances.plan_id');
}
private static function columns(): array
{
$columns = ['id', 'uuid', 'host_id', 'user_id', 'order_id', 'current_period_id',
'name', 'status', 'service_status', 'network_status', 'expires_at',
'renewal_price', 'renewal_days', 'renewal_traffic_bytes', 'traffic_quota_bytes',
'traffic_download_bytes', 'traffic_upload_bytes', 'traffic_synced_at',
'spec_json', 'created_at', 'updated_at'];
return array_merge(array_map(static fn ($key): string => 'cloud_instances.' . $key, $columns), [
'instance_user.user_name as owner_name', 'instance_user.email as owner_email',
'instance_host.name as host_name', 'instance_host.region as host_region',
'instance_plan.name as plan_name',
]);
}
private static function applyFilters($query, array $filters, int $now): void
{
foreach (['user_id', 'host_id'] as $key) {
if ($filters[$key] !== null) {
$query->where('cloud_instances.' . $key, $filters[$key]);
}
}
if ($filters['service_status'] !== '') {
$query->where('cloud_instances.service_status', $filters['service_status']);
}
if ($filters['expiry'] === 'exempt') {
$query->where('cloud_instances.service_status', 'exempt');
} elseif ($filters['expiry'] === 'soon') {
$query->where('cloud_instances.service_status', '<>', 'exempt')
->where('cloud_instances.expires_at', '>', $now)
->where('cloud_instances.expires_at', '<=', $now + 7 * 86400);
} elseif ($filters['expiry'] === 'expired') {
$query->where('cloud_instances.service_status', '<>', 'exempt')
->whereNotNull('cloud_instances.expires_at')->where('cloud_instances.expires_at', '<=', $now);
}
if ($filters['attention'] === 'network') {
$query->where('cloud_instances.network_status', '<>', 'active');
} elseif ($filters['attention'] === 'jobs') {
$query->whereRaw(self::attentionSql(), [$now - 86400]);
}
if ($filters['q'] === '') {
return;
}
$like = '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $filters['q']) . '%';
$query->where(static function ($search) use ($filters, $like): void {
$search->whereRaw("cloud_instances.name LIKE ? ESCAPE '!'", [$like])
->orWhereRaw("cloud_instances.uuid LIKE ? ESCAPE '!'", [$like]);
foreach (['public_ip_cidr', 'public_ip'] as $key) {
// CASE also permits searching databases containing a damaged
// old specification without calling JSON_EXTRACT on it.
$search->orWhereRaw("(CASE WHEN JSON_VALID(cloud_instances.spec_json) "
. "THEN JSON_EXTRACT(cloud_instances.spec_json, '$." . $key . "') "
. "ELSE '' END) LIKE ? ESCAPE '!'", [$like]);
}
if (preg_match('/^[1-9][0-9]*$/D', $filters['q']) === 1
&& strlen($filters['q']) < 19) {
$search->orWhere('cloud_instances.id', (int) $filters['q'])
->orWhere('cloud_instances.user_id', (int) $filters['q']);
}
// Match the billing search privacy boundary: readonly operators
// must not infer a masked account via repeated keyword searches.
if (!AdminDataMasker::shouldMask()) {
$search->orWhereRaw("instance_user.user_name LIKE ? ESCAPE '!'", [$like])
->orWhereRaw("instance_user.email LIKE ? ESCAPE '!'", [$like]);
}
});
}
private static function jobRelationSql(string $alias): string
{
return '(' . $alias . '.instance_id = cloud_instances.id OR (' . $alias
. '.instance_id IS NULL AND ' . $alias . '.order_id = cloud_instances.order_id '
. 'AND EXISTS (SELECT 1 FROM cloud_orders job_order WHERE '
. 'job_order.id = cloud_instances.order_id '
. 'AND job_order.user_id = cloud_instances.user_id '
. 'AND (job_order.instance_id IS NULL OR job_order.instance_id = cloud_instances.id))))';
}
private static function attentionSql(): string
{
return 'EXISTS (SELECT 1 FROM cloud_jobs attention_job WHERE '
. self::jobRelationSql('attention_job')
. " AND (attention_job.status = 'uncertain' OR (attention_job.status = 'failed' "
. 'AND attention_job.updated_at >= ?)))';
}
private static function activeJobs($records): array
{
$ids = $records->pluck('active_job_id')->filter()->unique()->values()->all();
$result = [];
if ($ids !== []) {
foreach (CloudJob::whereIn('id', $ids)->get(self::jobColumns()) as $job) {
$result[(string) $job->id] = self::jobRow($job);
}
}
return $result;
}
private static function jobColumns(): array
{
return ['id', 'kind', 'status', 'attempts', 'error_code', 'result_json', 'created_at', 'updated_at'];
}
private static function jobRow($job): array
{
$result = json_decode((string) $job->result_json, true);
return ['id' => (string) $job->id, 'kind' => (string) $job->kind,
'status' => (string) $job->status, 'attempts' => max(0, (int) $job->attempts),
'error' => self::jobText($job->error_code),
'phase' => self::jobText(is_array($result) ? ($result['phase'] ?? null) : null),
'created_at' => max(0, (int) $job->created_at),
'updated_at' => max(0, (int) $job->updated_at)];
}
private static function row($instance, array $actor, ?array $job, int $now): array
{
$spec = self::spec($instance->spec_json);
$cidr = self::text($spec['public_ip_cidr'] ?? null, 64);
$publicIp = self::ip($cidr === null ? ($spec['public_ip'] ?? null) : explode('/', $cidr, 2)[0]);
$service = (string) $instance->service_status;
$expires = $instance->expires_at === null ? null : (int) $instance->expires_at;
$used = max(0, (int) $instance->traffic_download_bytes) + max(0, (int) $instance->traffic_upload_bytes);
$quota = max(0, (int) $instance->traffic_quota_bytes);
$row = [
'id' => (string) $instance->id, 'name' => (string) $instance->name,
'uuid' => (string) $instance->uuid, 'user_id' => (string) $instance->user_id,
'user_name' => AdminDataMasker::account($instance->owner_name ?? ''),
'user_email' => AdminDataMasker::email($instance->owner_email ?? ''),
'user_url' => ($actor['is_super_admin'] ?? false) && ($actor['can_manage'] ?? false)
? '/admin/user/' . $instance->user_id . '/edit' : '',
'host_id' => (string) $instance->host_id, 'host_name' => (string) ($instance->host_name ?? ''),
'region' => self::text($instance->host_region, 64)
?? self::text($spec['region'] ?? $spec['location'] ?? null, 64) ?? '',
'plan_name' => self::text($spec['plan_name'] ?? null, 120)
?? self::text($instance->plan_name, 120) ?? '',
'os_name' => self::text($spec['os_name'] ?? $spec['install_iso'] ?? null, 255) ?? '',
'public_ip' => $publicIp ?? '',
'vcpu' => self::positiveOrNull($spec['vcpu'] ?? null),
'memory_mib' => self::positiveOrNull($spec['memory_mib'] ?? null),
'disk_gib' => self::positiveOrNull($spec['disk_gib'] ?? null),
'instance_status' => (string) $instance->status, 'service_status' => $service,
'network_status' => (string) $instance->network_status, 'service_expires_at' => $expires,
'traffic_used_bytes' => $used, 'traffic_quota_bytes' => $quota,
'traffic_synced_at' => max(0, (int) $instance->traffic_synced_at),
'created_at' => max(0, (int) $instance->created_at), 'active_job' => $job,
'state' => 'unknown',
'can_manage' => ($actor['is_admin'] ?? false) && ($actor['is_super_admin'] ?? false)
&& ($actor['can_manage'] ?? false),
'detail_url' => '/user/cloud/instances/' . $instance->id,
];
$row['display'] = [
'configuration' => ($row['vcpu'] === null ? '—' : $row['vcpu'] . ' 核') . ' · '
. ($row['memory_mib'] === null ? '—' : self::number($row['memory_mib'] / 1024) . ' GiB') . ' · '
. ($row['disk_gib'] === null ? '—' : self::number($row['disk_gib']) . ' GiB'),
'traffic' => $row['traffic_synced_at'] === 0 ? '未获取'
: self::bytes($used) . ($service === 'exempt' ? ' · 免计费' : ' / ' . self::bytes($quota)),
'expiry' => $service === 'exempt' ? '免计费' : ($expires === null ? '—'
: ($expires <= $now ? '已到期' : '剩余 ' . (int) ceil(($expires - $now) / 86400) . ' 天')),
'service' => $service === 'active' && $expires === null ? '期限未记录'
: ($service === 'active' && $expires <= $now
? '已到期' : (self::SERVICE_LABELS[$service] ?? '未知')),
'network' => self::NETWORK_LABELS[(string) $instance->network_status] ?? '未知',
'lifecycle' => ['active' => '在管', 'deleting' => '删除中', 'delete_failed' => '删除失败']
[(string) $instance->status] ?? '未知',
];
return $row;
}
private static function spec($json): array
{
$value = json_decode((string) $json, true);
return CloudInstanceMetadata::sanitizeSpec(is_array($value) && !array_is_list($value) ? $value : []);
}
private static function positiveInteger(string $value, string $label): int
{
if (preg_match('/^[1-9][0-9]*$/D', $value) !== 1
|| filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) === false) {
throw new CloudError($label . ' 无效', 400);
}
return (int) $value;
}
private static function positiveOrNull($value): ?float
{
if ((!is_int($value) && !is_float($value) && !is_string($value)) || !is_numeric($value)) {
return null;
}
$number = (float) $value;
return is_finite($number) && $number > 0 && $number <= 1048576 ? $number : null;
}
private static function text($value, int $limit): ?string
{
if (!is_string($value) || trim($value) === '' || preg_match('/[\x00-\x1f\x7f]/u', $value) !== 0) {
return null;
}
return mb_substr(trim($value), 0, $limit, 'UTF-8');
}
private static function ip($value): ?string
{
return is_string($value) && filter_var($value, FILTER_VALIDATE_IP) !== false ? $value : null;
}
private static function resourceName($value): ?string
{
return is_string($value) && preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$/D', $value) === 1
? $value : null;
}
private static function jobText($value): ?string
{
$text = self::text($value, 300);
if ($text === null) {
return null;
}
// Progress text is not a credential viewer, even for superadmins.
$text = preg_replace('/\bBearer\s+\S+/i', 'Bearer [已移除]', $text);
$text = preg_replace('#(https?://[^:/\s]+:)[^@\s/]+@#i', '$1[已移除]@', $text);
$text = preg_replace('/((?:"|\x27)?(?:password|passwd|api[_ -]?key|access[_ -]?token|refresh[_ -]?token|token|secret|credential|private[_ -]?key)(?:"|\x27)?\s*[:=]\s*)(?:"[^"]*"|\x27[^\x27]*\x27|[^\s,;]+)/i', '$1[已移除]', $text);
return AdminDataMasker::sensitiveText($text);
}
private static function bytes(int $bytes): string
{
foreach (['TiB' => 1099511627776, 'GiB' => 1073741824, 'MiB' => 1048576, 'KiB' => 1024] as $unit => $factor) {
if ($bytes >= $factor) {
return self::number($bytes / $factor) . ' ' . $unit;
}
}
return $bytes . ' B';
}
private static function number(float $value): string
{
return rtrim(rtrim(number_format($value, 2, '.', ''), '0'), '.');
}
private static function money($value): string
{
return CloudMoney::decimal(CloudMoney::cents($value));
}
}

@ -47,6 +47,8 @@ $app->group('/api/v1', function () {
$this->map(['GET', 'POST'], '/ssh-keys', 'App\Controllers\CloudApiController:sshKeys');
$this->delete('/ssh-keys/{id:[0-9]+}', 'App\Controllers\CloudApiController:deleteKey');
$this->post('/admin/hosts/scan', 'App\Controllers\CloudAdminController:scan');
$this->get('/admin/instances', 'App\Controllers\CloudAdminInstanceController:index');
$this->get('/admin/instances/{id:[0-9]+}', 'App\Controllers\CloudAdminInstanceController:detail');
$this->get('/admin/billing/invoices',
'App\Controllers\CloudAdminBillingController:invoices');
$this->get('/admin/billing/invoices/{id:[0-9]+}',

@ -786,6 +786,9 @@ function initialize() {
loadFiltersFromUrl();
bindEvents();
void loadList(true);
// Instance management links to this existing detail view by exact invoice ID.
const linkedInvoice = params.get('detail') || '';
if (/^[1-9][0-9]{0,18}$/.test(linkedInvoice)) void openDetail(linkedInvoice);
}
initialize();

@ -0,0 +1,502 @@
const root = document.querySelector('[data-admin-instances]');
const byId = id => document.getElementById(id);
const columns = ['实例', '用户', '所在位置', '公网 IP', '配置', '状态', '用量与期限', '操作'];
const tabs = ['basic', 'service', 'jobs', 'invoices'];
const filterNames = ['q', 'user_id', 'host_id', 'service_status', 'expiry', 'attention', 'sort', 'per_page'];
const state = {
items: [], pagination: { page: 1, per_page: 20, total: 0, total_pages: 1 },
request: null, serial: 0, loading: false, hasData: false, active: true, timer: null,
statusRequest: null, statusFailures: 0, detailRequest: null, detailId: null,
opener: null, scroll: null,
};
function el(tag, className = '', text) {
const node = document.createElement(tag);
node.className = className;
if (text !== undefined) node.textContent = String(text);
return node;
}
function text(...values) {
return values.find(value => value !== null && value !== undefined && String(value).trim() !== '') ?? '—';
}
function stack(primary, secondary) {
const node = el('span', 'admin-checkout-user');
node.append(primary instanceof Node ? primary : el('strong', '', text(primary)));
if (secondary) node.append(el('span', '', secondary));
return node;
}
function safeLink(value, label, className = '') {
try {
const url = new URL(value, location.origin);
if (url.origin !== location.origin || !/^https?:$/.test(url.protocol)) throw new Error('Unsafe URL');
const link = el('a', className, label);
link.href = url.pathname + url.search + url.hash;
return link;
} catch { return el('span', className, label); }
}
function date(value, short = false) {
if (!value) return '未记录';
const numeric = Number(value);
const timestamp = Number.isFinite(numeric) ? numeric * (numeric < 1e12 ? 1000 : 1) : Date.parse(value);
const parsed = new Date(timestamp);
if (!Number.isFinite(parsed.getTime())) return '未记录';
return short ? parsed.toLocaleDateString('zh-CN') : parsed.toLocaleString('zh-CN', { hour12: false });
}
function bytes(value) {
const number = Number(value);
if (value === null || value === undefined || !Number.isFinite(number) || number < 0) return '未记录';
if (number === 0) return '0 B';
const exponent = Math.min(4, Math.floor(Math.log(number) / Math.log(1024)));
return `${(number / 1024 ** exponent).toLocaleString('zh-CN', { maximumFractionDigits: 2 })} ${['B', 'KiB', 'MiB', 'GiB', 'TiB'][exponent]}`;
}
function notice(message, error = false) {
const node = byId('instances-notice');
node.textContent = message;
node.className = `admin-config-status ${error ? 'is-error' : 'is-success'}`;
node.setAttribute('role', error ? 'alert' : 'status');
}
async function api(path, controller) {
const timeout = setTimeout(() => controller.abort('timeout'), 30000);
try {
const response = await fetch(path, {
headers: { Accept: 'application/json' }, credentials: 'same-origin', cache: 'no-store', signal: controller.signal,
});
if (response.status === 401) throw new Error('登录已过期,请重新登录后刷新。');
let payload;
try { payload = await response.json(); }
catch { throw new Error('服务返回异常,请检查服务器日志后重试。'); }
if (!response.ok || payload?.ret === 0) {
throw new Error(typeof payload?.detail === 'string' ? payload.detail : (payload?.message || `请求失败 (${response.status})`));
}
return payload;
} catch (error) {
if (controller.signal.reason === 'timeout') throw new Error('请求超时,请稍后重试。');
throw error;
} finally { clearTimeout(timeout); }
}
function copyButton(value, label = '复制') {
const button = el('button', 'btn btn-light btn-sm');
button.type = 'button';
button.dataset.copy = String(value);
button.setAttribute('aria-label', `${label} ${value}`);
const icon = el('i', 'mdi mdi-content-copy');
icon.setAttribute('aria-hidden', 'true');
button.append(icon);
return button;
}
function powerInfo(value) {
return ({
running: ['运行中', 'success'], blocked: ['运行中', 'success'],
shutoff: ['已关机', 'secondary'], stopped: ['已关机', 'secondary'],
shutdown: ['关机中', 'warning'], paused: ['已暂停', 'warning'],
pmsuspended: ['已挂起', 'warning'], crashed: ['已崩溃', 'danger'],
})[String(value || '').toLowerCase()] || ['状态未知', 'secondary'];
}
function paintPower(node, vm) {
const [label, tone] = powerInfo(vm.state);
node.textContent = `电源:${label}`;
node.className = `badge bg-${tone}-subtle text-${tone}-emphasis`;
node.title = vm.live_state_available === true ? '来自宿主机的实时电源状态' : '尚未获取实时状态,或宿主机暂时不可达;不表示已关机。';
}
function jobStatus(value) {
return ({ queued: '已排队', pending: '待处理', running: '执行中', uncertain: '待核对',
succeeded: '已完成', completed: '已完成', failed: '失败', cancelled: '已取消' })[value] || text(value);
}
function jobKind(value) {
return ({ create: '创建实例', provision: '开通', action: '电源操作', start: '开机', shutdown: '关机', reboot: '重启',
destroy: '强制断电', reset: '强制重置', reinstall: '重装', delete: '删除',
suspend: '暂停网络', resume: '恢复网络', rescue: '救援',
service_suspend: '到期停用', service_resume: '服务恢复',
network_suspend: '限制网络', network_resume: '恢复网络', expiry_delete: '到期清理',
})[value] || text(value, '操作任务');
}
function row(vm) {
const tr = el('tr');
tr.dataset.instanceId = String(vm.id);
const ip = el('span', 'admin-instance-ip');
ip.append(el('span', 'admin-mono', text(vm.public_ip, '未记录')));
if (vm.public_ip) ip.append(copyButton(vm.public_ip, '复制公网 IP'));
const statuses = el('div', 'admin-instance-status');
const power = el('span');
power.dataset.powerStatus = '';
paintPower(power, vm);
statuses.append(power, el('span', 'fs-12', `服务:${text(vm.display?.service)}`),
el('span', 'fs-12', `网络:${text(vm.display?.network)}`));
if (vm.active_job) statuses.append(el('span', 'text-warning fs-12', `任务 #${vm.active_job.id} · ${jobStatus(vm.active_job.status)}`));
const detail = el('button', 'btn btn-primary btn-sm', '查看详情');
detail.type = 'button';
detail.dataset.instanceDetail = String(vm.id);
detail.setAttribute('aria-label', `查看 ${text(vm.name)} 的详情`);
const usage = stack(vm.display?.traffic, vm.display?.expiry);
if (vm.service_expires_at && vm.service_status !== 'exempt') usage.append(el('span', '', `到期 ${date(vm.service_expires_at, true)}`));
const cells = [
stack(text(vm.name), `#${vm.id} · ${text(vm.os_name, '系统未记录')}`),
stack(vm.user_url ? safeLink(vm.user_url, text(vm.user_name, `用户 #${vm.user_id}`)) : text(vm.user_name), `ID ${vm.user_id}`),
stack(text(vm.host_name, `宿主机 #${vm.host_id}`), text(vm.region, '地区未记录')),
ip, stack(vm.display?.configuration, text(vm.plan_name, '无关联套餐')),
statuses, usage, detail,
];
cells.forEach((content, index) => {
const td = el('td');
td.dataset.label = columns[index];
td.append(content);
tr.append(td);
});
return tr;
}
function renderRows() {
const body = byId('instances-body');
body.replaceChildren();
state.items.forEach(vm => body.append(row(vm)));
if (!state.items.length) {
const tr = el('tr');
const td = el('td', 'text-center text-muted py-4', '没有符合条件的实例。');
td.colSpan = columns.length;
tr.append(td); body.append(tr);
}
}
function renderPagination() {
const page = state.pagination;
byId('instances-count').textContent = state.hasData ? `共 ${page.total} 台` : '数据未获取';
byId('instances-page-label').textContent = state.hasData
? `第 ${page.page} / ${page.total_pages} 页 · 共 ${page.total} 台` : '实例数据暂不可用';
byId('instances-previous').disabled = !state.hasData || state.loading || page.page <= 1;
byId('instances-next').disabled = !state.hasData || state.loading || page.page >= page.total_pages;
byId('instances-refresh').disabled = state.loading;
byId('instances-body').setAttribute('aria-busy', String(state.loading));
}
function syncForm(payload) {
const form = byId('instances-filter');
const hosts = form.elements.namedItem('host_id');
hosts.replaceChildren(new Option('全部宿主机', ''));
for (const host of payload.hosts || []) hosts.add(new Option(`${host.name}${host.region ? ` · ${host.region}` : ''}`, host.id));
for (const name of filterNames) {
const control = form.elements.namedItem(name);
const value = String(name === 'per_page' ? payload.pagination.per_page : (payload.filters?.[name] ?? ''));
if (control instanceof HTMLSelectElement && value && !Array.from(control.options).some(option => option.value === value)) {
control.add(new Option(value, value));
}
control.value = value || ({ expiry: 'all', attention: 'all', sort: 'newest' })[name] || '';
}
}
function applyPayload(payload, replaceRows = true) {
if (!Array.isArray(payload?.items) || !payload?.pagination) throw new Error('实例数据格式无效,请重试。');
state.items = payload.items;
state.pagination = payload.pagination;
state.hasData = true;
for (const key of ['total', 'expiring', 'network_restricted', 'attention']) {
byId(`instances-${key.replaceAll('_', '-')}`).textContent = Number(payload.summary?.[key] ?? 0).toLocaleString('zh-CN');
}
syncForm(payload);
if (replaceRows) renderRows();
renderPagination();
}
function formUrl(page = 1) {
const url = new URL(location.pathname, location.origin);
const form = byId('instances-filter');
for (const key of filterNames) {
const value = form.elements.namedItem(key).value.trim();
if (value && value !== 'all' && !(key === 'sort' && value === 'newest')) url.searchParams.set(key, value);
}
if (page > 1) url.searchParams.set('page', String(page));
return url;
}
function stopStatuses() {
clearTimeout(state.timer);
state.timer = null;
state.statusRequest?.abort();
state.statusRequest = null;
}
function scheduleStatuses() {
clearTimeout(state.timer);
if (!state.active || document.hidden || !state.items.length || state.loading) return;
state.timer = setTimeout(refreshStatuses, Math.min(120000, 30000 * 2 ** state.statusFailures));
}
async function refreshStatuses() {
if (!state.active || document.hidden || state.loading || state.statusRequest || !state.items.length) return;
const controller = new AbortController();
state.statusRequest = controller;
const serial = state.serial;
byId('instances-live-status').textContent = '正在更新当前页电源状态…';
try {
const ids = state.items.map(vm => vm.id).join(',');
const payload = await api(`/api/v1/vms/statuses?ids=${encodeURIComponent(ids)}`, controller);
if (controller.signal.aborted || serial !== state.serial) return;
const updates = Array.isArray(payload?.vms) ? payload.vms : [];
let unknown = 0;
for (const vm of state.items) {
const update = updates.find(item => String(item.api_id ?? item.id) === String(vm.id) && item.uuid === vm.uuid);
vm.state = update?.state || 'unknown';
vm.live_state_available = update?.live_state_available === true;
if (!vm.live_state_available) unknown += 1;
const rowNode = Array.from(byId('instances-body').rows).find(node => node.dataset.instanceId === String(vm.id));
const badge = rowNode?.querySelector('[data-power-status]');
if (badge) paintPower(badge, vm);
}
state.statusFailures = 0;
byId('instances-live-status').textContent = `电源状态更新于 ${new Date().toLocaleTimeString('zh-CN')}${unknown ? ` · ${unknown} 台状态未知(宿主机暂不可达或未获取)` : ''}`;
} catch (error) {
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
if (serial !== state.serial) return;
state.statusFailures = Math.min(2, state.statusFailures + 1);
for (const vm of state.items) { vm.state = 'unknown'; vm.live_state_available = false; }
root.querySelectorAll('[data-power-status]').forEach(node => paintPower(node, { state: 'unknown' }));
byId('instances-live-status').textContent = `${error.message} 列表已保留,电源状态暂未知。`;
} finally {
if (state.statusRequest === controller) { state.statusRequest = null; scheduleStatuses(); }
}
}
async function loadPage(url, historyMode = 'push') {
state.request?.abort();
stopStatuses();
const controller = new AbortController();
state.request = controller;
const serial = ++state.serial;
state.loading = true;
renderPagination();
notice('正在读取实例数据…');
try {
const payload = await api(`/api/v1/admin/instances${url.search}`, controller);
if (controller.signal.aborted || serial !== state.serial) return;
applyPayload(payload);
const canonical = formUrl(payload.pagination.page);
if (historyMode === 'push' && canonical.href !== location.href) history.pushState(null, '', canonical);
notice(`已读取 ${payload.pagination.total} 台实例 · ${new Date().toLocaleTimeString('zh-CN')}`);
} catch (error) {
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
if (serial === state.serial) notice(`${error.message} 已保留原列表。`, true);
} finally {
if (serial === state.serial) {
state.loading = false;
state.request = null;
renderPagination();
void refreshStatuses();
}
}
}
function infoList(entries) {
const list = el('dl', 'admin-instance-details');
entries.forEach(([label, value]) => {
list.append(el('dt', '', label));
const dd = el('dd');
dd.append(value instanceof Node ? value : document.createTextNode(String(text(value))));
list.append(dd);
});
return list;
}
function chooseTab(name, focus = false) {
tabs.forEach(tab => {
const button = byId(`instance-tab-${tab}`);
button.setAttribute('aria-selected', String(tab === name));
button.tabIndex = tab === name ? 0 : -1;
byId(`instance-panel-${tab}`).hidden = tab !== name;
});
if (focus) byId(`instance-tab-${name}`).focus();
}
function detailNotice(message, error = false) {
const node = byId('instance-detail-notice');
node.textContent = message;
node.hidden = !message;
node.className = `alert alert-${error ? 'danger' : 'info'}`;
node.setAttribute('role', error ? 'alert' : 'status');
}
function renderDetail(payload) {
const vm = payload.instance;
if (!vm || String(vm.id) !== state.detailId) throw new Error('实例详情与请求不一致,请重新打开。');
byId('instance-detail-title').textContent = text(vm.name, `实例 #${vm.id}`);
const uuid = el('span', 'admin-instance-ip text-break');
uuid.append(el('span', 'admin-mono', text(vm.uuid)));
if (vm.uuid) uuid.append(copyButton(vm.uuid, '复制 UUID'));
byId('instance-panel-basic').replaceChildren(infoList([
['实例编号', `#${vm.id}`], ['UUID', uuid], ['引擎标识', text(vm.engine_name, '未记录')],
['生命周期', vm.display?.lifecycle], ['所属用户', text(vm.user_name, `用户 #${vm.user_id}`)],
['用户 ID', vm.user_id], ['宿主机', text(vm.host_name)], ['地区', text(vm.region, '未记录')],
['操作系统', text(vm.os_name, '未记录')], ['配置', vm.display?.configuration],
['公网地址', text(vm.public_ip_cidr, vm.public_ip, '未记录')], ['网关', text(vm.gateway, '未记录')],
['DNS', Array.isArray(vm.dns_servers) ? text(vm.dns_servers.join('、'), '未记录') : text(vm.dns_servers, '未记录')],
['带宽上限', vm.bandwidth_mbps ? `${vm.bandwidth_mbps} Mbps` : '未记录'],
['创建时间', date(vm.created_at)],
]));
byId('instance-panel-service').replaceChildren(infoList([
['套餐', text(vm.plan_name, '无关联套餐')], ['服务状态', vm.display?.service], ['网络状态', vm.display?.network],
['服务到期', vm.service_status === 'exempt' ? '免计费' : date(vm.service_expires_at)],
['剩余期限', vm.display?.expiry], ['本周期用量', vm.display?.traffic],
['下载流量', Number(vm.traffic_synced_at) > 0 ? bytes(vm.traffic_download_bytes) : '未采集'],
['上传流量', Number(vm.traffic_synced_at) > 0 ? bytes(vm.traffic_upload_bytes) : '未采集'],
['采集时间', date(vm.traffic_synced_at)], ['当前周期开始', date(vm.current_period_started_at)],
['当前周期结束', date(vm.current_period_ends_at)],
['续费价格', vm.renewal_price !== null && vm.renewal_price !== undefined ? `$${Number(vm.renewal_price).toFixed(2)}` : '不适用'],
['续费周期', vm.renewal_days ? `${vm.renewal_days} 天` : '不适用'],
['续费流量', vm.service_status === 'exempt' ? '不适用' : bytes(vm.renewal_traffic_bytes)],
]));
const jobs = byId('instance-panel-jobs');
jobs.replaceChildren();
for (const job of payload.jobs || []) {
const card = el('article', 'card mb-3');
const body = el('div', 'card-body');
body.append(el('h3', 'h6', `#${job.id} · ${jobKind(job.kind)} · ${jobStatus(job.status)}`),
infoList([['尝试次数', job.attempts ?? 0], ['阶段', text(job.phase, '未记录')],
['开始时间', date(job.created_at)], ['更新时间', date(job.updated_at)]]));
if (job.error) body.append(el('p', 'text-danger text-break mb-0', job.error));
card.append(body); jobs.append(card);
}
if (!payload.jobs?.length) jobs.append(el('p', 'text-muted py-3', '暂无任务记录。'));
if (payload.jobs_truncated) jobs.append(el('p', 'text-muted fs-12', '仅展示最近的任务记录。'));
const invoices = byId('instance-panel-invoices');
invoices.replaceChildren();
for (const invoice of payload.invoices || []) {
const card = el('article', 'card mb-3');
const body = el('div', 'card-body');
const purpose = ({ provision: '实例开通', renewal: '实例续费' })[invoice.purpose] || text(invoice.purpose, '账单');
const status = ({ open: '待支付', paid: '已支付', overdue: '已逾期', refunded: '已退款', expired: '已失效', void: '已作废' })[invoice.status] || text(invoice.status);
body.append(el('h3', 'h6', `账单 #${invoice.id} · ${purpose}`),
el('p', 'mb-2', `$${Number(invoice.amount).toFixed(2)} · ${status}`),
el('p', 'text-muted fs-12', date(invoice.created_at)));
if (invoice.detail_url) body.append(safeLink(invoice.detail_url, '查看账单', 'btn btn-light btn-sm'));
card.append(body); invoices.append(card);
}
if (!payload.invoices?.length) invoices.append(el('p', 'text-muted py-3', '暂无关联账单;导入或免计费实例可能没有开通账单。'));
if (payload.invoices_truncated) invoices.append(el('p', 'text-muted fs-12', '仅展示最近的关联账单。'));
const control = byId('instance-control-link');
const link = vm.can_manage && vm.detail_url ? safeLink(vm.detail_url, '') : null;
control.hidden = !(link instanceof HTMLAnchorElement);
if (link instanceof HTMLAnchorElement) control.href = link.href;
byId('instance-detail-permission').textContent = vm.can_manage
? '电源、VNC、重装等操作在实例控制台进行,继续使用原权限校验与确认步骤。'
: '当前管理员仅可查看;全局实例操作需超级管理员权限。';
}
function lockDetailScroll() {
state.scroll = { x: window.scrollX, y: window.scrollY };
document.body.style.setProperty('--admin-instance-scroll-top', `${-state.scroll.y}px`);
document.documentElement.classList.add('admin-instance-detail-open');
}
function closeDetail() {
state.detailRequest?.abort();
state.detailRequest = null;
state.detailId = null;
const dialog = byId('instance-detail');
if (dialog.open) dialog.close();
document.documentElement.classList.remove('admin-instance-detail-open');
document.body.style.removeProperty('--admin-instance-scroll-top');
if (state.scroll) {
window.scrollTo({ left: state.scroll.x, top: state.scroll.y, behavior: 'instant' });
state.scroll = null;
}
if (state.opener?.isConnected) state.opener.focus({ preventScroll: true });
state.opener = null;
}
async function openDetail(id, opener) {
if (!/^[1-9][0-9]*$/.test(id)) return;
state.detailRequest?.abort();
state.detailId = id;
state.opener = opener;
const controller = new AbortController();
state.detailRequest = controller;
byId('instance-detail-title').textContent = `实例 #${id}`;
byId('instance-control-link').hidden = true;
byId('instance-detail-permission').textContent = '当前详情为只读信息。';
tabs.forEach(tab => byId(`instance-panel-${tab}`).replaceChildren());
chooseTab('basic');
detailNotice('正在读取详情…');
if (!byId('instance-detail').open) { lockDetailScroll(); byId('instance-detail').showModal(); }
try {
const payload = await api(`/api/v1/admin/instances/${id}`, controller);
if (controller.signal.aborted || state.detailId !== id) return;
renderDetail(payload);
detailNotice('');
} catch (error) {
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
if (state.detailId === id) detailNotice(`${error.message} 请关闭后重试。`, true);
} finally { if (state.detailRequest === controller) state.detailRequest = null; }
}
async function copy(value) {
try {
if (!navigator.clipboard?.writeText) throw new Error('Clipboard unavailable');
await navigator.clipboard.writeText(value);
notice('已复制。');
if (byId('instance-detail').open) detailNotice('已复制。');
} catch {
const message = '复制失败,请长按或选中文本手动复制。';
notice(message, true);
if (byId('instance-detail').open) detailNotice(message, true);
}
}
if (root) {
let bootstrapped = false;
try { applyPayload(JSON.parse(byId('admin-instances-bootstrap').textContent), false); bootstrapped = true; }
catch { notice('初始数据读取失败,正在重试…', true); }
byId('instances-filter').addEventListener('submit', event => { event.preventDefault(); void loadPage(formUrl()); });
byId('instances-reset').addEventListener('click', event => {
if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
event.preventDefault(); void loadPage(new URL(location.pathname, location.origin));
});
byId('instances-refresh').addEventListener('click', () => { void loadPage(new URL(location.href), 'none'); });
byId('instances-previous').addEventListener('click', () => { void loadPage(formUrl(state.pagination.page - 1)); });
byId('instances-next').addEventListener('click', () => { void loadPage(formUrl(state.pagination.page + 1)); });
root.addEventListener('click', event => {
const detail = event.target.closest('[data-instance-detail]');
if (detail) void openDetail(detail.dataset.instanceDetail, detail);
const button = event.target.closest('[data-copy]');
if (button) void copy(button.dataset.copy);
});
const dialog = byId('instance-detail');
byId('instance-detail-close').addEventListener('click', closeDetail);
dialog.addEventListener('cancel', event => { event.preventDefault(); closeDetail(); });
dialog.addEventListener('click', event => {
if (event.target === dialog) {
const rect = dialog.getBoundingClientRect();
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) closeDetail();
}
const tab = event.target.closest('[data-instance-tab]');
if (tab) chooseTab(tab.dataset.instanceTab);
const button = event.target.closest('[data-copy]');
if (button) void copy(button.dataset.copy);
const link = event.target.closest('a[href]');
if (link && !event.defaultPrevented && event.button === 0 && !event.ctrlKey && !event.metaKey
&& !event.shiftKey && !event.altKey && (!link.target || link.target === '_self')) closeDetail();
});
dialog.addEventListener('keydown', event => {
if (!event.target.matches('[data-instance-tab]')) return;
const index = tabs.indexOf(event.target.dataset.instanceTab);
const next = ({ ArrowRight: (index + 1) % tabs.length, ArrowLeft: (index + tabs.length - 1) % tabs.length, Home: 0, End: tabs.length - 1 })[event.key];
if (next !== undefined) { event.preventDefault(); chooseTab(tabs[next], true); }
});
// Native modal dialog traps focus; background scrolling is locked separately for iOS.
window.addEventListener('popstate', () => { closeDetail(); void loadPage(new URL(location.href), 'none'); });
document.addEventListener('visibilitychange', () => { if (document.hidden) stopStatuses(); else void refreshStatuses(); });
window.addEventListener('pagehide', () => { state.active = false; stopStatuses(); state.request?.abort(); state.detailRequest?.abort(); });
window.addEventListener('pageshow', event => { state.active = true; if (event.persisted) { closeDetail(); void loadPage(new URL(location.href), 'none'); } });
if (bootstrapped) void refreshStatuses();
else void loadPage(new URL(location.href), 'none');
}

@ -47,14 +47,6 @@ function uploadApi(path, file, onProgress) {
}
function formList(value) { return String(value || '').split(/[\s,]+/).filter(Boolean); }
function profile(host) { return { ...host, ...(host.profile || host.config || {}) }; }
function orderStatus(value) {
return ({ awaiting_payment: '等待账单支付', expired: '账单已失效', queued: '等待创建', running: '创建中', succeeded: '已开通', failed: '已失败', uncertain: '待核对' })[value] || value || '—';
}
function unixTime(value) {
const seconds = Number(value);
if (!Number.isFinite(seconds) || seconds <= 0) return '—';
return new Date(seconds * 1000).toLocaleString('zh-CN', { hour12: false });
}
async function loadHosts() { state.hosts = collection(await api('/api/v1/admin/hosts'), 'hosts').map(profile); return state.hosts; }
async function loadUserIsoSettings() {
const settings = await api('/api/v1/admin/user-iso/settings');
@ -227,43 +219,12 @@ async function uploadRescue(event) {
try { const result = await api(`/api/v1/admin/rescue-templates/upload?host_id=${encodeURIComponent(hostId)}&name=${encodeURIComponent(byId('rescue-name').value.trim())}`, { method: 'POST', body: file, raw: true }); await importProgress(result); byId('rescue-file').value = ''; await loadCatalog(); notice('救援 ISO 导入已完成。'); }
catch (error) { notice(error.message, true); } finally { state.busy = false; button.disabled = !canManage; byId('catalog-host').disabled = false; }
}
async function records() {
const kind = root.dataset.cloudAdmin; notice('正在加载…');
try {
const payload = await api(`/api/v1/${kind === 'instances' ? 'vms' : 'orders'}`);
const entries = collection(payload, kind === 'instances' ? 'vms' : 'orders');
const tbody = byId('admin-records'); tbody.replaceChildren();
for (const record of entries) {
const row = element('tr');
const labels = kind === 'instances'
? ['实例', '用户', '宿主机', '状态', '公网 IP', '配置']
: ['任务', '用户', '套餐', '金额', '状态', '实例 / 引擎任务', '时间 / 错误'];
const fields = kind === 'instances'
? [record.name || record.id, record.owner_email || record.user_email || record.owner_user_id || record.user_id,
record.host_name || record.host_id, record.state || record.status,
String(record.public_ip_cidr || '').split('/')[0],
`${record.vcpu ?? record.cpu_cores ?? '—'} vCPU · ${record.memory_mib ?? '—'} MiB · ${record.disk_gib ?? '—'} GiB`]
: [record.id, record.user_email || record.user_id, record.plan_name || record.plan_id,
record.amount || record.price, orderStatus(record.status),
`${record.instance_id ? `实例 #${record.instance_id}` : '实例 —'} / ${record.job_id ? `任务 #${record.job_id}` : '任务 —'}${Number(record.attempts) > 0 ? ` · 尝试 ${record.attempts}` : ''}`,
`${unixTime(record.updated_at || record.created_at)}${record.error ? ' · ' + record.error : ''}`];
fields.forEach((field, index) => {
const cell = element('td', '', field ?? '—');
cell.dataset.label = labels[index];
row.append(cell);
});
tbody.append(row);
}
notice(`已加载 ${entries.length} 条记录。`);
} catch (error) { notice(error.message, true); }
}
async function initialize() {
if (!root) return;
try { const session = await api('/api/v1/session'); state.csrf = session.csrf_token || state.csrf; if (!session.admin) throw new Error('需要管理员权限。'); if (!state.csrf) throw new Error('会话令牌缺失,请重新登录。');
if (root.dataset.cloudAdmin === 'hosts') { await Promise.all([loadHosts(), loadUserIsoSettings()]); renderHosts(); fillHost(null); byId('host-new').addEventListener('click', () => fillHost(null)); byId('host-scan').addEventListener('click', scanHost); byId('host-form').addEventListener('submit', saveHost); byId('user-iso-settings-form').addEventListener('submit', saveUserIsoSettings); for (const id of ['host-address', 'host-port']) byId(id).addEventListener('input', resetScan); if (!canManage) { byId('host-form').querySelectorAll('input,textarea,button').forEach(input => { input.disabled = true; }); byId('user-iso-settings-form').querySelectorAll('input,button').forEach(input => { input.disabled = true; }); } notice(canManage ? '请选择宿主机编辑,或添加新的宿主机。' : '当前管理员仅可查看配置。'); }
else if (root.dataset.cloudAdmin === 'templates') { byId('template-import')?.addEventListener('submit', importTemplate); byId('template-upload')?.addEventListener('submit', uploadCloudTemplate); await loadCatalog(); }
else if (root.dataset.cloudAdmin === 'rescue') { await loadHosts(); const select = byId('catalog-host'); select.replaceChildren(); for (const host of state.hosts) { const option = element('option', '', `${host.name} · ${host.region || '地区未设置'}`); option.value = String(host.id); select.append(option); } select.addEventListener('change', loadCatalog); byId('rescue-upload')?.addEventListener('submit', uploadRescue); await loadCatalog(); }
else { byId('admin-records-refresh').addEventListener('click', records); await records(); }
} catch (error) { notice(error.message, true); }
}
void initialize();

@ -184,6 +184,187 @@ html.admin-sidebar-scroll-locked {
min-height: 116px;
}
/* VM inventory uses the existing Venix cards and table; only layout is scoped here. */
[data-admin-instances] .admin-instances-table {
min-width: 1120px;
}
[data-admin-instances] .admin-instances-table td {
max-width: 220px;
overflow-wrap: anywhere;
}
[data-admin-instances] .admin-instance-status {
display: grid;
justify-items: start;
gap: 5px;
}
[data-admin-instances] .admin-instance-ip,
[data-admin-instance-drawer] .admin-instance-ip {
display: inline-flex;
align-items: center;
gap: 6px;
min-width: 0;
}
[data-admin-instances] .admin-instance-ip .btn,
[data-admin-instance-drawer] .admin-instance-ip .btn {
flex: 0 0 auto;
width: auto;
}
[data-admin-instances] .admin-instance-ip .admin-mono,
[data-admin-instance-drawer] .admin-instance-ip .admin-mono {
overflow-wrap: anywhere;
}
html.admin-instance-detail-open {
overflow: hidden;
overscroll-behavior: none;
scroll-behavior: auto !important;
}
html.admin-instance-detail-open body {
position: fixed;
top: var(--admin-instance-scroll-top, 0px);
left: 0;
right: 0;
width: 100%;
overflow: hidden;
}
[data-admin-instance-drawer] {
position: fixed;
inset: 0 0 0 auto;
width: min(640px, 100%);
max-width: 100%;
height: 100vh;
height: 100dvh;
max-height: none;
margin: 0;
padding: 0;
border: 0;
background: var(--bs-body-bg, #fff);
color: var(--bs-body-color, #4a5a6b);
box-shadow: -12px 0 48px rgba(0, 8, 26, .16);
overflow: hidden;
}
[data-admin-instance-drawer][open] {
display: flex;
flex-direction: column;
}
[data-admin-instance-drawer]::backdrop {
background: rgba(0, 8, 26, .46);
}
[data-admin-instance-drawer] .admin-instance-drawer-header,
[data-admin-instance-drawer] .admin-instance-drawer-footer {
display: flex;
align-items: center;
justify-content: space-between;
flex: 0 0 auto;
gap: 16px;
padding: 20px 24px;
border-bottom: 1px solid var(--bs-border-color, #e8eef5);
}
[data-admin-instance-drawer] .admin-instance-drawer-header h2 {
overflow-wrap: anywhere;
}
[data-admin-instance-drawer] .admin-instance-drawer-footer {
border-top: 1px solid var(--bs-border-color, #e8eef5);
border-bottom: 0;
padding-bottom: max(20px, env(safe-area-inset-bottom));
}
[data-admin-instance-drawer] .admin-instance-drawer-footer .btn {
flex: 0 0 auto;
}
[data-admin-instance-drawer] .admin-instance-drawer-body {
min-height: 0;
flex: 1 1 auto;
overflow-y: auto;
overscroll-behavior-y: contain;
padding: 20px 24px;
}
[data-admin-instance-drawer] .admin-instance-tabs {
display: flex;
gap: 6px;
margin-bottom: 24px;
overflow-x: auto;
}
[data-admin-instance-drawer] .admin-instance-tabs .btn {
flex: 0 0 auto;
}
[data-admin-instance-drawer] .admin-instance-tabs [aria-selected="true"] {
color: #08785b;
background: #dff6ec;
}
[data-admin-instance-drawer] .admin-instance-details {
display: grid;
grid-template-columns: 116px minmax(0, 1fr);
gap: 16px 12px;
margin: 0;
font-size: 14px;
}
[data-admin-instance-drawer] .admin-instance-details dt {
color: #7d8a9c;
font-weight: 500;
}
[data-admin-instance-drawer] .admin-instance-details dd {
margin: 0;
overflow-wrap: anywhere;
}
[data-admin-instance-drawer] [hidden] {
display: none !important;
}
@media (max-width: 767.98px) {
[data-admin-instances] .admin-instances-table {
min-width: 0;
}
[data-admin-instances] .admin-instances-table td {
max-width: none;
}
[data-admin-instances] .admin-billing-summary .admin-stat-icon {
display: none;
}
[data-admin-instances] .admin-stat-card .card-body {
min-height: 96px;
}
[data-admin-instance-drawer] .admin-instance-drawer-header,
[data-admin-instance-drawer] .admin-instance-drawer-footer,
[data-admin-instance-drawer] .admin-instance-drawer-body {
padding-left: 16px;
padding-right: 16px;
}
[data-admin-instance-drawer] .admin-instance-drawer-footer {
flex-direction: column;
align-items: stretch;
}
[data-admin-instance-drawer] .admin-instance-details {
grid-template-columns: 94px minmax(0, 1fr);
}
}
.admin-stat-card h3 {
font-size: 30px;
font-weight: 800;

@ -1,41 +1,62 @@
{assign var=admin_title value='虚拟机实例'}
{assign var=admin_title value='虚拟机管理'}
{assign var=admin_active value='cloud-instances'}
{include file='admin/static_header.tpl'}
{if !$instance_page}
{assign var=instance_page value=['items'=>[], 'hosts'=>[], 'filters'=>['q'=>'', 'user_id'=>'', 'host_id'=>'', 'service_status'=>'', 'expiry'=>'all', 'attention'=>'all', 'sort'=>'newest'], 'pagination'=>['page'=>1, 'per_page'=>20, 'total'=>'—', 'total_pages'=>1], 'summary'=>['total'=>'—', 'expiring'=>'—', 'network_restricted'=>'—', 'attention'=>'—']]}
{/if}
<link rel="stylesheet" href="/cloud/admin.css?v={$venix_asset_version}">
<section class="cloud-admin" data-cloud-admin="instances">
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column cloud-admin-page-head">
<div class="flex-grow-1">
<p class="admin-eyebrow mb-1">Compute</p>
<h4 class="fs-20 fw-semibold mb-1">虚拟机实例</h4>
<p class="text-muted mb-0">跨宿主机查看已关联的实例、所属用户与资源配置。</p>
</div>
<div class="text-sm-end mt-3 mt-sm-0 cloud-admin-actions">
<p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status" aria-live="polite">正在加载…</p>
<button id="admin-records-refresh" class="btn btn-light" type="button">
<i class="mdi mdi-refresh me-1"></i>刷新
</button>
</div>
<main data-admin-instances>
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column gap-3">
<div class="flex-grow-1"><h1 class="fs-20 fw-semibold mb-1">虚拟机管理</h1><p class="text-muted mb-0">集中查看实例、服务期限和运行异常;电源状态异步更新,不影响列表加载。</p></div>
<div class="admin-checkout-actions text-sm-end"><span class="admin-config-status {if $instance_error}is-error{else}is-success{/if}" id="instances-notice" role="status" aria-live="polite">{if $instance_error}{$instance_error|escape}{else}已读取 {$instance_page.pagination.total|escape} 台实例{/if}</span><button class="btn btn-light" id="instances-refresh" type="button"><i class="mdi mdi-refresh me-1" aria-hidden="true"></i>刷新</button></div>
</div>
<div class="card cloud-admin-table-card">
<div class="card-body">
<div class="cloud-admin-card-head">
<div>
<p class="admin-eyebrow mb-1">Instances</p>
<h5 class="mb-1">实例目录</h5>
<p class="text-muted mb-0">客户资源与操作权限仍由后台校验,此页面仅用于集中查看。</p>
</div>
<span class="cloud-admin-card-icon"><i class="mdi mdi-server-network"></i></span>
</div>
<div class="table-responsive cloud-admin-table-wrap">
<table class="table table-hover align-middle mb-0 cloud-admin-table">
<thead><tr><th>实例</th><th>用户</th><th>宿主机</th><th>状态</th><th>公网 IP</th><th>配置</th></tr></thead>
<tbody id="admin-records"><tr class="cloud-admin-placeholder"><td colspan="6">实例数据加载中</td></tr></tbody>
</table>
</div>
</div>
<section class="row g-3 mb-3 admin-billing-summary" aria-label="当前筛选实例摘要">
<div class="col-6 col-xl-3"><article class="card admin-stat-card"><div class="card-body d-flex align-items-center justify-content-between gap-2"><div><h2 class="text-muted fs-14 fw-normal mb-1">在管实例</h2><strong class="admin-stat-value" id="instances-total">{$instance_page.summary.total|escape}</strong></div><span class="admin-stat-icon text-primary"><i class="mdi mdi-server-network" aria-hidden="true"></i></span></div></article></div>
<div class="col-6 col-xl-3"><article class="card admin-stat-card"><div class="card-body d-flex align-items-center justify-content-between gap-2"><div><h2 class="text-muted fs-14 fw-normal mb-1">7 天内到期</h2><strong class="admin-stat-value" id="instances-expiring">{$instance_page.summary.expiring|escape}</strong></div><span class="admin-stat-icon text-warning"><i class="mdi mdi-calendar-clock" aria-hidden="true"></i></span></div></article></div>
<div class="col-6 col-xl-3"><article class="card admin-stat-card"><div class="card-body d-flex align-items-center justify-content-between gap-2"><div><h2 class="text-muted fs-14 fw-normal mb-1">网络受限</h2><strong class="admin-stat-value" id="instances-network-restricted">{$instance_page.summary.network_restricted|escape}</strong></div><span class="admin-stat-icon text-danger"><i class="mdi mdi-lan-disconnect" aria-hidden="true"></i></span></div></article></div>
<div class="col-6 col-xl-3"><article class="card admin-stat-card"><div class="card-body d-flex align-items-center justify-content-between gap-2"><div><h2 class="text-muted fs-14 fw-normal mb-1">异常任务实例</h2><strong class="admin-stat-value" id="instances-attention">{$instance_page.summary.attention|escape}</strong></div><span class="admin-stat-icon text-warning"><i class="mdi mdi-alert-circle-outline" aria-hidden="true"></i></span></div></article></div>
</section>
<section class="card mb-3 admin-billing-filter" aria-labelledby="instances-filter-title">
<div class="card-header"><h2 class="h5 card-title mb-1" id="instances-filter-title">查找实例</h2><span class="text-muted fs-13">摘要和列表均按当前条件统计。异常任务包含待核对及近 24 小时失败任务。</span></div>
<div class="card-body"><form id="instances-filter" class="row g-2 align-items-end" method="get" action="/admin/cloud/instances">
<label class="col-xl-4 col-lg-6" for="instances-query"><span class="form-label d-block">关键词</span><input class="form-control" id="instances-query" name="q" type="search" maxlength="80" value="{$instance_page.filters.q|escape}" placeholder="名称 / IP / UUID / 用户"></label>
<label class="col-xl-2 col-lg-3 col-6" for="instances-user"><span class="form-label d-block">用户 ID</span><input class="form-control" id="instances-user" name="user_id" type="text" inputmode="numeric" pattern="[1-9][0-9]*" maxlength="20" value="{$instance_page.filters.user_id|escape}" placeholder="全部用户"></label>
<label class="col-xl-3 col-lg-3 col-6" for="instances-host"><span class="form-label d-block">宿主机</span><select class="form-select" id="instances-host" name="host_id"><option value="">全部宿主机</option>{foreach $instance_page.hosts as $host}<option value="{$host.id|escape}" {if $instance_page.filters.host_id == $host.id}selected{/if}>{$host.name|escape}{if $host.region} · {$host.region|escape}{/if}</option>{/foreach}</select></label>
<label class="col-xl-3 col-lg-4 col-6" for="instances-service"><span class="form-label d-block">服务状态</span><select class="form-select" id="instances-service" name="service_status"><option value="">全部服务状态</option><option value="active" {if $instance_page.filters.service_status == 'active'}selected{/if}>服务正常</option><option value="expired_grace" {if $instance_page.filters.service_status == 'expired_grace'}selected{/if}>到期宽限期</option><option value="expired" {if $instance_page.filters.service_status == 'expired'}selected{/if}>已到期</option><option value="exempt" {if $instance_page.filters.service_status == 'exempt'}selected{/if}>免计费</option><option value="suspended_expired" {if $instance_page.filters.service_status == 'suspended_expired'}selected{/if}>到期停用</option><option value="suspending_expired" {if $instance_page.filters.service_status == 'suspending_expired'}selected{/if}>到期停用中</option><option value="suspend_failed" {if $instance_page.filters.service_status == 'suspend_failed'}selected{/if}>暂停失败</option><option value="resume_pending" {if $instance_page.filters.service_status == 'resume_pending'}selected{/if}>等待恢复</option><option value="resuming" {if $instance_page.filters.service_status == 'resuming'}selected{/if}>恢复中</option><option value="resume_failed" {if $instance_page.filters.service_status == 'resume_failed'}selected{/if}>恢复失败</option><option value="purge_stopping" {if $instance_page.filters.service_status == 'purge_stopping'}selected{/if}>清理前关机中</option><option value="purge_stop_failed" {if $instance_page.filters.service_status == 'purge_stop_failed'}selected{/if}>清理前关机失败</option><option value="purge_deleting" {if $instance_page.filters.service_status == 'purge_deleting'}selected{/if}>到期清理中</option><option value="purge_failed" {if $instance_page.filters.service_status == 'purge_failed'}selected{/if}>清理失败</option></select></label>
<label class="col-xl-2 col-lg-4 col-6" for="instances-expiry"><span class="form-label d-block">到期范围</span><select class="form-select" id="instances-expiry" name="expiry"><option value="all">全部期限</option><option value="soon" {if $instance_page.filters.expiry == 'soon'}selected{/if}>7 天内到期</option><option value="expired" {if $instance_page.filters.expiry == 'expired'}selected{/if}>已到期</option><option value="exempt" {if $instance_page.filters.expiry == 'exempt'}selected{/if}>免计费</option></select></label>
<label class="col-xl-2 col-lg-4 col-6" for="instances-focus"><span class="form-label d-block">关注事项</span><select class="form-select" id="instances-focus" name="attention"><option value="all">全部实例</option><option value="network" {if $instance_page.filters.attention == 'network'}selected{/if}>网络受限</option><option value="jobs" {if $instance_page.filters.attention == 'jobs'}selected{/if}>异常任务</option></select></label>
<label class="col-xl-2 col-lg-4 col-6" for="instances-sort"><span class="form-label d-block">排序</span><select class="form-select" id="instances-sort" name="sort"><option value="newest">最近创建</option><option value="oldest" {if $instance_page.filters.sort == 'oldest'}selected{/if}>最早创建</option><option value="expiry" {if $instance_page.filters.sort == 'expiry'}selected{/if}>即将到期优先</option></select></label>
<label class="col-xl-2 col-lg-4 col-6" for="instances-per-page"><span class="form-label d-block">每页条数</span><select class="form-select" id="instances-per-page" name="per_page"><option value="20">20 条</option><option value="50" {if $instance_page.pagination.per_page == 50}selected{/if}>50 条</option><option value="100" {if $instance_page.pagination.per_page == 100}selected{/if}>100 条</option></select></label>
<div class="col-xl-4 col-lg-4 col-12 admin-form-actions admin-billing-filter-actions mt-0"><button class="btn btn-primary" type="submit">应用筛选</button><a class="btn btn-light" id="instances-reset" href="/admin/cloud/instances">清空条件</a></div>
</form></div>
</section>
<section class="card" aria-labelledby="instances-list-title">
<div class="card-header d-flex align-items-center justify-content-between gap-2 flex-wrap"><div><h2 class="h5 card-title mb-1" id="instances-list-title">实例列表</h2><span class="text-muted fs-13" id="instances-live-status" role="status">电源状态尚未获取</span></div><span class="badge text-bg-light" id="instances-count">共 {$instance_page.pagination.total|escape} 台</span></div>
<div class="card-body"><div class="table-responsive admin-checkout-table-wrap"><table class="table table-hover align-middle mb-0 admin-checkout-table admin-instances-table"><caption class="visually-hidden">管理员虚拟机列表</caption><thead><tr><th scope="col">实例</th><th scope="col">用户</th><th scope="col">所在位置</th><th scope="col">公网 IP</th><th scope="col">配置</th><th scope="col">状态</th><th scope="col">用量与期限</th><th scope="col">操作</th></tr></thead><tbody id="instances-body">
{foreach $instance_page.items as $vm}
<tr data-instance-id="{$vm.id|escape}">
<td data-label="实例"><span class="admin-checkout-user"><strong>{$vm.name|escape}</strong><span>#{$vm.id|escape} · {$vm.os_name|default:'系统未记录'|escape}</span></span></td>
<td data-label="用户"><span class="admin-checkout-user">{if $vm.user_url}<a href="{$vm.user_url|escape}">{$vm.user_name|escape}</a>{else}<strong>{$vm.user_name|escape}</strong>{/if}<span>ID {$vm.user_id|escape}</span></span></td>
<td data-label="所在位置"><span class="admin-checkout-user"><strong>{$vm.host_name|escape}</strong><span>{$vm.region|default:'地区未记录'|escape}</span></span></td>
<td data-label="公网 IP"><span class="admin-instance-ip"><span class="admin-mono">{$vm.public_ip|default:'未记录'|escape}</span>{if $vm.public_ip}<button class="btn btn-light btn-sm" type="button" data-copy="{$vm.public_ip|escape}" aria-label="复制公网 IP {$vm.public_ip|escape}"><i class="mdi mdi-content-copy" aria-hidden="true"></i></button>{/if}</span></td>
<td data-label="配置"><span class="admin-checkout-user"><strong>{$vm.display.configuration|escape}</strong><span>{$vm.plan_name|default:'无关联套餐'|escape}</span></span></td>
<td data-label="状态"><div class="admin-instance-status"><span class="badge bg-light text-dark" data-power-status>电源:待获取</span><span class="fs-12">服务:{$vm.display.service|escape}</span><span class="fs-12">网络:{$vm.display.network|escape}</span>{if $vm.active_job}<span class="text-warning fs-12">任务 #{$vm.active_job.id|escape} · {if $vm.active_job.status == 'uncertain'}待核对{elseif $vm.active_job.status == 'running'}执行中{elseif $vm.active_job.status == 'queued'}已排队{else}{$vm.active_job.status|escape}{/if}</span>{/if}</div></td>
<td data-label="用量与期限"><span class="admin-checkout-user"><strong>{$vm.display.traffic|escape}</strong><span>{$vm.display.expiry|escape}</span>{if $vm.service_expires_at && $vm.service_status != 'exempt'}<span>到期 {$vm.service_expires_at|date_format:'%Y-%m-%d'|escape}</span>{/if}</span></td>
<td data-label="操作"><button class="btn btn-primary btn-sm" type="button" data-instance-detail="{$vm.id|escape}" aria-label="查看 {$vm.name|escape} 的详情">查看详情</button></td>
</tr>
{foreachelse}<tr><td colspan="8" class="text-center text-muted py-4">{if $instance_error}实例暂时无法读取,请点击刷新重试。{else}没有符合条件的实例。{/if}</td></tr>{/foreach}
</tbody></table></div><nav class="admin-user-pagination" aria-label="实例列表分页"><button class="btn btn-light" id="instances-previous" type="button" {if $instance_page.pagination.page <= 1}disabled{/if}>上一页</button><span id="instances-page-label">第 {$instance_page.pagination.page|escape} / {$instance_page.pagination.total_pages|escape} 页 · 共 {$instance_page.pagination.total|escape} 台</span><button class="btn btn-light" id="instances-next" type="button" {if $instance_page.pagination.page >= $instance_page.pagination.total_pages}disabled{/if}>下一页</button></nav></div>
</section>
<noscript><p class="alert alert-info">已显示数据库中的实例信息。启用 JavaScript 后可分页、查看详情与实时电源状态。</p></noscript>
</main>
<dialog data-admin-instance-drawer id="instance-detail" aria-labelledby="instance-detail-title">
<header class="admin-instance-drawer-header"><div><p class="text-muted fs-13 mb-1">实例详情</p><h2 class="h4 fw-semibold mb-0" id="instance-detail-title">虚拟机</h2></div><button class="admin-modal-close position-static flex-shrink-0" id="instance-detail-close" type="button" aria-label="关闭实例详情" autofocus><i class="mdi mdi-close" aria-hidden="true"></i></button></header>
<div class="admin-instance-drawer-body"><p class="alert alert-info" id="instance-detail-notice" role="status" aria-live="polite">正在读取详情…</p>
<div class="admin-instance-tabs" role="tablist" aria-label="实例详情分类"><button class="btn btn-light" type="button" id="instance-tab-basic" data-instance-tab="basic" role="tab" aria-controls="instance-panel-basic" aria-selected="true">基本信息</button><button class="btn btn-light" type="button" id="instance-tab-service" data-instance-tab="service" role="tab" aria-controls="instance-panel-service" aria-selected="false" tabindex="-1">服务与流量</button><button class="btn btn-light" type="button" id="instance-tab-jobs" data-instance-tab="jobs" role="tab" aria-controls="instance-panel-jobs" aria-selected="false" tabindex="-1">任务记录</button><button class="btn btn-light" type="button" id="instance-tab-invoices" data-instance-tab="invoices" role="tab" aria-controls="instance-panel-invoices" aria-selected="false" tabindex="-1">关联账单</button></div>
<section id="instance-panel-basic" role="tabpanel" aria-labelledby="instance-tab-basic" tabindex="0"></section><section id="instance-panel-service" role="tabpanel" aria-labelledby="instance-tab-service" tabindex="0" hidden></section><section id="instance-panel-jobs" role="tabpanel" aria-labelledby="instance-tab-jobs" tabindex="0" hidden></section><section id="instance-panel-invoices" role="tabpanel" aria-labelledby="instance-tab-invoices" tabindex="0" hidden></section>
</div>
</section>
<script type="module" src="/cloud/admin.js?v={$venix_asset_version}"></script>
<footer class="admin-instance-drawer-footer"><span class="text-muted fs-12" id="instance-detail-permission">当前详情为只读信息。</span><a class="btn btn-primary" id="instance-control-link" hidden>进入实例控制台</a></footer>
</dialog>
<script id="admin-instances-bootstrap" type="application/json">{$instance_bootstrap_json nofilter}</script>
<script type="module" src="/cloud/admin-instances.js?v={$venix_asset_version}"></script>
{include file='admin/static_footer.tpl'}

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026093004' scope='global'}
{assign var=venix_asset_version value='2026093005' scope='global'}

@ -0,0 +1,141 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
if ((error_reporting() & $severity) && ($severity & (E_WARNING | E_USER_WARNING))) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
return false;
});
// Non-production data also used by the local browser fixture (--fixture).
$now = time();
$common = [
'uuid' => '11111111-1111-4111-8111-111111111111',
'user_id' => 42, 'user_name' => '演示客户', 'user_email' => 'd***@example.test',
'user_url' => '/admin/user/42/edit', 'host_id' => 7,
'host_name' => '香港宿主机 A', 'region' => 'HongKong', 'plan_name' => '标准云服务器',
'os_name' => 'Debian 12', 'vcpu' => 2, 'memory_mib' => 2048, 'disk_gib' => 40,
'instance_status' => 'active', 'service_status' => 'active', 'network_status' => 'active',
'service_expires_at' => $now + 4 * 86400, 'traffic_used_bytes' => 21474836480,
'traffic_quota_bytes' => 107374182400, 'traffic_synced_at' => $now - 60,
'created_at' => $now - 86400, 'active_job' => null, 'state' => 'unknown',
'can_manage' => true,
'display' => [
'configuration' => '2 vCPU · 2 GiB · 40 GiB', 'traffic' => '20 GiB / 100 GiB',
'expiry' => '4 天后到期', 'service' => '服务正常',
'network' => '网络正常', 'lifecycle' => '在管',
],
];
$items = [
array_replace($common, ['id' => '101', 'name' => 'vm-production',
'public_ip' => '192.0.2.101', 'detail_url' => '/user/cloud/instances/101']),
array_replace($common, ['id' => '102', 'name' => 'vm-network-limited',
'public_ip' => '192.0.2.102', 'detail_url' => '/user/cloud/instances/102',
'network_status' => 'blocked_traffic', 'traffic_used_bytes' => 107374182400,
'display' => array_replace($common['display'], [
'traffic' => '100 GiB / 100 GiB', 'network' => '流量耗尽已断网',
])]),
array_replace($common, ['id' => '103', 'name' => 'vm-task-reconciliation',
'public_ip' => '192.0.2.103', 'detail_url' => '/user/cloud/instances/103',
'active_job' => ['id' => '61', 'kind' => 'reinstall', 'status' => 'uncertain',
'attempts' => 3, 'error' => '等待核对操作结果', 'phase' => 'reconcile',
'created_at' => $now - 300, 'updated_at' => $now - 10]]),
];
$page = [
'items' => $items,
'pagination' => ['page' => 1, 'per_page' => 20, 'total' => 43,
'total_pages' => 3, 'from' => 1, 'to' => 3],
'summary' => ['total' => 43, 'expiring' => 3, 'network_restricted' => 1, 'attention' => 1],
'filters' => ['q' => '', 'user_id' => null, 'host_id' => null, 'service_status' => '',
'expiry' => 'all', 'attention' => 'all', 'sort' => 'newest', 'page' => 1, 'per_page' => 20],
'hosts' => [['id' => 7, 'name' => '香港宿主机 A', 'region' => 'HongKong']],
'generated_at' => $now,
];
$detail = [
'instance' => array_replace($items[0], [
'public_ip_cidr' => '192.0.2.101/24', 'gateway' => '192.0.2.1',
'dns_servers' => ['1.1.1.1', '8.8.8.8'], 'engine_name' => 'vc-1111111111114111',
'bandwidth_mbps' => 100, 'os_source' => 'cloud', 'login_name' => 'root',
'current_period_started_at' => $now - 26 * 86400,
'current_period_ends_at' => $now + 4 * 86400, 'renewal_price' => '10.00',
'renewal_days' => 30, 'renewal_traffic_bytes' => 107374182400,
'traffic_download_bytes' => 10737418240, 'traffic_upload_bytes' => 10737418240,
'updated_at' => $now - 60,
]),
'jobs' => [['id' => '62', 'kind' => 'action', 'status' => 'succeeded',
'attempts' => 1, 'error' => null, 'phase' => 'complete',
'created_at' => $now - 3600, 'updated_at' => $now - 3500]],
'jobs_truncated' => false,
'invoices' => [['id' => '201', 'purpose' => 'provision', 'status' => 'paid',
'amount' => '10.00', 'created_at' => $now - 86400,
'detail_url' => '/admin/billing?detail=201']],
'invoices_truncated' => false,
];
$smarty = new Smarty();
$compileDir = sys_get_temp_dir() . '/admin-instance-view-' . bin2hex(random_bytes(6));
mkdir($compileDir);
$smarty->setCompileDir($compileDir);
$smarty->setTemplateDir(dirname(__DIR__) . '/resources/views/venix');
$smarty->assign('config', ['appName' => 'Venix Test']);
$smarty->assign('cdn', '');
$smarty->assign('user', (object) ['isLogin' => false]);
$smarty->assign('admin_can_manage', true);
$smarty->assign('admin_csrf_token', 'fixture-not-a-real-token');
$render = static function (?array $payload, string $error = '') use ($smarty): string {
$smarty->assign('instance_page', $payload);
$smarty->assign('instance_error', $error);
$smarty->assign('instance_bootstrap_json', json_encode($payload,
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
| JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE));
return $smarty->fetch('admin/cloud/instances.tpl');
};
$assert = static function (bool $ok, string $message): void {
if (!$ok) throw new RuntimeException($message);
};
$html = $render($page);
if (in_array('--fixture', $argv ?? [], true)) {
echo json_encode(['html' => $html, 'billing_html' => $smarty->fetch('admin/billing.tpl'),
'page' => $page, 'detail' => $detail],
JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
exit;
}
// The table is usable without waiting for JavaScript or any host connection.
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('<?xml encoding="UTF-8">' . $html);
$xpath = new DOMXPath($dom);
$assert($xpath->query('//tbody//tr')->length === 3, 'SSR did not render all fixture rows.');
$assert(str_contains($dom->textContent, '192.0.2.101')
&& str_contains($dom->textContent, '20 GiB / 100 GiB')
&& str_contains($dom->textContent, '香港宿主机 A'), 'Useful instance data is missing before scripts run.');
$assert($xpath->query('//select[@name="per_page"]/option[@value="20"]')->length === 1
&& $xpath->query('//select[@name="per_page"]/option[@selected and @value!="20"]')->length === 0,
'SSR did not retain the current page size.');
$unsafe = $page;
$unsafe['items'][0]['name'] = '</script><img src=x onerror=alert(1)>';
$unsafe['items'][0]['user_name'] = '<script>window.bad=1</script>';
$unsafe['items'][0]['host_name'] = '" onmouseover="alert(2)';
$unsafeHtml = $render($unsafe);
$dom->loadHTML('<?xml encoding="UTF-8">' . $unsafeHtml);
$xpath = new DOMXPath($dom);
$assert($xpath->query('//*[@onerror or @onmouseover]')->length === 0,
'Untrusted row content escaped into an executable attribute.');
$assert(!str_contains($unsafeHtml, '<script>window.bad=1</script>')
&& str_contains($dom->textContent, '</script><img src=x onerror=alert(1)>'),
'Untrusted names must render as text, not active markup.');
$empty = $page;
$empty['items'] = [];
$empty['pagination'] = ['page' => 1, 'per_page' => 20, 'total' => 0, 'total_pages' => 1, 'from' => 0, 'to' => 0];
$empty['summary'] = ['total' => 0, 'expiring' => 0, 'network_restricted' => 0, 'attention' => 0];
$emptyHtml = $render($empty);
$assert(!str_contains($emptyHtml, 'vm-production'), 'Empty result retained an old instance.');
$failedHtml = $render(null, '实例信息暂不可用,请重试');
$assert(str_contains($failedHtml, '实例信息暂不可用,请重试')
&& !str_contains($failedHtml, 'vm-production'), 'Unavailable data was disguised as a successful list.');
echo "Administrator instance SSR, escaping and empty/error rendering passed.\n";

@ -0,0 +1,502 @@
<?php
namespace App\Services {
final class AdminPermission
{
public static bool $superAdmin = true;
public static function isSuperAdmin(): bool
{
return self::$superAdmin;
}
}
final class Auth
{
public static $user = null;
public static function getUser()
{
return self::$user;
}
}
final class Config
{
public static function get($name, $default = null)
{
return $default;
}
}
}
namespace App\Services\Cloud {
final class CloudSessionService
{
public static int $calls = 0;
public static function current($user): string
{
self::$calls++;
throw new \RuntimeException('Database-only instance reads created an engine session.');
}
}
final class CloudEngineClient
{
public static int $calls = 0;
public function __construct()
{
self::$calls++;
throw new \RuntimeException('Database-only instance reads contacted the engine.');
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Controllers\CloudAdminInstanceController;
use App\Models\User;
use App\Services\AdminPermission;
use App\Services\Auth;
use App\Services\Cloud\CloudAdminInstanceService;
use App\Services\Cloud\CloudEngineClient;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudSessionService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
use Slim\Http\Environment;
use Slim\Http\Request;
use Slim\Http\Response;
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$expectError = static function (callable $callback, int $status, string $message) use ($assert): void {
try {
$callback();
} catch (CloudError $error) {
$assert($error->httpStatus === $status, $message . ': unexpected HTTP status ' . $error->httpStatus);
return;
}
throw new RuntimeException($message . ': request was accepted.');
};
$ids = static fn (array $items): array => array_map('intval', array_column($items, 'id'));
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('user', static function (Blueprint $table): void {
$table->increments('id');
$table->string('user_name');
$table->string('email');
$table->boolean('is_admin')->default(false);
$table->boolean('enable')->default(true);
$table->string('pass')->default('must-not-expose-account-password');
});
$schema->create('cloud_hosts', static function (Blueprint $table): void {
$table->increments('id');
$table->string('name');
$table->string('region')->default('');
$table->string('country_code')->default('');
$table->boolean('enabled')->default(true);
});
$schema->create('shop', static function (Blueprint $table): void {
$table->increments('id');
$table->string('name');
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->string('uuid');
$table->integer('host_id');
$table->integer('user_id');
$table->integer('order_id')->nullable();
$table->integer('plan_id')->nullable();
$table->integer('current_period_id')->nullable();
$table->string('name');
$table->string('status')->default('active');
$table->string('service_status')->default('active');
$table->string('network_status')->default('active');
$table->integer('expires_at')->nullable();
$table->string('renewal_price')->nullable();
$table->integer('renewal_days')->default(0);
$table->integer('renewal_traffic_bytes')->default(0);
$table->integer('traffic_quota_bytes')->default(0);
$table->integer('traffic_download_bytes')->default(0);
$table->integer('traffic_upload_bytes')->default(0);
$table->integer('lifetime_download_bytes')->default(0);
$table->integer('lifetime_upload_bytes')->default(0);
$table->integer('traffic_synced_at')->default(0);
$table->integer('suspended_at')->nullable();
$table->integer('network_suspended_at')->nullable();
$table->text('spec_json');
$table->text('credential_cipher')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_service_periods', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('instance_id');
$table->integer('user_id');
$table->integer('starts_at');
$table->integer('ends_at');
$table->string('status');
});
$schema->create('cloud_orders', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('instance_id')->nullable();
$table->integer('user_id');
$table->integer('plan_id')->nullable();
$table->integer('host_id')->default(7);
$table->string('amount')->default('10.00');
$table->string('status')->default('succeeded');
$table->text('spec_json')->default('{}');
$table->text('payload_cipher')->default('must-not-expose-order-payload');
$table->integer('created_at')->default(0);
$table->integer('updated_at')->default(0);
});
$schema->create('cloud_jobs', static function (Blueprint $table): void {
$table->increments('id');
$table->string('operation_id');
$table->integer('instance_id')->nullable();
$table->integer('order_id')->nullable();
$table->integer('user_id');
$table->integer('host_id')->default(7);
$table->string('kind');
$table->string('status');
$table->integer('attempts')->default(0);
$table->string('error_code')->nullable();
$table->text('payload_cipher')->default('must-not-expose-job-payload');
$table->text('result_json')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_invoices', static function (Blueprint $table): void {
$table->increments('id');
$table->string('invoice_no');
$table->string('purpose')->default('renewal');
$table->integer('instance_id')->nullable();
$table->integer('order_id')->nullable();
$table->integer('user_id');
$table->integer('plan_id')->nullable();
$table->integer('renewal_id')->nullable();
$table->integer('due_at');
$table->string('amount')->default('10.00');
$table->string('status')->default('open');
$table->string('paid_via')->nullable();
$table->string('payment_reference')->default('must-not-expose-payment-reference');
$table->integer('paid_at')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
Capsule::table('user')->insert([
['id' => 1, 'user_name' => 'Alice Ops', 'email' => 'alice@example.test'],
['id' => 2, 'user_name' => 'Bob Client', 'email' => 'bob@example.test'],
['id' => 99, 'user_name' => 'Root Operator', 'email' => 'root@example.test'],
]);
Capsule::table('cloud_hosts')->insert([
['id' => 7, 'name' => 'Hong Kong 07', 'region' => 'HongKong', 'country_code' => 'HK'],
['id' => 8, 'name' => 'Tokyo 08', 'region' => 'Tokyo', 'country_code' => 'JP'],
]);
Capsule::table('shop')->insert(['id' => 3, 'name' => 'Small Cloud']);
$now = time();
$base = [
'host_id' => 7, 'user_id' => 1, 'plan_id' => 3,
'status' => 'active', 'service_status' => 'active', 'network_status' => 'active',
'expires_at' => $now + 30 * 86400, 'renewal_price' => '10.00',
'renewal_days' => 30, 'renewal_traffic_bytes' => 2000,
'traffic_quota_bytes' => 2000, 'traffic_download_bytes' => 300,
'traffic_upload_bytes' => 200, 'traffic_synced_at' => $now - 30,
'credential_cipher' => 'must-not-expose-instance-credential',
'spec_json' => json_encode([
'vcpu' => 2, 'memory_mib' => 2048, 'disk_gib' => 40,
'os_source' => 'cloud_template', 'os_name' => 'AlmaLinux 10',
'public_ip_cidr' => '198.51.100.10/24',
'state' => 'running', 'console_port' => 5900,
'password' => 'must-not-expose-spec-password',
'api_token' => 'must-not-expose-api-token',
'unreviewed_note' => 'must-not-expose-unknown-spec-field',
'disks' => [['capacity_gib' => 40, 'source' => 'must-not-expose-disk-path']],
]),
'created_at' => $now - 600, 'updated_at' => $now - 300,
];
$insertInstance = static function (int $id, array $overrides = []) use ($base): void {
Capsule::table('cloud_instances')->insert(array_replace($base, [
'id' => $id, 'uuid' => sprintf('11111111-1111-4111-8111-%012d', $id),
'name' => 'vm-' . $id,
], $overrides));
};
for ($id = 1; $id <= 205; $id++) {
$insertInstance($id);
}
$insertInstance(206, ['user_id' => 2, 'host_id' => 8, 'order_id' => 601,
'current_period_id' => 1, 'expires_at' => $now + 2 * 86400]);
$insertInstance(207, ['expires_at' => $now - 3600, 'service_status' => 'expired', 'order_id' => 602]);
$insertInstance(208, ['expires_at' => null, 'service_status' => 'exempt']);
$insertInstance(209, ['network_status' => 'blocked_traffic']);
$insertInstance(210, ['network_status' => 'restore_failed']);
$insertInstance(211, ['status' => 'deleted', 'expires_at' => $now + 3600]);
$insertInstance(212, ['user_id' => 404, 'host_id' => 404, 'plan_id' => 404, 'expires_at' => null]);
$insertInstance(213, ['name' => "tenant's 100%_ready"]);
$insertInstance(214, ['spec_json' => json_encode([
'public_ip_cidr' => '203.0.113.74/24', 'vcpu' => 4, 'memory_mib' => 4096,
])]);
Capsule::table('cloud_service_periods')->insert([
'id' => 1, 'instance_id' => 206, 'user_id' => 2,
'starts_at' => $now - 28 * 86400, 'ends_at' => $now + 2 * 86400, 'status' => 'active',
]);
Capsule::table('cloud_orders')->insert([
['id' => 601, 'instance_id' => 206, 'user_id' => 2],
['id' => 602, 'instance_id' => 207, 'user_id' => 2],
]);
$insertJob = static function (int $id, array $overrides = []) use ($now): void {
Capsule::table('cloud_jobs')->insert(array_replace([
'id' => $id, 'operation_id' => sprintf('%032d', $id),
'instance_id' => 206, 'user_id' => 99, 'kind' => 'action',
'status' => 'succeeded', 'created_at' => $now - 100, 'updated_at' => $now,
'result_json' => json_encode([
'phase' => 'finished', 'generated_password' => 'must-not-expose-job-password',
'unreviewed_note' => 'must-not-expose-unknown-job-result',
]),
], $overrides));
};
for ($id = 1; $id <= 26; $id++) {
$insertJob($id, ['status' => $id === 26 ? 'running' : 'succeeded']);
}
$insertJob(27, ['instance_id' => 209, 'status' => 'failed', 'error_code' => 'test_failure']);
$insertJob(28, ['instance_id' => 210, 'status' => 'uncertain', 'updated_at' => $now - 172800]);
$insertJob(29, ['instance_id' => 207, 'status' => 'failed', 'updated_at' => $now - 172800]);
$insertJob(30, ['instance_id' => 211, 'status' => 'failed']);
$insertInvoice = static function (int $id, array $overrides = []) use ($now): void {
Capsule::table('cloud_invoices')->insert(array_replace([
'id' => $id, 'invoice_no' => 'TEST-' . $id,
'instance_id' => 206, 'user_id' => 2,
'due_at' => $now + 3600, 'created_at' => $now - 100, 'updated_at' => $now,
], $overrides));
};
for ($id = 1; $id <= 25; $id++) {
$insertInvoice($id);
}
$insertInvoice(26, ['user_id' => 1]);
$insertInvoice(27, ['instance_id' => null, 'order_id' => 601]);
$insertInvoice(28, ['instance_id' => null, 'order_id' => 602, 'user_id' => 1]);
$admin = ['user_id' => 99, 'is_admin' => true, 'is_super_admin' => true, 'can_manage' => true];
$readOnly = ['user_id' => 99, 'is_admin' => true, 'is_super_admin' => false, 'can_manage' => false];
$customer = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false, 'can_manage' => false];
// All timestamps are deliberately identical: ordering must include the ID.
$page = CloudAdminInstanceService::page($admin);
$assert($page['pagination']['total'] === 213 && count($page['items']) === 20
&& $ids($page['items']) === array_values(array_diff(range(214, 194), [211])),
'Administrator first page lost records above 200, included deleted rows, or sorted ties unstably.');
$assert($page['summary']['total'] === 213 && $page['summary']['expiring'] === 1
&& $page['summary']['network_restricted'] === 2 && $page['summary']['attention'] === 2,
'Database statistics must cover the complete filtered population and preserve state meanings.');
$assert(!isset($page['summary']['running']) && !isset($page['summary']['stopped']),
'Database-only summary fabricated a live power-state count.');
$seen = [];
for ($number = 1; $number <= 3; $number++) {
$chunk = CloudAdminInstanceService::page($admin, ['page' => (string) $number, 'per_page' => '100']);
$seen = array_merge($seen, $ids($chunk['items']));
}
$assert(count($seen) === 213 && count(array_unique($seen)) === 213
&& $seen === array_values(array_diff(range(214, 1), [211])),
'Paging beyond 200 duplicated or silently truncated instances.');
$last = CloudAdminInstanceService::page($admin, ['page' => '9999', 'per_page' => '100']);
$assert($last['pagination']['page'] === 3 && count($last['items']) === 13,
'Out-of-range pages did not clamp to the last valid page.');
$oldest = CloudAdminInstanceService::page($admin, ['sort' => 'oldest']);
$assert($ids($oldest['items']) === range(1, 20), 'Oldest sorting needs a stable ascending ID order.');
$expiry = CloudAdminInstanceService::page($admin, ['sort' => 'expiry']);
$assert((int) $expiry['items'][0]['id'] === 207, 'Expiry sorting did not put the oldest expiry first.');
foreach ([['user_id' => '2'], ['host_id' => '8'], ['user_id' => '2', 'host_id' => '8']] as $filter) {
$filtered = CloudAdminInstanceService::page($admin, $filter);
$assert($ids($filtered['items']) === [206] && $filtered['summary']['total'] === 1
&& $filtered['summary']['expiring'] === 1,
'Exact owner/host filters or filtered summary crossed instance boundaries.');
}
$empty = CloudAdminInstanceService::page($admin, ['user_id' => '2', 'host_id' => '7']);
$assert($empty['items'] === [] && $empty['pagination']['total'] === 0
&& $empty['pagination']['total_pages'] === 1 && $empty['pagination']['page'] === 1
&& $empty['summary']['total'] === 0,
'Empty filtered collections returned stale rows or invalid pagination.');
foreach ([
"tenant's" => [213], '100%_ready' => [213], '%' => [213], '_ready' => [213],
'203.0.113.74' => [214], "' OR 1=1 --" => [],
'11111111-1111-4111-8111-000000000214' => [214],
'bob@example.test' => [206],
] as $query => $expected) {
$searched = CloudAdminInstanceService::page($admin, ['q' => $query]);
$assert($ids($searched['items']) === $expected,
'Search must bind quotes, escape SQL wildcards, and correctly match IP/UUID/account: ' . $query);
}
foreach (['soon' => [206], 'expired' => [207], 'exempt' => [208]] as $mode => $expected) {
$filtered = CloudAdminInstanceService::page($admin, ['expiry' => $mode]);
$assert($ids($filtered['items']) === $expected,
'Expiry filter confused paid periods, expired instances, or exempt instances: ' . $mode);
}
$exempt = CloudAdminInstanceService::page($admin, ['service_status' => 'exempt']);
$assert($ids($exempt['items']) === [208], 'Exact service-status filter was ignored.');
foreach (['network', 'jobs'] as $mode) {
$attention = CloudAdminInstanceService::page($admin, ['attention' => $mode]);
$assert($ids($attention['items']) === [210, 209],
'Attention filter included deleted/old failed jobs or omitted unresolved jobs/network restrictions.');
foreach ($attention['items'] as $item) {
$assert($item['state'] === 'unknown', 'Business/network/job state was mistaken for live VM power state.');
}
}
foreach (['page', 'per_page', 'q', 'user_id', 'host_id', 'service_status', 'expiry', 'attention', 'sort'] as $key) {
$expectError(static fn () => CloudAdminInstanceService::page($admin, [$key => ['1']]), 400,
'Array-valued filter must be rejected: ' . $key);
}
foreach ([['page' => '0'], ['page' => '-1'], ['page' => '1.5'], ['user_id' => '0'],
['host_id' => '1 OR 1=1'], ['expiry' => 'running'], ['attention' => 'powered'],
['sort' => 'id; DROP TABLE user'], ['service_status' => 'invented'], ['q' => str_repeat('x', 81)]] as $filter) {
$expectError(static fn () => CloudAdminInstanceService::page($admin, $filter), 400,
'Malformed filters must return a controlled client error');
}
$expectError(static fn () => CloudAdminInstanceService::page($customer), 403,
'Ordinary customers must not access the administrator read model');
$expectError(static fn () => CloudAdminInstanceService::detail($customer, '206'), 403,
'Ordinary customers must not inspect another owner through admin detail');
foreach (['211', '999999'] as $id) {
$expectError(static fn () => CloudAdminInstanceService::detail($admin, $id), 404,
'Missing or deleted detail must not disclose an instance');
}
$orphan = CloudAdminInstanceService::detail($admin, '212');
$assert((int) $orphan['instance']['id'] === 212 && $orphan['instance']['state'] === 'unknown',
'Missing user, host or plan caused an instance to disappear.');
$assert($orphan['instance']['display']['service'] === '期限未记录',
'An active record with an unknown billing deadline must not be labelled service-available.');
$detail = CloudAdminInstanceService::detail($admin, '206');
$assert((int) $detail['instance']['active_job']['id'] === 26
&& $detail['instance']['active_job']['status'] === 'running'
&& $detail['instance']['can_manage'] === true,
'An operation submitted by a super-admin was lost because the job actor differs from the instance owner.');
$assert(count($detail['jobs']) === 20 && $detail['jobs_truncated'] === true
&& $ids($detail['jobs']) === range(26, 7),
'Instance tasks must be newest-first, bounded to 20, and explicitly marked truncated.');
$expectedInvoiceIds = array_merge([27], range(25, 7));
$assert(count($detail['invoices']) === 20 && $detail['invoices_truncated'] === true
&& $ids($detail['invoices']) === $expectedInvoiceIds,
'Invoice detail included a foreign owner, missed the valid order link, or silently truncated history.');
$crossOwner = CloudAdminInstanceService::detail($admin, '207');
$assert($crossOwner['invoices'] === [],
'A same-owner invoice joined through another owner\'s order crossed the billing boundary.');
foreach ($detail['invoices'] as $invoice) {
$assert(str_starts_with($invoice['detail_url'], '/admin/billing?detail='),
'Invoice links must target the administrator ledger, not the customer route.');
}
$encoded = json_encode([$page, $detail, $crossOwner, $orphan], JSON_THROW_ON_ERROR);
$assert(!str_contains($encoded, 'must-not-expose')
&& !str_contains($encoded, 'credential_cipher')
&& !str_contains($encoded, 'payload_cipher')
&& !str_contains($encoded, 'result_json')
&& !str_contains($encoded, 'console_port')
&& !str_contains($encoded, 'unreviewed_note'),
'The administrator DTO allowlist leaked credentials, paths, or an unreviewed metadata/result field.');
AdminPermission::$superAdmin = false;
$masked = CloudAdminInstanceService::page($readOnly, ['user_id' => '2']);
$assert($masked['items'][0]['can_manage'] === false
&& $masked['items'][0]['user_email'] !== 'bob@example.test'
&& $masked['items'][0]['user_name'] !== 'Bob Client',
'Read-only administrators gained global operation controls or unmasked account data.');
$hiddenSearch = CloudAdminInstanceService::page($readOnly, ['q' => 'bob@example.test']);
$assert($hiddenSearch['items'] === [], 'Read-only account search became an oracle for masked email addresses.');
AdminPermission::$superAdmin = true;
$queryCounts = [];
foreach ([20, 100] as $size) {
$connection = Capsule::connection('default');
$connection->flushQueryLog();
$connection->enableQueryLog();
CloudAdminInstanceService::page($admin, ['per_page' => (string) $size]);
$queries = $connection->getQueryLog();
$connection->disableQueryLog();
$queryCounts[] = count($queries);
foreach ($queries as $query) {
$assert(preg_match('/^\s*(select|with)\b/i', $query['query']) === 1,
'Instance reads unexpectedly wrote business or session data.');
$assert(!str_contains(strtolower($query['query']), 'cloud_sessions'),
'Database-only instance reads touched the private engine session table.');
}
}
$assert($queryCounts[0] <= 8 && $queryCounts[1] <= $queryCounts[0],
'Increasing page size introduced per-instance SQL queries: ' . implode(', ', $queryCounts));
$login = static function (bool $isAdmin, bool $isSuper = false, bool $enabled = true): void {
$user = new User();
$user->id = $isAdmin ? 99 : 1;
$user->enable = $enabled ? 1 : 0;
$user->is_admin = $isAdmin;
$user->isLogin = true;
Auth::$user = $user;
AdminPermission::$superAdmin = $isSuper;
};
$app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);
require dirname(__DIR__) . '/config/routes_cloud.php';
$requestApi = static function (string $path, array $query = []) use ($app): array {
$request = Request::createFromEnvironment(Environment::mock([
'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => $path,
]))->withQueryParams($query);
$response = $app->process($request, new Response());
return [$response, json_decode((string) $response->getBody(), true)];
};
$login(true, true);
[$response, $payload] = $requestApi('/api/v1/admin/instances', ['user_id' => '2']);
$assert($response->getStatusCode() === 200 && $ids($payload['items']) === [206]
&& $response->getHeaderLine('Cache-Control') === 'private, no-store',
'The registered administrator list route did not provide a private scoped database response.');
[$response, $payload] = $requestApi('/api/v1/admin/instances/206');
$assert($response->getStatusCode() === 200 && (int) $payload['instance']['id'] === 206,
'The registered administrator detail route did not dispatch the database read model.');
foreach ([['q' => ['bad']], ['page' => '0'], ['host_id' => ['8']]] as $query) {
[$response, $payload] = $requestApi('/api/v1/admin/instances', $query);
$assert($response->getStatusCode() === 400 && isset($payload['error']),
'Malformed query parameters escaped CloudApi as a server error.');
}
foreach (['211', '999999'] as $id) {
[$response] = $requestApi('/api/v1/admin/instances/' . $id);
$assert($response->getStatusCode() === 404, 'Registered detail disclosed a missing/deleted instance.');
}
$login(true);
[$response, $payload] = $requestApi('/api/v1/admin/instances/206');
$assert($response->getStatusCode() === 200 && $payload['instance']['can_manage'] === false,
'Read-only administrators must retain global read access without mutation capability.');
$login(false);
foreach (['/api/v1/admin/instances', '/api/v1/admin/instances/206'] as $path) {
[$response] = $requestApi($path);
$assert($response->getStatusCode() === 403, 'A customer reached a registered administrator route.');
}
$login(true, true, false);
[$response] = $requestApi('/api/v1/admin/instances');
$assert($response->getStatusCode() === 401, 'Disabled accounts bypassed CloudAccess authentication.');
Auth::$user = null;
[$response] = $requestApi('/api/v1/admin/instances');
$assert($response->getStatusCode() === 401, 'Anonymous requests bypassed CloudAccess authentication.');
// The controller also works without middleware attributes and must request
// actor(false), preserving the no-engine-session guarantee in this path.
$login(true, true);
$direct = (new CloudAdminInstanceController())->index(
Request::createFromEnvironment(Environment::mock([
'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/api/v1/admin/instances',
])), new Response()
);
$assert($direct->getStatusCode() === 200, 'Controller fallback authentication broke database-only reads.');
$assert(CloudEngineClient::$calls === 0 && CloudSessionService::$calls === 0,
'The service, middleware, or controller read path contacted the private engine/session service.');
echo 'Administrator instance SQL filtering, pagination, ownership, DTO safety and bounded queries passed ('
. implode('/', $queryCounts) . " queries for 20/100 rows).\n";
echo "Administrator instance registered API routes, authorization, validation and session isolation passed.\n";
}

@ -601,9 +601,6 @@ $assert(str_contains($cloudSchema, 'CREATE TABLE IF NOT EXISTS cloud_template_re
'CloudTemplateDeletionService::fetchAuthoritativeCatalog')
&& str_contains($deploymentPageService, 'forgetTemplate('),
'Template retirement must block active provisioning/reinstall references and stale SSR catalogs.');
$assert(str_contains($adminScript, 'function unixTime(value)')
&& str_contains($adminScript, 'orderStatus(record.status)'),
'Order diagnostics must format timestamps and localize task status');
$assert(str_contains($clientScript,
"makeElement('div', 'cloud-order-actions cloud-invoice-list-actions')")
&& str_contains($clientStyles, '.cloud-orders { min-height: 0;'),
@ -746,7 +743,7 @@ $assert(!str_contains($clientScript, '/renewals')
'Retired direct-renewal controls must not remain in the user UI');
$assert(str_contains($cloudAdminController, "'known_owners' => (object) CloudInstanceDiscovery::knownOwners"),
'Empty VM ownership maps must be encoded as a JSON object for engine discovery');
foreach (['hosts/index.tpl', 'cloud/instances.tpl', 'cloud/rescue.tpl', 'cloud/templates.tpl'] as $template) {
foreach (['hosts/index.tpl', 'cloud/rescue.tpl', 'cloud/templates.tpl'] as $template) {
$source = file_get_contents($views . '/admin/' . $template);
$assert(str_contains($source, '/cloud/admin.js?v={$venix_asset_version}'),
'Cloud admin script cache busting missing: ' . $template);

Loading…
Cancel
Save