feat: add tenant vpc user console

venix
admin 1 month ago
parent ab1a04d297
commit b1e8a46a65

@ -189,8 +189,10 @@ Debian 13 ifupdown、nft 语法、重启、防火墙重载、跨宿主机握手
tombstone 和宿主机回读闭环之前不会释放;这会保留地址以避免未知状态下复用,
不能把 allocator 的 `active` 误认为已经可以回收。后续删除流程必须先阻断新成员
变更、确认所有成员/路由/ACL 已收敛,再以独立 revision 和 CAS 释放 reservation。
删除中的宿主机或子资源 tombstone 仍会关闭 `usable`;当前没有删除回读证据,
因此不能在只剩其余宿主机 active 时提前放行。空 VPC 也不会进入 active,必须先有
删除中的宿主机、私网 NIC、地址、子网或成员 tombstone 仍会关闭 `usable`;这些
对象没有专门的删除回读证据时,不能在只剩其余宿主机 active 时提前放行。Route/ACL
tombstone 属于已纳入每台宿主机精确路由、nft 和 revision/digest 回读的对象,只有所有
仍存活的宿主机逐一匹配后才会收敛为 `deleted`。空 VPC 也不会进入 active,必须先有
至少一个成员宿主机通过 Fabric 门禁。
VM 删除与 VPC 成员是两个独立状态机:仍有成员(包括 `deleting` tombstone)时,

