diff --git a/web/app/Controllers/Admin/CloudPageController.php b/web/app/Controllers/Admin/CloudPageController.php index 5f541b3e..14eb1fde 100644 --- a/web/app/Controllers/Admin/CloudPageController.php +++ b/web/app/Controllers/Admin/CloudPageController.php @@ -11,6 +11,7 @@ use App\Services\Cloud\CloudAdminResourceService; use App\Services\Cloud\CloudAdminVpcControlService; use App\Services\Cloud\CloudCountryCatalog; use App\Services\Cloud\CloudError; +use App\Services\Cloud\CloudMaintenanceNoticeService; use App\Services\Cloud\CloudPlatformDefaultNetworkPolicy; use App\Services\Cloud\CloudPlatformTestNetworkPolicy; @@ -229,6 +230,59 @@ final class CloudPageController extends AdminController return $response->withStatus($status)->withHeader('Cache-Control', 'private, no-store'); } + public function maintenanceNotices($request, $response, $args) + { + try { + $actor = CloudAccess::actor(false); + } catch (CloudError $exception) { + return $response->withStatus($exception->httpStatus) + ->withHeader('Cache-Control', 'private, no-store'); + } + if (!($actor['is_admin'] ?? false)) { + return $response->withStatus(403) + ->withHeader('Cache-Control', 'private, no-store'); + } + + $payload = null; + $error = ''; + $status = 200; + try { + $service = new CloudMaintenanceNoticeService(); + $catalog = $service->catalog(); + $payload = [ + 'page' => $service->page($request->getQueryParams()), + 'catalog' => $catalog, + 'prefill' => $service->prefill( + $request->getQueryParams(), + $catalog + ), + 'can_manage' => (bool) ($actor['can_manage'] ?? false), + ]; + } catch (CloudError $exception) { + $error = $exception->getMessage(); + $status = $exception->httpStatus; + } catch (\Throwable $exception) { + error_log('Admin maintenance notice snapshot failed: ' + . get_class($exception)); + $error = '维护通知数据暂时无法读取,请稍后重试。'; + $status = 503; + } + $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); + $smarty = $this->view()->assign([ + 'maintenance_notice_page' => $payload, + 'maintenance_notice_error' => $error, + 'maintenance_notice_bootstrap_json' => $json, + ]); + $response->getBody()->write( + $smarty->fetch('admin/cloud/maintenance_notices.tpl') + ); + return $response->withStatus($status) + ->withHeader('Cache-Control', 'private, no-store'); + } + public function platformDefaultPolicy($request, $response, $args) { try { diff --git a/web/app/Services/Cloud/CloudMaintenanceNoticeService.php b/web/app/Services/Cloud/CloudMaintenanceNoticeService.php index 82040966..d76571b2 100644 --- a/web/app/Services/Cloud/CloudMaintenanceNoticeService.php +++ b/web/app/Services/Cloud/CloudMaintenanceNoticeService.php @@ -33,6 +33,70 @@ final class CloudMaintenanceNoticeService return $this->audience->preview($scopeType, $scopeId); } + /** Return the immutable identifiers administrators may preview. */ + public function catalog(): array + { + $hosts = DB::table('cloud_hosts')->orderBy('name')->orderBy('id') + ->get(['id', 'name', 'region', 'enabled']) + ->map(static fn ($host): array => [ + 'id' => (int) $host->id, + 'name' => (string) $host->name, + 'region' => (string) $host->region, + 'enabled' => (bool) $host->enabled, + ])->all(); + $pools = DB::table('cloud_public_ip_pools as pool') + ->join('cloud_hosts as host', 'host.id', '=', 'pool.host_id') + ->orderBy('host.name')->orderBy('pool.address_family') + ->orderBy('pool.name')->orderBy('pool.id') + ->get([ + 'pool.id', 'pool.pool_key', 'pool.host_id', + 'pool.address_family', 'pool.name', 'pool.cidr', 'pool.state', + 'host.name as host_name', + ])->map(static fn ($pool): array => [ + 'id' => (int) $pool->id, + 'pool_key' => (string) $pool->pool_key, + 'host_id' => (int) $pool->host_id, + 'host_name' => (string) $pool->host_name, + 'address_family' => (int) $pool->address_family, + 'name' => (string) $pool->name, + 'cidr' => (string) $pool->cidr, + 'state' => (string) $pool->state, + ])->all(); + return ['hosts' => $hosts, 'pools' => $pools]; + } + + /** Resolve URL shortcuts only against the current server-owned catalog. */ + public function prefill(array $query, array $catalog): array + { + $scopeType = trim((string) ($query['scope_type'] ?? '')); + if ($scopeType === 'host') { + $hostId = filter_var($query['host_id'] ?? $query['scope_id'] ?? null, + FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); + foreach ($catalog['hosts'] ?? [] as $host) { + if ($hostId !== false && (int) $host['id'] === (int) $hostId) { + return ['scope_type' => 'host', 'scope_id' => (int) $hostId]; + } + } + } + if ($scopeType === 'public_ip_pool') { + $poolKey = strtolower(trim((string) ($query['pool_key'] ?? ''))); + $hostId = filter_var($query['host_id'] ?? null, + FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); + foreach ($catalog['pools'] ?? [] as $pool) { + if (preg_match('/^[0-9a-f]{32}$/D', $poolKey) === 1 + && hash_equals((string) $pool['pool_key'], $poolKey) + && $hostId !== false + && (int) $pool['host_id'] === (int) $hostId) { + return [ + 'scope_type' => 'public_ip_pool', + 'scope_id' => (int) $pool['id'], + ]; + } + } + } + return []; + } + public function schedule(int $actorId, string $idempotencyKey, array $input): array { diff --git a/web/config/routes.php b/web/config/routes.php index 5a35447a..2afacad5 100644 --- a/web/config/routes.php +++ b/web/config/routes.php @@ -192,6 +192,8 @@ $app->group('/admin', function () { $this->get('/billing', 'App\Controllers\Admin\CloudPageController:billing'); $this->get('/cloud/orders', 'App\Controllers\Admin\CloudPageController:orders'); $this->get('/operations', 'App\Controllers\Admin\CloudPageController:operations'); + $this->get('/maintenance-notices', + 'App\Controllers\Admin\CloudPageController:maintenanceNotices'); $this->get('/system-logs', 'App\Controllers\Admin\CloudPageController:systemLogs'); $this->get('/platform-default-policy', 'App\Controllers\Admin\CloudPageController:platformDefaultPolicy'); // Telegram administration is rendered inside the ticket system; these diff --git a/web/public/cloud/admin-maintenance-notices.js b/web/public/cloud/admin-maintenance-notices.js new file mode 100644 index 00000000..af710be4 --- /dev/null +++ b/web/public/cloud/admin-maintenance-notices.js @@ -0,0 +1,269 @@ +const root = document.querySelector('[data-admin-maintenance-notices]'); + +if (root) { + const byId = id => document.getElementById(id); + const element = (tag, className = '', text = '') => { + const node = document.createElement(tag); + if (className) node.className = className; + if (text !== '') node.textContent = text; + return node; + }; + const parseBootstrap = () => { + try { return JSON.parse(byId('admin-maintenance-notice-bootstrap')?.textContent || 'null'); } + catch (error) { return null; } + }; + const bootstrap = parseBootstrap() || {}; + const canManage = root.dataset.canManage === '1' && bootstrap.can_manage === true; + const runtime = window.VenixAdminRequestRuntime.create({}); + const state = { + catalog: bootstrap.catalog || { hosts: [], pools: [] }, + page: bootstrap.page || { page: 1, per_page: 20, total: 0, items: [] }, + prefill: bootstrap.prefill || {}, + preview: null, + mutationLocked: false, + detail: null, + }; + const labels = { + impacts: { + network_interruption: '网络可能中断', instance_restart: '实例需要重启', + service_interruption: '服务可能中断', no_interruption: '预计不中断', + }, + statuses: { + scheduled: '待发送', sending: '发送中', completed: '已完成', + attention: '需核对', cancelled: '已取消', + }, + }; + + function notify(message, error = false) { + const node = byId('maintenance-notice-status'); + node.textContent = message; + node.classList.toggle('is-error', error); + node.classList.toggle('is-success', !error); + } + function timestamp(value) { + const milliseconds = new Date(value).getTime(); + return Number.isFinite(milliseconds) ? Math.floor(milliseconds / 1000) : 0; + } + function utc(value) { + const parsed = timestamp(value); + return parsed > 0 ? new Date(parsed * 1000).toISOString().replace('.000Z', ' UTC') : '未选择'; + } + function localDateTime(value) { + const date = new Date(value * 1000); + return Number.isFinite(date.getTime()) ? date.toLocaleString() : '—'; + } + function localInputValue(date) { + const shifted = new Date(date.getTime() - date.getTimezoneOffset() * 60000); + return shifted.toISOString().slice(0, 16); + } + function scopeLabel(scope) { + if (!scope || typeof scope !== 'object') return '范围未知'; + return `${scope.type === 'host' ? '计算节点' : '公网地址池'} · ${scope.label || scope.id || '未知'}`; + } + function badge(status) { + const tone = status === 'completed' ? 'success' + : status === 'attention' ? 'danger' + : status === 'cancelled' ? 'secondary' : 'primary'; + return element('span', `badge text-bg-${tone}`, labels.statuses[status] || status || '未知'); + } + function updateUtcConfirmation() { + byId('maintenance-utc-confirmation').textContent = `邮件所示 UTC 时间:维护开始 ${utc(byId('maintenance-starts').value)};维护结束 ${utc(byId('maintenance-ends').value)};计划发送 ${utc(byId('maintenance-scheduled').value)}。`; + } + function invalidatePreview() { + state.preview = null; + byId('maintenance-preview-card').hidden = true; + byId('maintenance-preview-instances').replaceChildren(); + byId('maintenance-schedule').disabled = true; + } + function targetOptions() { + const type = byId('maintenance-scope-type').value; + const target = byId('maintenance-scope-id'); + const selected = String(state.prefill.scope_type === type ? state.prefill.scope_id || '' : ''); + target.replaceChildren(); + const rows = type === 'host' ? state.catalog.hosts || [] : state.catalog.pools || []; + for (const row of rows) { + const label = type === 'host' + ? `${row.name}${row.region ? ` · ${row.region}` : ''}${row.enabled ? '' : ' · 已停用'}` + : `${row.host_name} · IPv${row.address_family} · ${row.name} · ${row.cidr}${row.state === 'active' ? '' : ` · ${row.state}`}`; + target.append(new Option(label, String(row.id))); + } + if (selected && rows.some(row => String(row.id) === selected)) target.value = selected; + state.prefill = {}; + invalidatePreview(); + } + function validateTimes() { + const starts = timestamp(byId('maintenance-starts').value); + const ends = timestamp(byId('maintenance-ends').value); + const scheduled = timestamp(byId('maintenance-scheduled').value); + if (!starts || !ends || !scheduled || ends <= starts) throw new Error('请选择有效的维护窗口和发送时间。'); + return { maintenance_starts_at: starts, maintenance_ends_at: ends, scheduled_at: scheduled }; + } + function scopeRequest() { + const scopeId = Number(byId('maintenance-scope-id').value); + if (!Number.isInteger(scopeId) || scopeId < 1) throw new Error('请选择通知范围。'); + return { scope_type: byId('maintenance-scope-type').value, scope_id: scopeId }; + } + function setMutationBusy(busy) { + for (const id of ['maintenance-preview', 'maintenance-schedule']) { + const node = byId(id); + node.disabled = busy || state.mutationLocked || !canManage || (id === 'maintenance-schedule' && !state.preview); + } + } + function renderPreview(payload) { + state.preview = payload; + const card = byId('maintenance-preview-card'); + card.hidden = false; + byId('maintenance-preview-summary').textContent = `${scopeLabel(payload.scope)} · ${Number(payload.instance_count || 0)} 台实例 · ${Number(payload.recipient_count || 0)} 位可投递用户${Number(payload.skipped_count || 0) ? ` · ${Number(payload.skipped_count)} 位跳过` : ''}`; + const body = byId('maintenance-preview-instances'); + body.replaceChildren(); + for (const instance of payload.instances || []) { + const row = document.createElement('tr'); + for (const value of [instance.name || `实例 #${instance.id}`, `#${instance.host_id}`, instance.ipv4 || '—', instance.ipv6 || '—']) row.append(element('td', '', String(value))); + body.append(row); + } + byId('maintenance-schedule').disabled = !canManage || state.mutationLocked; + } + function renderList() { + const body = byId('maintenance-notice-list'); + body.replaceChildren(); + const items = state.page.items || []; + if (!items.length) { + const row = document.createElement('tr'); + const cell = element('td', 'text-muted text-center py-4', '当前没有维护通知。'); + cell.colSpan = 5; row.append(cell); body.append(row); + } + for (const item of items) { + const row = document.createElement('tr'); + const subject = element('td'); + subject.append(element('strong', 'd-block', item.subject || '未命名通知'), element('span', 'text-muted fs-13', scopeLabel(item.scope))); + const windowCell = element('td'); + windowCell.append(element('span', 'd-block', localDateTime(item.maintenance_starts_at)), element('span', 'text-muted fs-13', `至 ${localDateTime(item.maintenance_ends_at)}`)); + const audience = element('td', '', `${Number(item.instance_count || 0)} 台 / ${Number(item.recipient_count || 0)} 位`); + const status = element('td'); status.append(badge(item.status)); + const action = element('td'); + const detail = element('button', 'btn btn-sm btn-light', '查看详情'); + detail.type = 'button'; detail.addEventListener('click', () => { void openDetail(item.notice_key); }); + action.append(detail); + row.append(subject, windowCell, audience, status, action); body.append(row); + } + const totalPages = Math.max(1, Math.ceil(Number(state.page.total || 0) / Number(state.page.per_page || 20))); + const nav = byId('maintenance-pagination'); + nav.hidden = Number(state.page.total || 0) <= Number(state.page.per_page || 20); + byId('maintenance-page-label').textContent = `第 ${state.page.page || 1} / ${totalPages} 页 · 共 ${state.page.total || 0} 条`; + byId('maintenance-previous').disabled = Number(state.page.page || 1) <= 1; + byId('maintenance-next').disabled = Number(state.page.page || 1) >= totalPages; + } + async function loadPage(page = 1) { + const params = new URLSearchParams({ page: String(page), per_page: '20' }); + const status = byId('maintenance-status-filter').value; + if (status) params.set('status', status); + notify('正在刷新维护通知…'); + try { + state.page = await runtime.read(`/api/v1/admin/maintenance-notices?${params.toString()}`); + renderList(); notify(`已读取 ${Number(state.page.total || 0)} 条通知。`); + } catch (error) { notify(error.message || '维护通知读取失败。', true); } + } + function appendFact(list, label, value) { + list.append(element('dt', '', label), element('dd', '', String(value ?? '—'))); + } + function detailTable(title, columns, rows) { + const section = element('section', 'mt-4'); + section.append(element('h3', 'h6', title)); + const wrap = element('div', 'table-responsive'); + const table = element('table', 'table table-sm align-middle'); + const head = document.createElement('thead'); const headRow = document.createElement('tr'); + for (const column of columns) headRow.append(element('th', '', column)); + head.append(headRow); const body = document.createElement('tbody'); + for (const values of rows) { const row = document.createElement('tr'); for (const value of values) row.append(element('td', '', String(value ?? '—'))); body.append(row); } + table.append(head, body); wrap.append(table); section.append(wrap); return section; + } + function renderDetail(detail) { + state.detail = detail; + byId('maintenance-detail-title').textContent = detail.subject || '维护通知'; + byId('maintenance-detail-state').textContent = `${labels.statuses[detail.status] || detail.status} · ${scopeLabel(detail.scope)}`; + const body = byId('maintenance-detail-body'); body.replaceChildren(); + const facts = element('dl', 'admin-instance-details'); + appendFact(facts, '影响类型', labels.impacts[detail.impact] || detail.impact); + appendFact(facts, '计划发送', localDateTime(detail.scheduled_at)); + appendFact(facts, '维护开始', localDateTime(detail.maintenance_starts_at)); + appendFact(facts, '维护结束', localDateTime(detail.maintenance_ends_at)); + appendFact(facts, '受众', `${detail.instance_count} 台实例 / ${detail.recipient_count} 位用户`); + body.append(facts, element('h3', 'h6 mt-4', '通知正文'), element('p', 'text-break', detail.message_text || '—')); + body.append(detailTable('受影响实例', ['实例', 'IPv4', 'IPv6'], (detail.instances || []).map(item => [item.instance_name, item.ipv4 || '—', item.ipv6 || '—']))); + body.append(detailTable('投递结果', ['用户', '邮箱', '状态'], (detail.recipients || []).map(item => [`#${item.user_id}`, item.email, item.status]))); + const cancel = byId('maintenance-detail-cancel'); + cancel.hidden = !canManage || !['scheduled', 'sending'].includes(detail.status); + cancel.disabled = state.mutationLocked; + } + async function openDetail(key) { + const dialog = byId('maintenance-detail'); + if (!dialog.open) dialog.showModal(); + byId('maintenance-detail-state').textContent = '正在读取通知详情…'; + byId('maintenance-detail-body').replaceChildren(); + byId('maintenance-detail-cancel').hidden = true; + try { renderDetail(await runtime.read(`/api/v1/admin/maintenance-notices/${encodeURIComponent(key)}`)); } + catch (error) { byId('maintenance-detail-state').textContent = error.message || '详情读取失败。'; } + } + function uncertain(error) { + if (!error?.mutationMayHaveApplied) return false; + state.mutationLocked = true; + setMutationBusy(false); + notify('操作结果待核对,请刷新页面确认;当前页面不会再次提交。', true); + return true; + } + + byId('maintenance-scope-type').value = state.prefill.scope_type || 'host'; + targetOptions(); + const now = Date.now(); + byId('maintenance-scheduled').value = localInputValue(new Date(now + 5 * 60000)); + byId('maintenance-starts').value = localInputValue(new Date(now + 60 * 60000)); + byId('maintenance-ends').value = localInputValue(new Date(now + 2 * 60 * 60000)); + updateUtcConfirmation(); renderList(); setMutationBusy(false); + + byId('maintenance-scope-type').addEventListener('change', targetOptions); + byId('maintenance-scope-id').addEventListener('change', invalidatePreview); + for (const id of ['maintenance-starts', 'maintenance-ends', 'maintenance-scheduled']) byId(id).addEventListener('change', () => { updateUtcConfirmation(); invalidatePreview(); }); + byId('maintenance-preview').addEventListener('click', async () => { + if (!canManage || state.mutationLocked) return; + setMutationBusy(true); notify('正在核对受影响实例与用户…'); + try { + renderPreview(await runtime.mutate('/api/v1/admin/maintenance-notices/preview', { method: 'POST', response: 'json', body: scopeRequest() })); + notify('受众预览已冻结,请核对后调度发送。'); + } catch (error) { if (!uncertain(error)) notify(error.message || '受众预览失败。', true); } + finally { setMutationBusy(false); } + }); + byId('maintenance-notice-form').addEventListener('submit', async event => { + event.preventDefault(); + if (!canManage || state.mutationLocked || !state.preview) return; + setMutationBusy(true); notify('正在创建维护通知…'); + try { + const payload = { + ...scopeRequest(), ...validateTimes(), + subject: byId('maintenance-subject').value.trim(), + message_text: byId('maintenance-message').value.trim(), + impact: byId('maintenance-impact').value, + audience_digest: state.preview.audience_digest, + }; + const detail = await runtime.mutate('/api/v1/admin/maintenance-notices', { method: 'POST', response: 'json', body: payload }); + invalidatePreview(); notify(`维护通知“${detail.subject}”已创建。`); await loadPage(1); + } catch (error) { if (!uncertain(error)) notify(error.message || '维护通知创建失败。', true); } + finally { setMutationBusy(false); } + }); + byId('maintenance-detail-cancel').addEventListener('click', async () => { + if (!canManage || state.mutationLocked || !state.detail) return; + const confirmed = await window.VenixAdminDangerDialog.confirm({ tone: 'warning', title: '取消尚未发送的维护邮件', message: '只会取消尚未被发送进程领取的邮件;正在发送的记录仍会继续收敛。', confirmText: '确认取消' }); + if (!confirmed) return; + const button = byId('maintenance-detail-cancel'); button.disabled = true; + try { + renderDetail(await runtime.mutate(`/api/v1/admin/maintenance-notices/${encodeURIComponent(state.detail.notice_key)}/cancel`, { method: 'POST', response: 'json', body: {} })); + notify('尚未领取的维护邮件已取消。'); await loadPage(state.page.page || 1); + } catch (error) { if (!uncertain(error)) notify(error.message || '取消失败。', true); } + finally { button.disabled = state.mutationLocked; } + }); + byId('maintenance-detail-close').addEventListener('click', () => byId('maintenance-detail').close()); + byId('maintenance-detail').addEventListener('cancel', event => { event.preventDefault(); byId('maintenance-detail').close(); }); + byId('maintenance-notice-refresh').addEventListener('click', () => { void loadPage(state.page.page || 1); }); + byId('maintenance-status-filter').addEventListener('change', () => { void loadPage(1); }); + byId('maintenance-previous').addEventListener('click', () => { void loadPage(Math.max(1, Number(state.page.page || 1) - 1)); }); + byId('maintenance-next').addEventListener('click', () => { void loadPage(Number(state.page.page || 1) + 1); }); +} diff --git a/web/resources/views/venix/admin/cloud/maintenance_notices.tpl b/web/resources/views/venix/admin/cloud/maintenance_notices.tpl new file mode 100644 index 00000000..c967568b --- /dev/null +++ b/web/resources/views/venix/admin/cloud/maintenance_notices.tpl @@ -0,0 +1,71 @@ +{assign var=admin_title value='维护通知'} +{assign var=admin_active value='maintenance-notices'} +{include file='admin/static_header.tpl'} + +
+
+
+

维护通知

+

按计算节点或公网地址池冻结受影响实例,同一用户只发送一封邮件。通知时间统一以 UTC 写入邮件。

+
+
+ {if $maintenance_notice_error|default:''}{$maintenance_notice_error|escape}{else}已读取 {$maintenance_notice_page.page.total|default:0|escape} 条通知{/if} + +
+
+ + {if !$admin_can_manage|default:false} +

当前管理员为只读模式,可查看已脱敏的通知记录,不能预览受众、创建或取消通知。

+ {/if} + +
+
+

创建维护通知

+

先预览并确认冻结受众,再调度发送。受众变化后原预览摘要会失效,服务端会拒绝创建。

+
+
+
+
+
+ + + + + + + + +
+

请选择维护窗口和发送时间。

+
+
+
+
+
+ + + +
+
+

通知记录

邮件已交给服务商不代表用户一定收件;效果未知的投递不会自动重发。

+ +
+
+
主题与范围维护窗口受众状态操作
+ +
+
+ +
+ + +

维护通知详情

通知

+

正在读取通知详情…

+ +
+ + +{include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/admin/static_header.tpl b/web/resources/views/venix/admin/static_header.tpl index 6a9bbbd0..9259dfff 100644 --- a/web/resources/views/venix/admin/static_header.tpl +++ b/web/resources/views/venix/admin/static_header.tpl @@ -169,6 +169,7 @@
  • 云镜像模板
  • 救援镜像
  • 虚拟机管理
  • +
  • 维护通知
  • 系统运行与异常任务
  • diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 9d26e759..31911ba1 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026110504' scope='global'} +{assign var=venix_asset_version value='2026110601' scope='global'} diff --git a/web/tests/AdminMaintenanceNoticeBehaviorTest.mjs b/web/tests/AdminMaintenanceNoticeBehaviorTest.mjs new file mode 100644 index 00000000..cba8b196 --- /dev/null +++ b/web/tests/AdminMaintenanceNoticeBehaviorTest.mjs @@ -0,0 +1,22 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; + +const source = await readFile( + new URL('../public/cloud/admin-maintenance-notices.js', import.meta.url), + 'utf8', +); + +assert.match(source, /state\.preview = null;[\s\S]*maintenance-schedule/, + 'Changing the scope must invalidate the reviewed audience.'); +assert.match(source, /maintenance_starts_at: starts, maintenance_ends_at: ends, scheduled_at: scheduled/, + 'Browser-local inputs must be converted to epoch seconds for UTC delivery.'); +assert.match(source, /audience_digest: state\.preview\.audience_digest/, + 'Scheduling must send the reviewed audience digest.'); +assert.match(source, /if \(!error\?\.mutationMayHaveApplied\) return false;[\s\S]*state\.mutationLocked = true/, + 'An uncertain write must lock the composer instead of replaying it.'); +assert.match(source, /VenixAdminDangerDialog\.confirm/, + 'Cancellation must use the shared administrator danger dialog.'); +assert.doesNotMatch(source, /\bfetch\s*\(|innerHTML|window\.confirm/, + 'The page must not bypass the request runtime or safe DOM rendering.'); + +console.log('Maintenance notice browser behavior checks passed.'); diff --git a/web/tests/CloudAssetVersionContractTest.php b/web/tests/CloudAssetVersionContractTest.php index 30fa1d70..ed7745c8 100644 --- a/web/tests/CloudAssetVersionContractTest.php +++ b/web/tests/CloudAssetVersionContractTest.php @@ -15,7 +15,7 @@ $assert = static function (bool $condition, string $message): void { }; $assert(is_string($assets) - && str_contains($assets, "venix_asset_version value='2026110503'") + && str_contains($assets, "venix_asset_version value='2026110601'") && is_string($cloudShell) && str_contains($cloudShell, '/cloud/app.js?v={$venix_asset_version}'), 'The cloud application entry must use the shared Venix asset version.'); diff --git a/web/tests/CloudMaintenanceNoticeAdminPageContractTest.php b/web/tests/CloudMaintenanceNoticeAdminPageContractTest.php new file mode 100644 index 00000000..d4ec37c8 --- /dev/null +++ b/web/tests/CloudMaintenanceNoticeAdminPageContractTest.php @@ -0,0 +1,56 @@ + (bool)"), + 'The administrator page route lost authorization or private bootstrap boundaries.'); +$assert(str_contains($service, 'public function catalog(): array') + && str_contains($service, 'public function prefill(') + && str_contains($service, "hash_equals((string) \$pool['pool_key'], \$poolKey)") + && str_contains($service, "'state' => (string) \$pool->state"), + 'Audience shortcuts must resolve through the full server-owned catalog.'); +$assert(str_contains($template, 'data-admin-maintenance-notices') + && str_contains($template, 'data-can-manage=') + && str_contains($template, '
    ') + && str_contains($template, 'admin-maintenance-notice-bootstrap') + && str_contains($template, ' nofilter}') + && str_contains($template, + '/cloud/admin-maintenance-notices.js?v={$venix_asset_version}') + && str_contains($sidebar, 'href="/admin/maintenance-notices"'), + 'Maintenance notice page or navigation contracts are incomplete.'); +$assert(str_contains($script, 'window.VenixAdminRequestRuntime.create') + && str_contains($script, 'window.VenixAdminDangerDialog.confirm') + && str_contains($script, 'mutationMayHaveApplied') + && str_contains($script, 'state.mutationLocked = true') + && str_contains($script, 'audience_digest: state.preview.audience_digest') + && str_contains($script, 'textContent') + && !str_contains($script, 'window.confirm') + && !str_contains($script, 'innerHTML') + && !preg_match('/\bfetch\s*\(/', $script), + 'Browser actions must use the shared runtime and safe DOM rendering.'); + +echo "Maintenance notice administrator page contracts passed.\n"; diff --git a/web/tests/CloudMaintenanceNoticeServiceTest.php b/web/tests/CloudMaintenanceNoticeServiceTest.php index 75cd6584..b32e6b56 100644 --- a/web/tests/CloudMaintenanceNoticeServiceTest.php +++ b/web/tests/CloudMaintenanceNoticeServiceTest.php @@ -37,6 +37,7 @@ $schema->create('cloud_hosts', static function (Blueprint $table): void { $table->increments('id'); $table->string('name'); $table->string('region')->default(''); + $table->boolean('enabled')->default(false); }); $schema->create('cloud_public_ip_pools', static function (Blueprint $table): void { $table->increments('id'); @@ -45,6 +46,7 @@ $schema->create('cloud_public_ip_pools', static function (Blueprint $table): voi $table->integer('address_family'); $table->string('name'); $table->string('cidr'); + $table->string('state')->default('active'); }); $schema->create('user', static function (Blueprint $table): void { $table->increments('id'); @@ -147,7 +149,12 @@ $schema->create('cloud_maintenance_notice_recipients', static function (Blueprin }); Capsule::table('cloud_hosts')->insert([ - 'id' => 1, 'name' => 'HKG-A', 'region' => 'HongKong', + 'id' => 1, 'name' => 'HKG-A', 'region' => 'HongKong', 'enabled' => 1, +]); +Capsule::table('cloud_public_ip_pools')->insert([ + 'id' => 7, 'pool_key' => str_repeat('a', 32), 'host_id' => 1, + 'address_family' => 4, 'name' => 'HKG public v4', + 'cidr' => '192.0.2.0/29', 'state' => 'draining', ]); Capsule::table('user')->insert([ ['id' => 1, 'email' => 'owner@example.com'], @@ -168,6 +175,20 @@ $service = new CloudMaintenanceNoticeService( $audience, static fn (): int => $now ); +$catalog = $service->catalog(); +$assert($catalog['hosts'][0]['enabled'] === true + && $catalog['pools'][0]['state'] === 'draining', + 'The page catalog must retain disabled or draining audience scopes.'); +$assert($service->prefill([ + 'scope_type' => 'public_ip_pool', 'host_id' => 1, + 'pool_key' => str_repeat('a', 32), +], $catalog) === ['scope_type' => 'public_ip_pool', 'scope_id' => 7], + 'A trusted pool shortcut must resolve through the server catalog.'); +$assert($service->prefill([ + 'scope_type' => 'public_ip_pool', 'host_id' => 2, + 'pool_key' => str_repeat('a', 32), +], $catalog) === [], + 'A shortcut cannot resolve a pool under a different host.'); $preview = $service->preview('host', 1); $request = [ 'scope_type' => 'host',