@ -11,6 +11,8 @@ use App\Services\Cloud\CloudInstancePageService;
use App\Services\Cloud\CloudInvoiceDetailPageService;
use App\Services\Cloud\CloudInvoicePageService;
use App\Services\Cloud\CloudUserIsoFeature;
use App\Services\Cloud\CloudVpcPageService;
use App\Services\Cloud\CloudVpcService;
use App\Services\UserDrawerService;
use App\Services\View;
@ -48,6 +50,37 @@ final class CloudPageController
]);
}
/**
* Tenant VPC page. The initial document is database-only; the browser
* uses the typed /api/v1/vpcs endpoints for mutations and readback polls.
*/
public function vpcs($request, $response, $args)
{
$actor = CloudAccess::actor(false);
$user = $request->getAttribute('auth_user') ?? Auth::getUser();
$pageData = CloudVpcPageService::bootstrap($actor);
try {
$vpcs = CloudVpcService::listing($actor);
} catch (\Throwable) {
// Keep the shell renderable during a rolling schema migration;
// the API error is shown by the page's explicit retry path.
$vpcs = [];
}
$payload = [
'user' => $this->userBootstrap($user, $actor),
'vpcs' => $vpcs,
'regions' => $pageData['regions'],
'instances' => $pageData['instances'],
'scope_label' => ($actor['is_admin'] ?? false)
? '管理员权限范围内的 VPC' : '仅显示当前账户资源',
];
return $this->render($response, 'vpcs', 'VPC 私网', '', '', [
'cloud_vpc_bootstrap_json' => $this->safeJson($payload),
'cloud_vpc_scope_label' => $payload['scope_label'],
]);
}
public function detail($request, $response, $args)
{
$vmId = isset($args['id']) ? (string) $args['id'] : '';
@ -315,6 +348,7 @@ final class CloudPageController
$smarty->assign('cloud_reinstall_ssh_keys', []);
$smarty->assign('cloud_reinstall_catalog_unavailable', false);
$smarty->assign('cloud_reinstall_bootstrap_json', '{}');
$smarty->assign('cloud_vpc_bootstrap_json', '{}');
$smarty->assign('panel_announcements_bootstrap_json', UserDrawerService::announcementBootstrapJson());
foreach ($values as $name => $value) {
$smarty->assign($name, $value);

@ -0,0 +1,93 @@
<?php
namespace App\Services\Cloud;
use App\Models\CloudInstance;
use App\Models\CloudRegionFabric;
/**
* Database-only bootstrap data for the tenant VPC page.
*
* The page must never enumerate a host or ask the engine for placement data.
* Regions are limited to platform mappings that can actually accept a VPC;
* instance choices contain only owner-scoped display fields needed by the
* attach form. The API remains authoritative for every write and validation.
*/
final class CloudVpcPageService
{
public static function bootstrap(array $actor): array
{
return [
'regions' => self::regions(),
'instances' => self::instances($actor),
];
}
private static function regions(): array
{
try {
$connection = (new CloudRegionFabric())->getConnection();
$schema = $connection->getSchemaBuilder();
if (!$schema->hasTable('cloud_region_fabrics')) {
return [];
}
return CloudRegionFabric::query()
->join('cloud_regions as region', 'region.id', '=', 'cloud_region_fabrics.region_id')
->where('cloud_region_fabrics.state', 'active')
->where('cloud_region_fabrics.fabric_revision', '>', 0)
->where('region.status', 'active')
->orderByDesc('region.sort')->orderBy('region.id')
->get([
'region.id as id', 'region.name', 'region.country_code',
])
->map(static fn ($row): array => [
'id' => (int) $row->id,
'name' => trim((string) $row->name),
'country_code' => strtoupper(trim((string) ($row->country_code ?? ''))),
])->all();
} catch (\Throwable) {
// A rolling schema install should leave the page usable while
// making the unavailable Fabric choice explicit to the tenant.
return [];
}
}
private static function instances(array $actor): array
{
$userId = (int) ($actor['user_id'] ?? 0);
if ($userId < 1) {
return [];
}
try {
return CloudInstance::query()
->where('user_id', $userId)
->where('status', 'active')
->orderBy('name')->orderBy('id')->limit(200)->get([
'id', 'name', 'spec_json', 'service_status', 'expires_at',
])->map(static function ($row): array {
$spec = json_decode((string) $row->spec_json, true);
$spec = is_array($spec) && !array_is_list($spec) ? $spec : [];
$regionId = filter_var($spec['region_id'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$region = trim((string) ($spec['region'] ?? $spec['location'] ?? ''));
// A future expiry does not make a blocked/suspended
// service eligible for a private-network attachment.
// Keep this projection identical to CloudInstance's
// serviceAvailable() lifecycle gate.
$available = (string) $row->service_status === 'exempt'
|| ((string) $row->service_status === 'active'
&& $row->expires_at !== null
&& (int) $row->expires_at > time());
return [
'id' => (int) $row->id,
'name' => (string) $row->name,
'region_id' => $regionId === false ? null : (int) $regionId,
'region' => $region,
'service_available' => $available,
];
})->all();
} catch (\Throwable) {
return [];
}
}
}

@ -621,8 +621,23 @@ final class CloudVpcService
}
$rows = CloudVpcRoute::where('vpc_id', $vpc->id)->lockForUpdate()->get();
$existingByDestination = [];
$deletedByDestination = [];
$existingByKey = [];
foreach ($rows as $row) {
$existingByDestination[(string) $row->destination_cidr] = $row;
$existingByKey[(string) $row->route_key] = $row;
if ((string) $row->state === 'deleted') {
// A proven tombstone still owns the destination/key
// unique indexes. It may be revived by a later complete
// replacement, but must never be reopened merely because
// another save includes unrelated routes.
$deletedByDestination[(string) $row->destination_cidr] = $row;
} else {
$existingByDestination[(string) $row->destination_cidr] = $row;
}
}
if ($rows->contains(static fn ($row): bool =>
(string) $row->state === 'deleting')) {
throw new CloudError('路由仍在清理,请等待宿主机回读后再保存', 409);
}
$seenDestinations = [];
foreach ($routes as $route) {
@ -631,18 +646,30 @@ final class CloudVpcService
throw new CloudError('路由目标不能重复', 409);
}
$seenDestinations[$destination] = true;
$existing = $existingByDestination[$destination] ?? null;
if ($existing !== null && (string) $existing->route_key !== $route['route_key']) {
$existing = $existingByDestination[$destination]
?? $deletedByDestination[$destination] ?? null;
if ($existing !== null
&& (string) $existing->state !== 'deleted'
&& (string) $existing->route_key !== $route['route_key']) {
throw new CloudError('路由目标已存在,请沿用原 route_key 修改', 409);
}
$sameKey = $existingByKey[$route['route_key']] ?? null;
if ($sameKey !== null && $existing !== null
&& (int) $sameKey->id !== (int) $existing->id) {
throw new CloudError('route_key 已被其他路由使用', 409);
}
}
foreach ($rows as $row) {
if ((string) $row->state === 'deleted') {
continue;
}
$row->state = 'deleting';
$row->updated_at = time();
$row->save();
}
$now = time();
foreach ($routes as $route) {
$destination = (string) $route['destination']['cidr'];
$next = $byIp[$route['next_hop_ip']] ?? null;
if ($next === null) {
throw new CloudError('路由下一跳必须是本 VPC 的成员私网 IP');
@ -654,12 +681,20 @@ final class CloudVpcService
}
$row = CloudVpcRoute::where('vpc_id', $vpc->id)
->where('route_key', $route['route_key'])->lockForUpdate()->first();
if ($row === null) {
// Reuse a proven tombstone when the user recreates the
// same destination with a fresh browser-generated key.
// This satisfies both unique indexes without exposing
// historical keys in the tenant editor.
$row = $deletedByDestination[$destination] ?? null;
}
if ($row === null) {
$row = new CloudVpcRoute();
$row->route_key = $route['route_key'];
$row->vpc_id = $vpc->id;
$row->created_at = $now;
}
$row->route_key = $route['route_key'];
$row->member_id = $next->id;
$row->destination_cidr = $route['destination']['cidr'];
$row->destination_int = $route['destination']['network'];
@ -694,8 +729,20 @@ final class CloudVpcService
$root = self::cidr((string) $vpc->cidr, 16, 24, 'VPC CIDR');
$rows = CloudVpcAclRule::where('vpc_id', $vpc->id)->lockForUpdate()->get();
$existingByPriority = [];
$deletedByPriority = [];
$existingByKey = [];
foreach ($rows as $row) {
$existingByPriority[(string) $row->direction . ':' . (int) $row->priority] = $row;
$priorityKey = (string) $row->direction . ':' . (int) $row->priority;
$existingByKey[(string) $row->rule_key] = $row;
if ((string) $row->state === 'deleted') {
$deletedByPriority[$priorityKey] = $row;
} else {
$existingByPriority[$priorityKey] = $row;
}
}
if ($rows->contains(static fn ($row): bool =>
(string) $row->state === 'deleting')) {
throw new CloudError('ACL 仍在清理,请等待宿主机回读后再保存', 409);
}
$seenPriorities = [];
foreach ($rules as $rule) {
@ -704,18 +751,30 @@ final class CloudVpcService
throw new CloudError('同一方向的 ACL 优先级不能重复', 409);
}
$seenPriorities[$priorityKey] = true;
$existing = $existingByPriority[$priorityKey] ?? null;
if ($existing !== null && (string) $existing->rule_key !== $rule['rule_key']) {
$existing = $existingByPriority[$priorityKey]
?? $deletedByPriority[$priorityKey] ?? null;
if ($existing !== null
&& (string) $existing->state !== 'deleted'
&& (string) $existing->rule_key !== $rule['rule_key']) {
throw new CloudError('ACL 优先级已存在,请沿用原 rule_key 修改', 409);
}
$sameKey = $existingByKey[$rule['rule_key']] ?? null;
if ($sameKey !== null && $existing !== null
&& (int) $sameKey->id !== (int) $existing->id) {
throw new CloudError('rule_key 已被其他 ACL 使用', 409);
}
}
foreach ($rows as $row) {
if ((string) $row->state === 'deleted') {
continue;
}
$row->state = 'deleting';
$row->updated_at = time();
$row->save();
}
$now = time();
foreach ($rules as $rule) {
$priorityKey = (string) $rule['direction'] . ':' . (int) $rule['priority'];
foreach (['source', 'destination'] as $side) {
if (!self::contains($root['network'], $root['broadcast'],
$rule[$side]['network'], $rule[$side]['broadcast'])) {
@ -724,12 +783,18 @@ final class CloudVpcService
}
$row = CloudVpcAclRule::where('vpc_id', $vpc->id)
->where('rule_key', $rule['rule_key'])->lockForUpdate()->first();
if ($row === null) {
// As with routes, a terminal tombstone can be reused for
// the same direction/priority without exposing its key.
$row = $deletedByPriority[$priorityKey] ?? null;
}
if ($row === null) {
$row = new CloudVpcAclRule();
$row->rule_key = $rule['rule_key'];
$row->vpc_id = $vpc->id;
$row->created_at = $now;
}
$row->rule_key = $rule['rule_key'];
$row->priority = $rule['priority'];
$row->direction = $rule['direction'];
$row->action = $rule['action'];
@ -1060,6 +1125,8 @@ final class CloudVpcService
&& $privateDataplaneVerified
&& $observedRevision === $revision
&& hash_equals($digest, $observedDigest);
$pendingHostTombstone = $required->contains(static fn ($row): bool =>
(string) $row->state === 'deleting');
$fabricGate = is_array($observed['fabric_gate'] ?? null)
? $observed['fabric_gate'] : [];
// An empty VPC is a valid tenant reservation, but there is no
@ -1098,9 +1165,9 @@ final class CloudVpcService
$liveRequired = $required->filter(static fn ($row): bool =>
(string) $row->state !== 'deleting');
// A Fabric or host control-plane digest cannot prove that a
// deleting child/host is gone from the data plane. Keep every
// tombstone closed until the typed private-NIC/route/nft evidence
// is introduced by the engine.
// deleting private interface/address/subnet is gone. Route and
// ACL tombstones may be closed later, but only after the exact
// per-host route/nft readback gate.
$pendingChildTombstone = false;
foreach ([
CloudVpcSubnet::class,
@ -1115,21 +1182,26 @@ final class CloudVpcService
break;
}
}
$pendingHostTombstone = $required->contains(static fn ($row): bool =>
(string) $row->state === 'deleting');
$allActive = $globalActive && $liveRequired->count() > 0
&& !$pendingChildTombstone && !$pendingHostTombstone;
// Keep this independent from child tombstones: route/ACL rows can
// close after exact host readback, while private NIC/address rows
// still require their explicit removal proof.
$allLiveHostsExact = $globalActive && $liveRequired->count() > 0
&& !$pendingHostTombstone;
$allRemovalProof = true;
$hasRemovalTarget = false;
foreach ($hosts as $hostKey => $_item) {
if (!$required->has((int) $hostKey)) {
$allActive = false;
$allLiveHostsExact = false;
}
}
foreach ($required as $hostId => $deployment) {
$item = $hosts[(string) $hostId] ?? null;
if (!is_array($item)) {
$allActive = false;
$allLiveHostsExact = false;
// A deleting host remains a tombstone until an exact
// desired revision proves that the empty-host target was
// accepted. Converting it to uncertain would make a
@ -1148,6 +1220,7 @@ final class CloudVpcService
$active = $globalActive && ($item['state'] ?? null) === 'active'
&& ($item['transport_verified'] ?? false) === true
&& ($item['private_dataplane_verified'] ?? false) === true
&& ($item['removed'] ?? false) !== true
&& $itemRevision <= $revision
&& $itemRevision === $revision && hash_equals($digest, $itemDigest);
$deleting = (string) $deployment->state === 'deleting';
@ -1185,9 +1258,82 @@ final class CloudVpcService
} else {
$deployment->last_failure_at = time();
$allActive = false;
if (!$deleting) {
$allLiveHostsExact = false;
}
}
$deployment->save();
}
// A terminal no-members/no-participating-hosts response is a
// positive control-plane proof only when this revision has no
// host deployment left to remove. In that case no host-side
// route or nft object can still be owned by this VPC, so route
// and ACL tombstones may converge without pretending that a
// private NIC, address, member, or subnet was removed. Keep the
// proof in the operation audit; the operation itself remains a
// terminal gate failure until a future member mutation creates a
// real host dataplane target.
$noDataPlaneTerminalProof = $terminalGate
&& $required->count() === 0
&& $liveRequired->count() === 0
&& $hosts === []
&& !$pendingHostTombstone;
if ($noDataPlaneTerminalProof) {
$observed['no_data_plane_terminal_proof'] = [
'revision' => $revision,
'digest' => $digest,
'gate' => $gateError,
];
$observedAt = time();
foreach ([CloudVpcRoute::class, CloudVpcAclRule::class] as $childModel) {
$childModel::where('vpc_id', $vpc->id)
->where('desired_revision', $revision)
->where('state', 'deleting')
->update([
'observed_revision' => $revision,
'observed_digest' => $digest,
'state' => 'deleted',
'last_error_code' => null,
'updated_at' => $observedAt,
]);
}
}
// Routes and ACLs are part of the exact host dataplane digest.
// Close their tombstones only after every required live host was
// individually matched above; a top-level active envelope with a
// missing or mismatched host must remain fail-closed.
if ($allLiveHostsExact) {
$observedAt = time();
foreach ([CloudVpcRoute::class, CloudVpcAclRule::class] as $childModel) {
$childModel::where('vpc_id', $vpc->id)
->where('desired_revision', $revision)
->where('state', 'deleting')
->update([
'observed_revision' => $revision,
'observed_digest' => $digest,
'state' => 'deleted',
'last_error_code' => null,
'updated_at' => $observedAt,
]);
}
}
// Re-read after route/ACL closure so their former tombstones do
// not keep an otherwise exact VPC in degraded state.
$pendingChildTombstone = false;
foreach ([
CloudVpcSubnet::class,
CloudVpcPrivateIp::class,
CloudVpcMember::class,
CloudVpcRoute::class,
CloudVpcAclRule::class,
] as $childModel) {
if ($childModel::where('vpc_id', $vpc->id)
->where('state', 'deleting')->exists()) {
$pendingChildTombstone = true;
break;
}
}
$allActive = $allLiveHostsExact && !$pendingChildTombstone;
$removalOnlyComplete = $hasRemovalTarget && $allRemovalProof
&& $liveRequired->count() === 0 && !$pendingChildTombstone;
if ($hasRemovalTarget && $allRemovalProof && $liveRequired->count() === 0) {
@ -3121,6 +3267,20 @@ final class CloudVpcService
private static function boundedObserved(array $value): array
{
$hosts = [];
$terminalProof = null;
$proof = $value['no_data_plane_terminal_proof'] ?? null;
if (is_array($proof)
&& (int) ($proof['revision'] ?? 0) > 0
&& preg_match('/^[a-f0-9]{64}$/D', (string) ($proof['digest'] ?? '')) === 1
&& in_array((string) ($proof['gate'] ?? ''), [
'vpc_no_members', 'vpc_no_participating_hosts',
], true)) {
$terminalProof = [
'revision' => (int) $proof['revision'],
'digest' => strtolower((string) $proof['digest']),
'gate' => (string) $proof['gate'],
];
}
foreach (is_array($value['hosts'] ?? null) ? $value['hosts'] : [] as $key => $host) {
if (!is_array($host) || count($hosts) >= 256) {
continue;
@ -3238,6 +3398,10 @@ final class CloudVpcService
}
$hosts[(string) $key] = $bounded;
}
return ['hosts' => $hosts];
$result = ['hosts' => $hosts];
if ($terminalProof !== null) {
$result['no_data_plane_terminal_proof'] = $terminalProof;
}
return $result;
}
}

@ -92,6 +92,7 @@ $app->group('/user', function () {
$this->get('/', 'App\Controllers\CloudPageController:home');
$this->get('/cloud', 'App\Controllers\CloudPageController:index');
$this->get('/cloud/instances', 'App\Controllers\CloudPageController:instances');
$this->get('/cloud/vpcs', 'App\Controllers\CloudPageController:vpcs');
$this->get('/cloud/instances/{id:[0-9]+}', 'App\Controllers\CloudPageController:detail');
$this->get('/cloud/instances/{id:[0-9]+}/reinstall', 'App\Controllers\CloudPageController:reinstall');
$this->get('/cloud/instances/{id:[0-9]+}/rescue', 'App\Controllers\CloudPageController:rescue');

@ -1,5 +1,6 @@
const pageModules = Object.freeze({
instances: '/cloud/instances.js',
vpcs: '/cloud/vpc.js',
detail: '/cloud/detail.js',
deploy: '/cloud/deploy.js',
isos: '/cloud/iso-images.js',

File diff suppressed because one or more lines are too long

@ -0,0 +1,820 @@
import { toast } from './toast.js?v=2026100802';
const byId = id => document.getElementById(id);
const state = {
csrfToken: '', userId: '', regions: [], instances: [], vpcs: [],
selectedKey: '', selected: null, busy: false, stopped: false, detailDirty: false,
listEpoch: 0, detailEpoch: 0, listController: null, detailController: null,
pollTimer: 0,
};
const STATUS_LABELS = Object.freeze({
applying: '应用中', waiting: '等待宿主机回读', uncertain: '结果待核对',
degraded: '部分失败', active: '已生效', deleting: '清理中', unknown: '状态未知',
});
function element(tag, className = '', textContent = '') {
const node = document.createElement(tag);
if (className) node.className = className;
if (textContent !== '') node.textContent = String(textContent);
return node;
}
function field(label, value, className = '') {
const wrapper = element('div', `vpc-fact ${className}`.trim());
wrapper.append(element('dt', '', label), element('dd', '', value));
return wrapper;
}
function setError(message = '') {
const node = byId('vpc-page-error');
if (!node) return;
node.textContent = message;
node.hidden = !message;
}
function setNotice(message = '', kind = '') {
const node = byId('vpc-page-notice');
if (!node) return;
node.textContent = message;
node.className = `vpc-notice ${kind}`.trim();
node.hidden = !message;
}
function setFormError(id, message = '') {
const node = byId(id);
if (!node) return;
node.textContent = message;
node.hidden = !message;
}
function secureTransportRequired() {
return location.protocol !== 'https:'
&& !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname);
}
async function api(path, options = {}) {
const method = String(options.method || 'GET').toUpperCase();
const headers = new Headers({ Accept: 'application/json', ...(options.headers || {}) });
if (!['GET', 'HEAD'].includes(method)) {
if (secureTransportRequired()) throw new Error('请通过 HTTPS 修改 VPC 私网配置。');
if (!state.csrfToken) throw new Error('会话安全令牌缺失,请刷新页面。');
headers.set('X-CSRF-Token', state.csrfToken);
headers.set('Content-Type', 'application/json');
}
const response = await fetch(path, {
method, headers, credentials: 'same-origin', cache: 'no-store',
signal: options.signal,
body: options.body === undefined ? undefined : JSON.stringify(options.body),
});
let payload = null;
try { payload = response.status === 204 ? null : await response.json(); }
catch { throw new Error('服务返回了非 JSON 数据,请检查 PHP 及反代配置。'); }
if (response.status === 401) {
location.assign('/auth/login');
throw new Error('登录已过期。');
}
if (!response.ok || payload?.ret === 0) {
const detail = Array.isArray(payload?.detail)
? payload.detail.map(item => item?.msg || '输入错误').join(';') : payload?.detail;
throw new Error(String(detail || payload?.message || payload?.error
|| `请求失败 (${response.status})`));
}
return payload;
}
function requestKey(prefix) {
const uuid = typeof crypto?.randomUUID === 'function'
? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(16).slice(2)}`;
return `${prefix}-${uuid}`.slice(0, 128);
}
function entityKey() {
const value = typeof crypto?.randomUUID === 'function'
? crypto.randomUUID().replaceAll('-', '')
: `${Date.now()}${Math.random().toString(16).slice(2)}`;
return value.replace(/[^a-f0-9]/gi, '').toLowerCase().padEnd(32, '0').slice(0, 32);
}
function safeText(value, fallback = '—') {
const text = value === null || value === undefined ? '' : String(value).trim();
return text || fallback;
}
function rootStatus(root) {
const sync = String(root?.sync_state || '').toLowerCase();
const raw = String(root?.state || '').toLowerCase();
if (root?.usable === true) return 'active';
if (sync === 'waiting' || sync === 'waiting_observed') return 'waiting';
if (sync === 'uncertain' || raw === 'uncertain') return 'uncertain';
if (raw === 'degraded' || sync === 'failed') return 'degraded';
if (raw === 'deleting') return 'deleting';
if (raw === 'applying' || ['pending', 'queued', 'running'].includes(sync)) return 'applying';
return raw === 'active' ? 'uncertain' : (raw || 'unknown');
}
function childStatus(value) {
const raw = String(value || '').toLowerCase();
return ['active', 'applying', 'waiting', 'uncertain', 'degraded', 'deleting', 'deleted']
.includes(raw) ? raw : 'unknown';
}
function statusPill(status, extra = '') {
const normalized = status === 'waiting_observed' ? 'waiting' : String(status || 'unknown');
const pill = element('span', `vpc-state-pill ${normalized}`.trim(),
STATUS_LABELS[normalized] || normalized);
if (extra) pill.title = extra;
return pill;
}
function errorLabel(code) {
return {
vpc_no_members: 'VPC 已创建;加入至少一个实例后才会应用私网数据面。',
vpc_data_plane_deferred: 'Fabric 已就绪,正在等待私网数据面回读。',
vpc_observation_incomplete: '宿主机回读尚未完整,请稍后核对。',
}[String(code || '')] || '';
}
function regionName(regionId) {
const row = state.regions.find(item => Number(item.id) === Number(regionId));
return row ? safeText(row.name, `地区 ${regionId}`) : `地区 ${regionId || '未知'}`;
}
function instanceName(instanceId) {
const row = state.instances.find(item => Number(item.id) === Number(instanceId));
return row ? safeText(row.name, `实例 #${instanceId}`) : `实例 #${instanceId}`;
}
function instanceRegion(instanceId) {
const row = state.instances.find(item => Number(item.id) === Number(instanceId));
return row ? safeText(row.region, '地区待核验') : '地区待核验';
}
function normalizeRoot(value) {
if (!value || typeof value !== 'object') return null;
return {
...value,
vpc_key: String(value.vpc_key || ''),
name: String(value.name || '未命名 VPC'),
cidr: String(value.cidr || ''),
region_id: Number(value.region_id || 0),
desired_revision: Number(value.desired_revision || 0),
observed_revision: Number(value.observed_revision || 0),
last_error_code: value.last_error_code ? String(value.last_error_code) : '',
};
}
function normalizeDocument(value) {
if (!value || typeof value !== 'object') return null;
const root = normalizeRoot(value.vpc);
if (!root) return null;
return {
vpc: root,
subnets: Array.isArray(value.subnets) ? value.subnets : [],
members: Array.isArray(value.members) ? value.members : [],
routes: Array.isArray(value.routes) ? value.routes : [],
acl_rules: Array.isArray(value.acl_rules) ? value.acl_rules : [],
operations: Array.isArray(value.operations) ? value.operations : [],
};
}
function needsPolling() {
return state.vpcs.some(vpc => rootStatus(vpc) !== 'active')
|| (state.selected && rootStatus(state.selected.vpc) !== 'active');
}
function markDetailDirty() {
if (state.detailDirty) return;
state.detailDirty = true;
setNotice('详情中有未保存修改,自动状态核对已暂停。', 'warning');
}
function confirmDetailMutation() {
return !state.detailDirty
|| confirm('当前 VPC 有未保存修改,继续操作会丢失这些修改。继续吗?');
}
function clearDetailDirty() {
state.detailDirty = false;
}
function refreshRouteEditorState() {
const editor = byId('vpc-route-editor');
if (!editor) return;
const allowed = new Set((state.selected?.members || [])
.filter(item => !['deleting', 'deleted'].includes(childStatus(item.state)))
.map(item => String(item.private_ip || '')));
for (const row of editor.querySelectorAll('.vpc-editor-row')) {
const value = row.querySelector('[data-route-field="next_hop_ip"]')?.value || '';
if (!value || !allowed.has(String(value))) row.dataset.invalid = 'true';
else delete row.dataset.invalid;
}
const blocked = Boolean(editor.querySelector('[data-vpc-tombstone-state="deleting"]'));
const save = document.querySelector('[data-vpc-save="routes"]');
if (save) save.disabled = state.busy || blocked
|| Boolean(editor.querySelector('[data-invalid="true"]'));
}
function schedulePoll(delay = needsPolling() ? 8000 : 30000) {
clearTimeout(state.pollTimer);
if (state.stopped || document.visibilityState === 'hidden') return;
state.pollTimer = window.setTimeout(async () => {
if (state.stopped || document.visibilityState === 'hidden') return;
if (state.busy) { schedulePoll(1500); return; }
await loadList(true);
if (state.selectedKey && !state.detailDirty) {
await loadDetail(state.selectedKey, true);
}
schedulePoll();
}, delay);
}
function renderSummary() {
const active = state.vpcs.filter(item => rootStatus(item) === 'active').length;
const attention = state.vpcs.length - active;
byId('vpc-stat-total').textContent = String(state.vpcs.length);
byId('vpc-stat-active').textContent = String(active);
byId('vpc-stat-attention').textContent = String(attention);
byId('vpc-list-caption').textContent = state.vpcs.length
? `${state.vpcs.length} 个 VPC · 状态每 ${needsPolling() ? '8' : '30'} 秒自动核对`
: '还没有已创建的 VPC';
}
function renderList() {
const container = byId('vpc-list');
container.replaceChildren();
const rows = state.vpcs.map(root => {
const row = element('button', `vpc-list-row${root.vpc_key === state.selectedKey ? ' selected' : ''}`);
row.type = 'button';
row.dataset.vpcKey = root.vpc_key;
const main = element('span', 'vpc-list-main');
const heading = element('span', 'vpc-list-heading');
heading.append(element('strong', '', root.name), statusPill(rootStatus(root), root.last_error_code));
main.append(heading, element('small', '', `${root.cidr} · ${regionName(root.region_id)}`));
const meta = element('span', 'vpc-list-meta');
meta.append(element('small', '', `目标 revision ${root.desired_revision || 0}`),
element('small', '', root.usable === true ? '宿主机回读已确认' : '等待实际回读'));
row.append(main, meta);
return row;
});
container.append(...rows);
byId('vpc-list-empty').hidden = rows.length !== 0;
byId('vpc-list-reconcile').disabled = !state.selectedKey || state.busy
|| rootStatus(state.vpcs.find(item => item.vpc_key === state.selectedKey)) === 'active';
renderSummary();
}
function section(title, description, className = '') {
const card = element('section', `vpc-subpanel ${className}`.trim());
const header = element('div', 'vpc-subpanel-heading');
header.append(element('div', '', ''), element('span', 'vpc-subpanel-count', ''));
header.firstChild.append(element('h3', '', title), element('p', '', description));
card.append(header);
return card;
}
function button(label, className = 'button button-outline small') {
const node = element('button', className, label);
node.type = 'button';
return node;
}
function input(labelText, value = '', type = 'text', placeholder = '') {
const wrapper = element('div', 'field');
const id = `vpc-field-${Math.random().toString(16).slice(2)}`;
const label = element('label', '', labelText);
const control = document.createElement(type === 'select' ? 'select' : 'input');
control.id = id;
if (type !== 'select') {
control.type = type; control.value = value === null ? '' : String(value);
if (placeholder) control.placeholder = placeholder;
}
label.htmlFor = id;
wrapper.append(label, control);
return { wrapper, control };
}
function renderDetail() {
const container = byId('vpc-detail');
const doc = state.selected;
if (!doc) { container.replaceChildren(); return; }
const root = doc.vpc;
container.replaceChildren();
byId('vpc-detail-title').textContent = root.name;
byId('vpc-detail-caption').textContent = `${root.cidr} · ${regionName(root.region_id)}`;
const overview = element('section', 'vpc-detail-overview');
const overviewHeading = element('div', 'vpc-detail-overview-heading');
const status = rootStatus(root);
const rootHint = errorLabel(root.last_error_code);
overviewHeading.append(statusPill(status, root.last_error_code),
element('span', 'vpc-readback-note', root.usable === true
? 'WireGuard、私网路由和实例网卡均已回读确认。'
: (rootHint || '配置仍在宿主机应用或核对,期间不要重复创建同一成员。')));
const actions = element('div', 'vpc-detail-actions');
const reconcile = button('核对 / 重试', 'button button-primary small');
reconcile.dataset.vpcAction = 'reconcile'; reconcile.disabled = state.busy || status === 'active';
actions.append(reconcile);
overviewHeading.append(actions);
const facts = element('dl', 'vpc-facts');
facts.append(field('VPC CIDR', root.cidr), field('地区', regionName(root.region_id)),
field('目标 revision', root.desired_revision || 0), field('已观测 revision', root.observed_revision || 0),
field('同步状态', safeText(root.sync_state)), field('最近错误', root.last_error_code || '无'));
overview.append(overviewHeading, facts);
container.append(overview);
container.append(renderSubnets(doc));
container.append(renderMembers(doc));
container.append(renderRoutes(doc));
container.append(renderAcl(doc));
container.append(renderOperations(doc));
clearDetailDirty();
}
function renderSubnets(doc) {
const card = section('子网与 CIDR', '子网是 VPC 内的地址范围;当前数据面使用成员精确 /32,不自动提供网关。', 'vpc-subnets');
const form = element('form', 'vpc-inline-form'); form.dataset.vpcForm = 'subnet';
const cidr = input('新增子网 CIDR', '', 'text', '10.40.1.0/24');
cidr.control.name = 'cidr'; cidr.control.required = true; cidr.control.maxLength = 18;
const save = button('添加子网', 'button button-primary small'); save.type = 'submit';
form.append(cidr.wrapper, save); card.append(form);
const list = element('div', 'vpc-row-list');
for (const row of doc.subnets) {
const item = element('div', 'vpc-data-row');
const copy = element('div', 'vpc-row-copy');
copy.append(element('strong', '', row.cidr || '未知子网'), element('small', '', `状态:${STATUS_LABELS[childStatus(row.state)] || safeText(row.state)}`));
if (row.last_error_code) copy.append(element('small', 'vpc-row-error', row.last_error_code));
const remove = button('删除', 'button button-outline small danger');
remove.dataset.vpcRemoveSubnet = row.subnet_key;
remove.disabled = state.busy || ['deleting', 'deleted'].includes(childStatus(row.state));
item.append(copy, remove); list.append(item);
}
if (!doc.subnets.length) list.append(element('p', 'vpc-empty-inline', '暂无子网。'));
card.append(list); return card;
}
function renderMembers(doc) {
const card = section('成员与私网 IP', '把同一地区的实例加入 VPC;私网 IP 由 PHP 租约账本分配并在宿主机回读后生效。', 'vpc-members');
const form = element('form', 'vpc-inline-form vpc-member-form'); form.dataset.vpcForm = 'member';
const subnet = input('加入子网', '', 'select'); subnet.control.name = 'subnet_key'; subnet.control.required = true;
for (const row of doc.subnets.filter(item => !['deleting', 'deleted'].includes(childStatus(item.state)))) {
subnet.control.append(new Option(row.cidr, row.subnet_key));
}
const instance = input('选择实例', '', 'select'); instance.control.name = 'instance_id'; instance.control.required = true;
const vpcRegionId = Number(doc.vpc.region_id || 0);
const attached = new Set(doc.members
.filter(item => childStatus(item.state) !== 'deleted')
.map(item => Number(item.instance_id)));
for (const row of state.instances.filter(item => item.service_available !== false)) {
const sameRegion = !row.region_id || Number(row.region_id) === vpcRegionId;
const alreadyAttached = attached.has(Number(row.id));
const suffix = alreadyAttached ? ' · 已在当前 VPC' : (!sameRegion ? ' · 地区不匹配' : '');
const option = new Option(`${row.name} · ${safeText(row.region, '地区待核验')}${suffix}`, String(row.id));
option.dataset.regionId = row.region_id || '';
option.disabled = alreadyAttached || !sameRegion;
instance.control.append(option);
}
const ip = input('指定私网 IP(可选)', '', 'text', '自动分配'); ip.control.name = 'private_ip'; ip.control.maxLength = 15;
const save = button('加入 VPC', 'button button-primary small'); save.type = 'submit';
form.append(subnet.wrapper, instance.wrapper, ip.wrapper, save); card.append(form);
const list = element('div', 'vpc-row-list');
for (const row of doc.members.filter(item => childStatus(item.state) !== 'deleted')) {
const item = element('div', 'vpc-data-row');
const copy = element('div', 'vpc-row-copy');
copy.append(element('strong', '', `${instanceName(row.instance_id)} · ${safeText(row.private_ip)}`),
element('small', '', `${instanceRegion(row.instance_id)} · 状态:${STATUS_LABELS[childStatus(row.state)] || safeText(row.state)}`));
if (row.last_error_code) copy.append(element('small', 'vpc-row-error', row.last_error_code));
const remove = button('退出 VPC', 'button button-outline small danger');
remove.dataset.vpcRemoveMember = row.member_key;
remove.disabled = state.busy || childStatus(row.state) === 'deleting';
item.append(copy, remove); list.append(item);
}
if (!doc.members.some(item => childStatus(item.state) !== 'deleted')) list.append(element('p', 'vpc-empty-inline', '暂无成员。'));
card.append(list); return card;
}
function routeRow(value = {}) {
const row = element('div', 'vpc-editor-row');
row.dataset.routeKey = value.route_key || entityKey();
const destination = input('目标 /32', value.destination_cidr || '', 'text', '10.40.2.7/32');
destination.control.dataset.routeField = 'destination_cidr';
const nextHop = input('下一跳成员 IP', value.next_hop_ip || '', 'select');
nextHop.control.dataset.routeField = 'next_hop_ip';
const members = (state.selected?.members || [])
.filter(item => !['deleting', 'deleted'].includes(childStatus(item.state)));
let foundNextHop = false;
for (const member of members) {
const memberIp = String(member.private_ip || '');
if (memberIp === String(value.next_hop_ip || '')) foundNextHop = true;
nextHop.control.append(new Option(`${safeText(member.private_ip)} · ${instanceName(member.instance_id)}`, memberIp));
}
nextHop.control.value = String(value.next_hop_ip || '');
if (!foundNextHop) {
row.dataset.invalid = 'true';
if (value.next_hop_ip) {
const missing = new Option(`${value.next_hop_ip} · 成员状态待核验`, value.next_hop_ip);
missing.disabled = true;
nextHop.control.append(missing);
nextHop.control.value = String(value.next_hop_ip);
}
}
const metric = input('Metric', value.metric || 100, 'number'); metric.control.min = '1'; metric.control.max = '65535'; metric.control.dataset.routeField = 'metric';
const remove = button('移除', 'button button-outline small danger'); remove.dataset.editorRemove = 'route';
row.append(destination.wrapper, nextHop.wrapper, metric.wrapper, remove); return row;
}
function renderRoutes(doc) {
const card = section('Route', '路由目标当前限制为 VPC 内的精确 /32,下一跳必须是本 VPC 成员私网 IP。保存会替换整套路由。', 'vpc-routes');
const list = element('div', 'vpc-editor-list'); list.id = 'vpc-route-editor';
const tombstones = doc.routes.filter(row => ['deleting', 'deleted'].includes(childStatus(row.state)));
const editable = doc.routes.filter(row => !['deleting', 'deleted'].includes(childStatus(row.state)));
for (const row of editable) list.append(routeRow(row));
for (const row of tombstones) {
const item = element('div', 'vpc-tombstone-row');
item.dataset.vpcTombstone = 'true';
item.dataset.vpcTombstoneState = childStatus(row.state);
const pending = childStatus(row.state) === 'deleting';
item.append(element('strong', '', row.destination_cidr || '已删除路由'),
element('small', '', pending
? '状态:清理中;完成前不能覆盖整套路由'
: '状态:已清理;这是历史记录,可继续编辑其他路由'));
list.append(item);
}
if (!editable.length && !tombstones.length) list.append(element('p', 'vpc-empty-inline', '暂无自定义路由;同 VPC 成员的 /32 由数据面维护。'));
const toolbar = element('div', 'vpc-editor-toolbar');
const add = button('添加路由', 'button button-outline small'); add.dataset.editorAdd = 'route';
const save = button('保存路由', 'button button-primary small'); save.dataset.vpcSave = 'routes';
const pendingTombstones = tombstones.some(row => childStatus(row.state) === 'deleting');
add.disabled = state.busy || pendingTombstones;
save.disabled = state.busy || pendingTombstones || Boolean(list.querySelector('[data-invalid="true"]'));
toolbar.append(add, save); card.append(list, toolbar); return card;
}
function aclRow(value = {}) {
const row = element('div', 'vpc-editor-row vpc-acl-row');
row.dataset.aclKey = value.rule_key || entityKey();
const priority = input('优先级', value.priority || 100, 'number'); priority.control.min = '1'; priority.control.max = '1000000'; priority.control.dataset.aclField = 'priority';
const direction = input('方向', '', 'select'); direction.control.dataset.aclField = 'direction';
for (const option of [['ingress', '入站'], ['egress', '出站']]) direction.control.append(new Option(option[1], option[0]));
direction.control.value = value.direction || 'ingress';
const action = input('动作', '', 'select'); action.control.dataset.aclField = 'action';
for (const option of [['allow', '允许'], ['deny', '拒绝']]) action.control.append(new Option(option[1], option[0]));
action.control.value = value.action || 'deny';
const protocol = input('协议', '', 'select'); protocol.control.dataset.aclField = 'protocol';
for (const option of [['all', '全部'], ['tcp', 'TCP'], ['udp', 'UDP'], ['icmp', 'ICMP']]) protocol.control.append(new Option(option[1], option[0]));
protocol.control.value = value.protocol || 'all';
const source = input('源 CIDR', value.source_cidr || '', 'text', '10.40.0.0/16'); source.control.dataset.aclField = 'source_cidr';
const destination = input('目标 CIDR', value.destination_cidr || '', 'text', '10.40.0.0/16'); destination.control.dataset.aclField = 'destination_cidr';
const from = input('起始端口', value.port_from ?? '', 'number', 'TCP/UDP 可选'); from.control.min = '1'; from.control.max = '65535'; from.control.dataset.aclField = 'port_from';
const to = input('结束端口', value.port_to ?? '', 'number', 'TCP/UDP 可选'); to.control.min = '1'; to.control.max = '65535'; to.control.dataset.aclField = 'port_to';
const remove = button('移除', 'button button-outline small danger'); remove.dataset.editorRemove = 'acl';
row.append(priority.wrapper, direction.wrapper, action.wrapper, protocol.wrapper, source.wrapper, destination.wrapper, from.wrapper, to.wrapper, remove); return row;
}
function renderAcl(doc) {
const card = section('VPC ACL', '默认策略由数据面保持拒绝;这里只提交结构化规则,不会修改实例公网防火墙。保存会替换整套 ACL。', 'vpc-acl');
const list = element('div', 'vpc-editor-list'); list.id = 'vpc-acl-editor';
const tombstones = doc.acl_rules.filter(row => ['deleting', 'deleted'].includes(childStatus(row.state)));
const editable = doc.acl_rules.filter(row => !['deleting', 'deleted'].includes(childStatus(row.state)));
for (const row of editable) list.append(aclRow(row));
for (const row of tombstones) {
const item = element('div', 'vpc-tombstone-row');
item.dataset.vpcTombstone = 'true';
item.dataset.vpcTombstoneState = childStatus(row.state);
const pending = childStatus(row.state) === 'deleting';
item.append(element('strong', '', `规则 ${safeText(row.rule_key)}`),
element('small', '', pending
? '状态:清理中;完成前不能覆盖整套 ACL'
: '状态:已清理;这是历史记录,可继续编辑其他规则'));
list.append(item);
}
if (!editable.length && !tombstones.length) list.append(element('p', 'vpc-empty-inline', '暂无自定义 ACL 规则。'));
const toolbar = element('div', 'vpc-editor-toolbar');
const add = button('添加规则', 'button button-outline small'); add.dataset.editorAdd = 'acl';
const save = button('保存 ACL', 'button button-primary small'); save.dataset.vpcSave = 'acl';
const pendingTombstones = tombstones.some(row => childStatus(row.state) === 'deleting');
add.disabled = state.busy || pendingTombstones;
save.disabled = state.busy || pendingTombstones;
toolbar.append(add, save); card.append(list, toolbar); return card;
}
function renderOperations(doc) {
const card = section('最近操作', '每次修改都会生成独立的 VPC revision;只有宿主机精确回读后才会进入 active。', 'vpc-operations');
const list = element('div', 'vpc-operation-list');
for (const row of doc.operations.slice(0, 12)) {
const item = element('div', 'vpc-operation-row');
item.append(element('span', '', safeText(row.kind)), statusPill(row.status === 'waiting_observed' ? 'waiting' : row.status),
element('small', '', `revision ${row.desired_revision || 0}${row.error_code ? ` · ${row.error_code}` : ''}`));
list.append(item);
}
if (!doc.operations.length) list.append(element('p', 'vpc-empty-inline', '暂无操作记录。'));
card.append(list); return card;
}
function createRegionOptions() {
const select = byId('vpc-create-region');
select.replaceChildren();
if (!state.regions.length) {
select.append(new Option('暂无可用 Fabric 地区', ''));
select.disabled = true;
byId('vpc-create-region-hint').textContent = '管理员尚未完成可用 Fabric 映射,暂不能创建 VPC。';
return;
}
select.disabled = false;
select.append(new Option('请选择地区', ''));
for (const row of state.regions) select.append(new Option(String(row.name), String(row.id)));
}
async function loadList(silent = false) {
const epoch = ++state.listEpoch;
state.listController?.abort(); state.listController = new AbortController();
try {
const payload = await api('/api/v1/vpcs', { signal: state.listController.signal });
if (epoch !== state.listEpoch || state.stopped) return;
state.vpcs = Array.isArray(payload?.vpcs) ? payload.vpcs.map(normalizeRoot).filter(Boolean) : [];
renderList();
if (!silent) setError('');
} catch (error) {
if (error?.name === 'AbortError') return;
if (!silent || !state.vpcs.length) setError(error.message);
}
}
async function loadDetail(key, silent = false, allowDirty = false) {
if (!key) return;
if (state.detailDirty && !allowDirty) return;
const epoch = ++state.detailEpoch;
state.detailController?.abort(); state.detailController = new AbortController();
try {
const payload = await api(`/api/v1/vpcs/${encodeURIComponent(key)}`, { signal: state.detailController.signal });
if (epoch !== state.detailEpoch || state.stopped || key !== state.selectedKey) return;
state.selected = normalizeDocument(payload);
byId('vpc-detail-panel').hidden = !state.selected;
renderDetail();
if (!silent) setError('');
} catch (error) {
if (error?.name === 'AbortError') return;
if (!silent) setError(error.message);
}
}
async function selectVpc(key) {
if (state.detailDirty
&& !confirm('当前 VPC 有未保存修改,切换后会丢失这些修改。继续吗?')) return;
clearDetailDirty();
state.selectedKey = String(key || '');
state.selected = null;
byId('vpc-detail-panel').hidden = !state.selectedKey;
renderList();
await loadDetail(state.selectedKey);
schedulePoll(5000);
}
async function applyDocument(payload, message = '') {
const doc = normalizeDocument(payload);
if (doc) {
clearDetailDirty();
state.selected = doc;
state.selectedKey = doc.vpc.vpc_key;
if (!state.vpcs.some(item => item.vpc_key === doc.vpc.vpc_key)) state.vpcs.unshift(doc.vpc);
else state.vpcs = state.vpcs.map(item => item.vpc_key === doc.vpc.vpc_key ? doc.vpc : item);
byId('vpc-detail-panel').hidden = false;
renderList(); renderDetail();
}
if (message) { setNotice(message, 'success'); toast(message, 'success'); }
schedulePoll(1500);
}
async function mutate(path, method, body, message) {
if (state.busy) return null;
clearTimeout(state.pollTimer);
const controls = [...document.querySelectorAll('#vpc-workspace button, #vpc-workspace input, #vpc-workspace select')];
const previousDisabled = new Map(controls.map(node => [node, node.disabled]));
state.busy = true; controls.forEach(node => { node.disabled = true; });
let succeeded = false;
try {
const payload = await api(path, { method, body });
await applyDocument(payload, message);
succeeded = true;
return payload;
} catch (error) {
setError(error.message); setNotice(''); return null;
} finally {
state.busy = false;
if (!succeeded) previousDisabled.forEach((disabled, node) => { node.disabled = disabled; });
createRegionOptions(); renderList();
if (succeeded && state.selected) renderDetail();
else refreshRouteEditorState();
schedulePoll(succeeded ? 1500 : undefined);
}
}
async function createVpc(event) {
event.preventDefault(); if (state.busy) return;
setFormError('vpc-create-error', ''); setError('');
clearTimeout(state.pollTimer);
const form = event.currentTarget;
const body = {
name: form.name.value.trim(), region_id: Number(form.region_id.value),
cidr: form.cidr.value.trim(), max_members: Number(form.max_members.value || 256),
};
if (form.subnet_cidr.value.trim()) body.subnet_cidr = form.subnet_cidr.value.trim();
// Keep one idempotency key for the same form values until the server has
// acknowledged the create. A lost 202 response must be retryable without
// allocating a second VPC/CIDR; changing the values starts a new intent.
const fingerprint = JSON.stringify(body);
if (form.dataset.requestFingerprint !== fingerprint
|| !/^[A-Za-z0-9_.:-]{8,128}$/.test(form.dataset.requestKey || '')) {
form.dataset.requestKey = requestKey('vpc-create');
form.dataset.requestFingerprint = fingerprint;
}
body.request_key = form.dataset.requestKey;
state.busy = true;
try {
const payload = await api('/api/v1/vpcs', { method: 'POST', body });
delete form.dataset.requestKey; delete form.dataset.requestFingerprint;
form.reset(); form.max_members.value = '256';
byId('vpc-create-panel').hidden = true;
await applyDocument(payload, 'VPC 已创建,正在等待宿主机回读。');
} catch (error) { setFormError('vpc-create-error', error.message); }
finally { state.busy = false; createRegionOptions(); renderList(); schedulePoll(1500); }
}
async function submitSubnet(form) {
if (!confirmDetailMutation()) return;
const value = form.cidr.value.trim();
if (!value) return;
const payload = await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/subnets`, 'POST', {
cidr: value, request_key: requestKey('subnet-add'),
}, '子网目标已提交,等待宿主机回读。');
if (payload) form.reset();
}
async function submitMember(form) {
if (!confirmDetailMutation()) return;
const body = { subnet_key: form.subnet_key.value, instance_id: Number(form.instance_id.value), request_key: requestKey('member-add') };
if (form.private_ip.value.trim()) body.private_ip = form.private_ip.value.trim();
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/members`, 'POST', body,
'实例已加入 VPC 目标,私网网卡将在实际回读后显示为可用。');
}
function readRoutes() {
return [...document.querySelectorAll('#vpc-route-editor .vpc-editor-row')].map(row => ({
route_key: row.dataset.routeKey,
destination_cidr: row.querySelector('[data-route-field="destination_cidr"]').value.trim(),
next_hop_ip: row.querySelector('[data-route-field="next_hop_ip"]').value,
metric: Number(row.querySelector('[data-route-field="metric"]').value || 100),
}));
}
function readAcl() {
return [...document.querySelectorAll('#vpc-acl-editor .vpc-editor-row')].map(row => {
const value = fieldName => row.querySelector(`[data-acl-field="${fieldName}"]`).value.trim();
const item = {
rule_key: row.dataset.aclKey, priority: Number(value('priority') || 100),
direction: value('direction'), action: value('action'), protocol: value('protocol'),
source_cidr: value('source_cidr'), destination_cidr: value('destination_cidr'),
port_from: value('port_from') === '' ? null : Number(value('port_from')),
port_to: value('port_to') === '' ? null : Number(value('port_to')),
};
return item;
});
}
async function saveEditor(kind) {
if (kind === 'routes') {
refreshRouteEditorState();
if (document.querySelector('#vpc-route-editor [data-vpc-tombstone-state="deleting"]')) {
setError('路由仍有删除中的记录,待宿主机回读完成后再保存整套路由。');
return;
}
if (document.querySelector('#vpc-route-editor [data-invalid="true"]')) {
setError('路由下一跳必须选择当前仍在 VPC 中的成员私网 IP。');
return;
}
}
if (kind === 'acl' && document.querySelector('#vpc-acl-editor [data-vpc-tombstone-state="deleting"]')) {
setError('ACL 仍有删除中的记录,待宿主机回读完成后再保存整套 ACL。');
return;
}
const body = kind === 'routes'
? { routes: readRoutes(), request_key: requestKey('routes') }
: { rules: readAcl(), request_key: requestKey('acl') };
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/${kind === 'routes' ? 'routes' : 'acl'}`,
'PUT', body, `${kind === 'routes' ? '路由' : 'ACL'} 目标已提交,等待宿主机回读。`);
}
async function reconcile() {
if (!state.selectedKey || state.busy) return;
if (state.detailDirty
&& !confirm('当前 VPC 有未保存修改,核对后会丢失这些修改。继续吗?')) return;
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/reconcile`, 'POST', {}, '已请求重新核对 VPC 状态。');
}
async function removeSubnet(key) {
if (!state.selectedKey || state.busy || !confirmDetailMutation()
|| !confirm('确认删除这个子网?子网必须没有成员和地址租约。')) return;
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/subnets/${encodeURIComponent(key)}`,
'DELETE', { request_key: requestKey('subnet-remove') }, '子网删除目标已提交。');
}
async function removeMember(key) {
if (!state.selectedKey || state.busy || !confirmDetailMutation()
|| !confirm('确认让这个实例退出 VPC?宿主机回读确认前,私网 IP 不会重新分配。')) return;
await mutate(`/api/v1/vpcs/${encodeURIComponent(state.selectedKey)}/members/${encodeURIComponent(key)}`,
'DELETE', { request_key: requestKey('member-remove') }, '成员退出目标已提交,等待私网网卡移除回读。');
}
function handleClick(event) {
const listRow = event.target.closest('[data-vpc-key]');
if (listRow && listRow.closest('#vpc-list')) { selectVpc(listRow.dataset.vpcKey); return; }
const removeSubnetKey = event.target.closest('[data-vpc-remove-subnet]')?.dataset.vpcRemoveSubnet;
if (removeSubnetKey) { removeSubnet(removeSubnetKey); return; }
const removeMemberKey = event.target.closest('[data-vpc-remove-member]')?.dataset.vpcRemoveMember;
if (removeMemberKey) { removeMember(removeMemberKey); return; }
const action = event.target.closest('[data-vpc-action]')?.dataset.vpcAction;
if (action === 'reconcile') { reconcile(); return; }
const add = event.target.closest('[data-editor-add]')?.dataset.editorAdd;
if (add) {
const list = byId(add === 'route' ? 'vpc-route-editor' : 'vpc-acl-editor');
if (list.querySelector('[data-vpc-tombstone-state="deleting"]')) return;
list.querySelector('.vpc-empty-inline')?.remove();
list.append(add === 'route' ? routeRow() : aclRow());
markDetailDirty();
refreshRouteEditorState();
return;
}
const remove = event.target.closest('[data-editor-remove]')?.dataset.editorRemove;
if (remove) {
event.target.closest('.vpc-editor-row')?.remove(); markDetailDirty(); refreshRouteEditorState(); return;
}
const save = event.target.closest('[data-vpc-save]')?.dataset.vpcSave;
if (save) saveEditor(save);
}
function handleSubmit(event) {
const kind = event.target.dataset.vpcForm;
if (kind === 'subnet') { event.preventDefault(); submitSubnet(event.target); }
if (kind === 'member') { event.preventDefault(); submitMember(event.target); }
}
function handleDetailInput(event) {
if (event.target.closest('#vpc-detail')) {
markDetailDirty();
if (event.target.matches('[data-route-field="next_hop_ip"]')) refreshRouteEditorState();
}
}
function readBootstrap() {
const node = byId('vpc-bootstrap');
let payload;
try { payload = JSON.parse(node?.textContent || '{}'); } catch { throw new Error('VPC 页面初始数据无效,请刷新页面。'); }
const user = payload?.user;
if (!user || !/^[a-f0-9]{64}$/.test(String(user.csrf_token || ''))
|| !/^[1-9]\d*$/.test(String(user.user_id || ''))) {
throw new Error('VPC 页面安全会话缺失,请刷新页面。');
}
state.csrfToken = String(user.csrf_token); state.userId = String(user.user_id);
state.regions = Array.isArray(payload.regions) ? payload.regions : [];
state.instances = Array.isArray(payload.instances) ? payload.instances : [];
state.vpcs = Array.isArray(payload.vpcs) ? payload.vpcs.map(normalizeRoot).filter(Boolean) : [];
}
function bind() {
byId('vpc-create-open').addEventListener('click', () => {
const form = byId('vpc-create-form');
form.reset(); form.max_members.value = '256';
delete form.dataset.requestKey; delete form.dataset.requestFingerprint;
byId('vpc-create-panel').hidden = false; byId('vpc-create-name').focus();
});
byId('vpc-create-close').addEventListener('click', () => {
const form = byId('vpc-create-form');
byId('vpc-create-panel').hidden = true;
delete form.dataset.requestKey; delete form.dataset.requestFingerprint;
});
byId('vpc-create-form').addEventListener('submit', createVpc);
byId('vpc-refresh').addEventListener('click', async () => {
if (state.detailDirty && !confirm('当前 VPC 有未保存修改,刷新后会丢失这些修改。继续吗?')) return;
await loadList(); if (state.selectedKey) await loadDetail(state.selectedKey, false, true); schedulePoll(8000);
});
byId('vpc-list-reconcile').addEventListener('click', reconcile);
byId('vpc-workspace').addEventListener('click', handleClick);
byId('vpc-workspace').addEventListener('submit', handleSubmit);
byId('vpc-workspace').addEventListener('input', handleDetailInput);
byId('vpc-workspace').addEventListener('change', handleDetailInput);
byId('vpc-detail-refresh').addEventListener('click', () => {
if (state.detailDirty && !confirm('当前 VPC 有未保存修改,刷新后会丢失这些修改。继续吗?')) return;
loadDetail(state.selectedKey, false, true);
});
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') schedulePoll(1000); else clearTimeout(state.pollTimer); });
window.addEventListener('beforeunload', () => { state.stopped = true; state.listController?.abort(); state.detailController?.abort(); clearTimeout(state.pollTimer); }, { once: true });
}
export async function initialize() {
try {
readBootstrap(); bind(); createRegionOptions(); renderList();
await loadList();
if (state.vpcs.length) await selectVpc(state.selectedKey || state.vpcs[0].vpc_key);
schedulePoll(3000);
} catch (error) { setError(error.message); }
}

@ -9,6 +9,7 @@
<link rel="stylesheet" href="/theme/venix/css/icons.min.css?v={$venix_asset_version}"/>
<link rel="stylesheet" href="/cloud/styles.css?v={$venix_asset_version}"/>
<link rel="stylesheet" href="/cloud/client.css?v={$venix_asset_version}"/>
{if $cloud_page == 'vpcs'}<link rel="stylesheet" href="/cloud/vpc.css?v={$venix_asset_version}"/>{/if}
</head>
<body data-cloud-page="{$cloud_page|escape:"html"}" data-asset-version="{$venix_asset_version|escape:"html"}"{if $cloud_vm_id != ''} data-vm-id="{$cloud_vm_id|escape:"html"}"{/if}{if $cloud_invoice_id != ''} data-invoice-id="{$cloud_invoice_id|escape:"html"}"{/if}>
<div id="dashboard-view" class="dashboard user-dashboard">
@ -23,6 +24,8 @@
<div id="cloud-page-error" class="resource-warning" role="alert" hidden></div>
{if $cloud_page == 'instances'}
{include file='cloud/pages/instances.tpl'}
{elseif $cloud_page == 'vpcs'}
{include file='cloud/pages/vpcs.tpl'}
{elseif $cloud_page == 'detail'}
{include file='cloud/pages/detail.tpl'}
{elseif $cloud_page == 'deploy'}

@ -0,0 +1,58 @@
<div id="vpc-workspace">
<div class="page-heading vpc-page-heading">
<div>
<span class="eyebrow">PRIVATE NETWORK</span>
<h1 id="vpc-page-title" tabindex="-1">VPC 私网</h1>
<p>在同一地区的实例之间建立受控三层私网。私网配置只有在宿主机实际回读确认后才会显示为可用。</p>
</div>
<div class="heading-actions">
<button id="vpc-refresh" class="button button-outline" type="button"><span aria-hidden="true">↻</span> 刷新</button>
<button id="vpc-create-open" class="button button-primary" type="button"><span aria-hidden="true">+</span> 创建 VPC</button>
</div>
</div>
<div id="vpc-page-error" class="resource-warning" role="alert" hidden></div>
<div id="vpc-page-notice" class="vpc-notice" role="status" aria-live="polite" hidden></div>
<div class="overview-grid vpc-overview" aria-label="VPC 概览">
<section class="stat-card"><div class="stat-top"><span>VPC</span><span class="stat-icon total" aria-hidden="true">⌁</span></div><strong id="vpc-stat-total">0</strong><small>{$cloud_vpc_scope_label|default:'仅显示当前账户资源'}</small></section>
<section class="stat-card"><div class="stat-top"><span>已确认可用</span><span class="stat-icon running" aria-hidden="true">✓</span></div><strong id="vpc-stat-active">0</strong><small>所有参与宿主机均已回读</small></section>
<section class="stat-card"><div class="stat-top"><span>需要关注</span><span class="stat-icon stopped" aria-hidden="true">!</span></div><strong id="vpc-stat-attention">0</strong><small>正在应用或等待核对</small></section>
</div>
<div class="vpc-columns">
<section class="inventory-panel vpc-list-panel" aria-labelledby="vpc-list-title">
<div class="panel-heading">
<div><h2 id="vpc-list-title">VPC 列表</h2><p id="vpc-list-caption">正在读取 VPC 状态…</p></div>
<div class="panel-tools"><button id="vpc-list-reconcile" class="button button-outline small" type="button" disabled>核对选中 VPC</button></div>
</div>
<div id="vpc-list" class="vpc-list" aria-live="polite" aria-busy="false"></div>
<div id="vpc-list-empty" class="empty-state" hidden><div class="empty-icon" aria-hidden="true">⌁</div><h3>还没有 VPC</h3><p>创建一个私网后,再把同一地区的实例加入其中。</p></div>
</section>
<section id="vpc-detail-panel" class="inventory-panel vpc-detail-panel" aria-labelledby="vpc-detail-title" hidden>
<div class="panel-heading vpc-detail-heading">
<div><h2 id="vpc-detail-title">VPC 详情</h2><p id="vpc-detail-caption">选择左侧 VPC 查看子网、成员、路由和 ACL。</p></div>
<div class="panel-tools"><button id="vpc-detail-refresh" class="button button-outline small" type="button">刷新详情</button></div>
</div>
<div id="vpc-detail" class="vpc-detail" aria-live="polite"></div>
</section>
</div>
<section id="vpc-create-panel" class="inventory-panel vpc-create-panel" aria-labelledby="vpc-create-title" hidden>
<div class="panel-heading"><div><h2 id="vpc-create-title">创建 VPC</h2><p>平台会按地区绑定已激活的 WireGuard Fabric;浏览器不会接触宿主机密钥或地址。</p></div><button id="vpc-create-close" class="button button-ghost small" type="button">取消</button></div>
<form id="vpc-create-form" class="vpc-form">
<div class="vpc-form-grid">
<div class="field"><label for="vpc-create-name">名称 <span>*</span></label><input id="vpc-create-name" name="name" type="text" maxlength="63" required placeholder="例如:生产私网"/><small>只用于面板识别。</small></div>
<div class="field"><label for="vpc-create-region">地区 <span>*</span></label><select id="vpc-create-region" name="region_id" required></select><small id="vpc-create-region-hint">只列出已完成 Fabric 映射的地区。</small></div>
<div class="field"><label for="vpc-create-cidr">VPC CIDR <span>*</span></label><input id="vpc-create-cidr" name="cidr" type="text" inputmode="decimal" maxlength="18" required placeholder="10.40.0.0/16"/><small>必须是 RFC1918 的 /16 至 /24 网段。</small></div>
<div class="field"><label for="vpc-create-subnet">首个子网 CIDR</label><input id="vpc-create-subnet" name="subnet_cidr" type="text" inputmode="decimal" maxlength="18" placeholder="留空则使用整个 VPC CIDR"/><small>子网必须完全位于 VPC CIDR 内;当前不提供网关。</small></div>
<div class="field"><label for="vpc-create-max-members">成员上限</label><input id="vpc-create-max-members" name="max_members" type="number" min="1" max="4096" value="256"/><small>每台虚拟机只允许加入一个 VPC。</small></div>
</div>
<div id="vpc-create-error" class="form-error" role="alert" hidden></div>
<div class="vpc-form-actions"><button class="button button-primary" type="submit">创建并开始应用</button></div>
</form>
</section>
<script id="vpc-bootstrap" type="application/json">{$cloud_vpc_bootstrap_json nofilter}</script>
</div>

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

@ -17,6 +17,9 @@
<a class="sidebar-link{if $panel_cloud_active_key == 'instances' || $panel_cloud_active_key == 'detail' || $panel_cloud_active_key == 'reinstall' || $panel_cloud_active_key == 'rescue' || (!$panel_cloud_mode && $panel_active_key == 'cloud')} active{/if}" href="/user/cloud/instances">
<i class="mdi mdi-server nav-icon" aria-hidden="true"></i><span>我的实例</span>
</a>
<a class="sidebar-link{if $panel_cloud_active_key == 'vpcs'} active{/if}" href="/user/cloud/vpcs">
<i class="mdi mdi-lan-connect nav-icon" aria-hidden="true"></i><span>VPC 私网</span>
</a>
<a class="sidebar-link{if $panel_cloud_active_key == 'deploy'} active{/if}" href="/user/cloud/deploy">
<i class="mdi mdi-cart-outline nav-icon" aria-hidden="true"></i><span>部署实例</span>
</a>

@ -86,6 +86,31 @@ $assert(str_contains($service, "'observed_revision' => " . '$revision')
&& str_contains($service, 'CloudVpcAclRule::class')
&& str_contains($service, 'whereNotIn(\'state\', [\'deleted\'])'),
'VPC child observed revisions are not advanced with the all-host gate.');
$assert(str_contains($service, 'deletedByDestination')
&& str_contains($service, 'deletedByPriority')
&& str_contains($service, 'CloudVpcRoute::class, CloudVpcAclRule::class')
&& str_contains($service, '$allLiveHostsExact')
&& str_contains($service, "where('desired_revision', \$revision)")
&& str_contains($service, 'individually matched above'),
'VPC route/ACL tombstones must close only after exact readback and remain safely reusable.');
$terminalProofStart = strpos($service, '$noDataPlaneTerminalProof');
$terminalProofEnd = $terminalProofStart === false ? false
: strpos($service, '// Routes and ACLs are part of the exact host dataplane digest.',
$terminalProofStart);
$terminalProofBlock = ($terminalProofStart !== false && $terminalProofEnd !== false)
? substr($service, $terminalProofStart, $terminalProofEnd - $terminalProofStart) : '';
$assert($terminalProofBlock !== ''
&& str_contains($terminalProofBlock, '$terminalGate')
&& str_contains($terminalProofBlock, '$required->count() === 0')
&& str_contains($terminalProofBlock, '$liveRequired->count() === 0')
&& str_contains($terminalProofBlock, '$hosts === []')
&& str_contains($terminalProofBlock, '!$pendingHostTombstone')
&& str_contains($terminalProofBlock, 'no_data_plane_terminal_proof')
&& str_contains($terminalProofBlock, 'CloudVpcRoute::class, CloudVpcAclRule::class')
&& !str_contains($terminalProofBlock, 'CloudVpcMember::class')
&& !str_contains($terminalProofBlock, 'CloudVpcPrivateIp::class')
&& !str_contains($terminalProofBlock, 'CloudVpcSubnet::class'),
'Empty-VPC terminal proof may close only route/ACL tombstones and must not release private member resources.');
$assert(!str_contains($service, 'CloudJob')
&& !str_contains($service, 'network_change')
&& !str_contains($service, 'publicIpCidr'),

@ -0,0 +1,136 @@
<?php
// Static tenant-page contract. The VPC control plane and host dataplane have
// their own tests; this protects the user-facing page from drifting away from
// the database-only bootstrap and the versioned VPC API.
$root = dirname(__DIR__);
$read = static fn (string $path): string => (string) file_get_contents($root . '/' . $path);
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$controller = $read('app/Controllers/CloudPageController.php');
$pageService = $read('app/Services/Cloud/CloudVpcPageService.php');
$middleware = $read('app/Middleware/CloudApi.php');
$routes = $read('config/routes.php');
$shell = $read('resources/views/venix/cloud/page.tpl');
$template = $read('resources/views/venix/cloud/pages/vpcs.tpl');
$sidebar = $read('resources/views/venix/user/panel_sidebar.tpl');
$app = $read('public/cloud/app.js');
$script = $read('public/cloud/vpc.js');
$styles = $read('public/cloud/vpc.css');
$controllerStart = strpos($controller, 'public function vpcs(');
$controllerEnd = strpos($controller, 'public function detail(', $controllerStart ?: 0);
$controllerSection = $controllerStart !== false && $controllerEnd !== false
? substr($controller, $controllerStart, $controllerEnd - $controllerStart) : '';
$assert($controllerSection !== ''
&& str_contains($controllerSection, 'CloudAccess::actor(false)')
&& str_contains($controllerSection, 'CloudVpcPageService::bootstrap($actor)')
&& str_contains($controllerSection, 'CloudVpcService::listing($actor)')
&& str_contains($controllerSection, "'cloud_vpc_bootstrap_json'")
&& str_contains($controllerSection, '$this->safeJson($payload)'),
'VPC page must use an owner-scoped, safe database bootstrap and the typed listing projection.');
$assert(str_contains($controller, 'use App\\Services\\Cloud\\CloudVpcPageService;')
&& str_contains($controller, "'cloud_vpc_bootstrap_json', '{}'")
&& !str_contains($controllerSection, 'CloudEngineClient')
&& !str_contains($controllerSection, 'CloudHost'),
'VPC first paint must not contact libvirt or expose host inventory.');
$assert(str_contains($pageService, 'CloudRegionFabric')
&& str_contains($pageService, "->where('cloud_region_fabrics.state', 'active')")
&& str_contains($pageService, "->where('cloud_region_fabrics.fabric_revision', '>', 0)")
&& str_contains($pageService, "->where('region.status', 'active')")
&& str_contains($pageService, "->where('user_id', \$userId)")
&& str_contains($pageService, "->where('status', 'active')")
&& str_contains($pageService, "(string) \$row->service_status === 'active'")
&& str_contains($pageService, "(int) \$row->expires_at > time()")
&& str_contains($pageService, '->limit(200)')
&& !str_contains($pageService, 'CloudEngineClient')
&& !str_contains($pageService, "'host_id'"),
'VPC bootstrap must expose only active Fabric regions and bounded owner-scoped instances.');
$assert(str_contains($routes, "\$this->get('/cloud/vpcs', 'App\\Controllers\\CloudPageController:vpcs');"),
'Authenticated user routes must expose the VPC page.');
$assert(str_contains($middleware, "^/api/v1/vpcs(?:/[0-9a-f]{32}(?:/.*)?)?\$#D")
&& str_contains($middleware, 'CloudAccess::actor(!$databaseOnly)'),
'VPC API requests must stay in the PHP/database-only auth lane.');
$assert(str_contains($sidebar, 'href="/user/cloud/vpcs"')
&& str_contains($sidebar, "panel_cloud_active_key == 'vpcs'")
&& str_contains($sidebar, 'VPC 私网'),
'The user cloud navigation must expose and mark the VPC page.');
$assert(str_contains($shell, "cloud_page == 'vpcs'")
&& str_contains($shell, "cloud/pages/vpcs.tpl")
&& str_contains($shell, '/cloud/vpc.css'),
'The cloud shell must load the dedicated VPC view and styles.');
$assert(str_contains($app, "vpcs: '/cloud/vpc.js'"),
'Cloud page module routing must load the VPC module.');
foreach ([
'vpc-create-form', 'vpc-create-region', 'vpc-create-cidr', 'vpc-create-subnet',
'vpc-list', 'vpc-detail', 'vpc-list-reconcile', 'vpc-bootstrap',
] as $id) {
$assert(str_contains($template, 'id="' . $id . '"'),
'VPC view is missing required control ' . $id . '.');
}
foreach (['子网与 CIDR', '成员与私网 IP', 'Route', 'VPC ACL', '最近操作'] as $label) {
$assert(str_contains($script, $label),
'VPC module is missing section ' . $label . '.');
}
$assert(str_contains($template, '创建 VPC'),
'VPC view is missing the create form.');
$assert(str_contains($script, "'/api/v1/vpcs'")
&& str_contains($script, '/subnets')
&& str_contains($script, '/members')
&& str_contains($script, '/reconcile')
&& str_contains($script, "kind === 'routes'")
&& str_contains($script, ": 'acl'")
&& str_contains($script, "'DELETE'")
&& str_contains($script, "'PUT'"),
'VPC module must cover create, subnet, member, route, ACL, reconcile and deletion APIs.');
$assert(str_contains($script, 'X-CSRF-Token')
&& str_contains($script, 'credentials: \'same-origin\'')
&& str_contains($script, 'request_key')
&& str_contains($script, 'function entityKey()')
&& str_contains($script, 'route_key: row.dataset.routeKey')
&& str_contains($script, 'rule_key: row.dataset.aclKey'),
'VPC mutations must use same-origin CSRF protection and separate idempotency/entity keys.');
foreach (['applying', 'degraded', 'uncertain', 'waiting', 'active'] as $status) {
$assert(str_contains($script, $status),
'VPC UI lost state projection for ' . $status . '.');
}
$assert(str_contains($script, 'usable === true')
&& str_contains($script, 'desired_revision')
&& str_contains($script, 'observed_revision')
&& str_contains($script, 'setTimeout')
&& str_contains($script, 'visibilitychange')
&& str_contains($script, 'AbortController')
&& str_contains($script, 'loadDetail(state.selectedKey, true)')
&& str_contains($script, 'state.detailDirty')
&& str_contains($script, 'allowDirty = false'),
'VPC UI must poll desired/observed state, pause hidden tabs and only show active after usable readback.');
$assert(str_contains($script, 'data-vpc-tombstone-state="deleting"')
&& str_contains($script, 'pendingTombstones')
&& str_contains($script, 'sameRegion')
&& str_contains($script, 'alreadyAttached')
&& str_contains($script, 'option.disabled')
&& str_contains($script, 'requestFingerprint')
&& str_contains($script, 'confirmDetailMutation'),
'VPC editors must preserve dirty drafts, block only in-flight tombstones and constrain member choices.');
$assert(!str_contains($script, '/internal/v1/')
&& !str_contains($script, 'host_id')
&& !str_contains($script, 'credential_cipher'),
'Tenant VPC JavaScript must not call private engine endpoints or expose host credentials.');
$assert(str_contains($styles, '.vpc-state-pill')
&& str_contains($styles, '.vpc-columns')
&& str_contains($styles, '@media'),
'VPC page needs dedicated state/list/detail responsive styling.');
echo "Tenant VPC page, API wiring and state-polling contract passed.\n";
Loading…
Cancel
Save