import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import vm from 'node:vm'; const adminSource = await readFile(new URL('../public/cloud/admin-hosts.js', import.meta.url), 'utf8'); const requestRuntimeSource = await readFile( new URL('../public/cloud/admin-request-runtime.js', import.meta.url), 'utf8'); const source = adminSource.slice(adminSource.indexOf('const root =')) .replace('void initialize();', '') + '\nglobalThis.hostUI = { initialize, fillHost, saveHost, renderHostNetworkAttachments, createHostNetworkAttachment, networkAttachmentBody, renderHostNetworkPools, renderNetworkPoolReplacementPanel, networkPoolReplacementRequest, newNetworkPoolBody, syncNewNetworkPoolFamily, state };'; const submit = { preventDefault() {} }; const descendants = node => [node, ...(node?.children || []).flatMap(descendants)]; function fixture(canManage = true) { const elements = new Map(); const selectIds = new Set(['host-country-code', 'host-network-type', 'host-network-attachment-new-line', 'host-network-attachment-new-selector', 'host-network-attachment-new-state', 'host-network-pool-new-attachment', 'host-network-pool-new-state', 'host-network-pool-new-family', 'host-network-pool-new-gateway-on-link']); class Element { constructor(tag = 'input') { this.tag = tag; this.value = ''; this.textContent = ''; this.dataset = {}; this.children = []; this.listeners = new Map(); this.disabled = false; this.lastChild = { textContent: '' }; this.classList = { add() {}, remove() {} }; } get options() { return this.children; } append(...children) { this.children.push(...children); } replaceChildren(...children) { this.children = children; } addEventListener(name, listener) { this.listeners.set(name, listener); } reset() {} querySelectorAll(selector) { return [...elements.values()].filter(node => selector.split(',').includes(node.tag)); } } const get = id => { if (!elements.has(id)) elements.set(id, new Element(selectIds.has(id) ? 'select' : 'input')); return elements.get(id); }; const root = { dataset: { cloudAdmin: 'hosts', canManage: canManage ? '1' : '0' } }; const requests = []; let saved = null; const context = { document: { querySelector: () => root, getElementById: get, createElement: tag => new Element(tag), createTextNode: value => ({ textContent: String(value) }) }, ADMIN_CSRF_TOKEN: 'a'.repeat(64), addEventListener() {}, VenixAdminDangerDialog: { confirm: async () => true }, taskUrl: payload => payload?.task_id && payload?.status_url ? payload.status_url : '', location: { protocol: 'https:', hostname: 'panel.test', assign() {} }, Headers, AbortController, crypto, setTimeout, clearTimeout, Option: class extends Element { constructor(label = '', value = '') { super('option'); this.textContent = label; this.value = String(value); } }, async fetch(path, options) { requests.push({ path, ...options }); let payload; if (path === '/api/v1/session') payload = { admin: true, csrf_token: 'a'.repeat(64) }; else if (path === '/api/v1/admin/user-iso/settings') payload = { enabled: false }; else if (options.method === 'GET') payload = { hosts: saved ? [saved] : [] }; else payload = saved = { id: 7, ...JSON.parse(options.body) }; return { ok: true, status: 200, json: async () => payload }; }, }; context.window = context; vm.runInNewContext(requestRuntimeSource, context, { filename: 'admin-request-runtime.js' }); vm.runInNewContext(source, context, { filename: 'admin-hosts.js' }); return { ...context.hostUI, get, requests, writes: () => requests.filter(request => request.method !== 'GET') }; } { const test = fixture(); await test.initialize(); assert.equal(test.get('host-network-type').value, 'bridge'); assert.equal(test.get('host-network-name').value, 'br0'); assert.equal(test.get('host-network-name').maxLength, 15); assert.ok(new RegExp(`^(?:${test.get('host-network-name').pattern})$`, 'v').test('br-public'), 'Browser pattern must accept hyphens under HTML unicodeSets validation.'); assert.equal(test.get('host-network-warning').hidden, true); await test.saveHost(submit); assert.equal(test.writes()[0].method, 'POST'); assert.equal(test.writes()[0].headers.get('X-Admin-CSRF-Token'), 'a'.repeat(64)); assert.equal(JSON.parse(test.writes()[0].body).default_network, 'bridge:br0'); test.get('host-network-type').value = 'network'; test.get('host-network-type').listeners.get('change')(); assert.equal(test.get('host-network-name').maxLength, 64); assert.ok(new RegExp(`^(?:${test.get('host-network-name').pattern})$`, 'v').test('a'.repeat(64))); test.get('host-network-name').value = 'default'; await test.saveHost(submit); assert.equal(test.writes()[1].path, '/api/v1/admin/hosts/7'); assert.equal(test.writes()[1].method, 'PUT'); assert.equal(JSON.parse(test.writes()[1].body).default_network, 'network:default'); assert.equal(test.get('host-network-type').value, 'network'); assert.equal(test.get('host-network-name').value, 'default'); } { const test = fixture(); for (const old of ['public', '', 'bridge:br0\n', 'bridge:' + 'a'.repeat(16), 'network:' + 'a'.repeat(65)]) { test.fillHost({ id: 7, name: 'Host', default_network: old }); assert.equal(test.get('host-network-type').value, '', `Unsafe value accepted: ${JSON.stringify(old)}`); assert.equal(test.get('host-network-name').value, ''); assert.equal(test.get('host-network-warning').hidden, false); assert.match(test.get('host-network-warning').textContent, /不会自动改为 br0/); test.get('host-region').value = 'Tokyo'; await test.saveHost(submit); } assert.equal(test.writes().length, 0, 'Editing other fields silently converted a legacy network.'); test.get('host-network-type').value = 'bridge'; test.get('host-network-name').value = 'br-public'; await test.saveHost(submit); assert.equal(JSON.parse(test.writes()[0].body).default_network, 'bridge:br-public'); } { const test = fixture(); test.fillHost(null); for (const [type, name] of [['bridge', 'a'.repeat(16)], ['network', 'a'.repeat(65)], ['bridge', '-br0'], ['network', 'bad/name'], ['bridge', 'br 0'], ['other', 'br0']]) { test.get('host-network-type').value = type; test.get('host-network-name').value = name; await test.saveHost(submit); } assert.equal(test.writes().length, 0, 'Invalid network input reached the API.'); for (const [type, name] of [['bridge', 'a'.repeat(15)], ['network', 'a'.repeat(64)]]) { test.get('host-network-type').value = type; test.get('host-network-name').value = name; await test.saveHost(submit); assert.equal(JSON.parse(test.writes().at(-1).body).default_network, `${type}:${name}`); } } { const test = fixture(false); await test.initialize(); assert.equal(test.get('host-network-type').disabled, true); assert.equal(test.get('host-network-name').disabled, true); await test.saveHost(submit); assert.equal(test.writes().length, 0, 'Read-only administrator sent host configuration.'); } { const test = fixture(); test.state.hosts = [{ id: 7, default_network: 'bridge:br0' }]; test.state.networkPoolHostId = '7'; test.get('host-network-pools-drawer').open = true; test.renderHostNetworkPools({ host: { id: 7 }, attachments: [], items: [] }, 7, 0); const summary = test.get('host-network-pools-summary').children; assert.equal(summary[0].textContent, '兼容默认网络(旧入口)'); assert.equal(summary[1].textContent, 'Linux 网桥 · br0'); } { const test = fixture(); test.state.hosts = [{ id: 7, default_network: 'bridge:br0' }]; test.state.networkAttachmentHostId = '7'; test.get('host-network-attachments-drawer').open = true; const selector = 'bridge:br-public'; test.renderHostNetworkAttachments({ host: { id: 7, name: 'Host' }, agent: { revision: 4, tested_revision: 4, network_selectors: [selector] }, lines: [{ id: 3, name: 'China optimized', status: 'active' }], maximum: 64, items: [{ attachment_key: 'b'.repeat(32), name: 'Public uplink', line_id: 3, line_name: 'China optimized', network_selector: selector, state: 'active', priority: 10, config_revision: 2, verified_agent_revision: 4, verification_state: 'verified', ready: true, last_verified_at: 1, verification_error_code: '', }], }, 7, 0); assert.deepEqual(Array.from(test.get('host-network-attachment-new-selector').options, option => option.value), ['', selector]); assert.match(test.get('host-network-attachments-summary').children[0].textContent, /兼容默认网络/); const body = test.networkAttachmentBody({ dataset: { requestKey: 'c'.repeat(32) }, elements: { namedItem: name => ({ value: ({ name: 'Public uplink', line_id: '3', network_selector: selector, state: 'active', priority: '10' })[name] }) }, }, true); assert.equal(body.line_id, 3); assert.equal(body.network_selector, selector); assert.equal(body.request_key, 'c'.repeat(32)); } { const test = fixture(false); test.state.networkAttachmentHostId = '7'; await test.createHostNetworkAttachment({ preventDefault() {}, currentTarget: test.get('host-network-attachment-create-form') }); assert.equal(test.writes().length, 0, 'Read-only administrator sent a network attachment mutation.'); } { const test = fixture(); test.state.hosts = [{ id: 7, default_network: 'bridge:br0' }]; test.state.networkPoolHostId = '7'; test.get('host-network-pools-drawer').open = true; test.renderHostNetworkPools({ host: { id: 7, name: 'Host' }, attachments: [{ id: 11, name: 'Public uplink', line_id: 3, line_name: 'China optimized', network_selector: 'bridge:br-public', state: 'active', verification_state: 'verified', ready: true }], maximum: 32, items: [{ pool_key: 'a'.repeat(32), name: 'Public pool', cidr: '8.8.8.0/29', network_attachment_id: 11, attachment: { id: 11, name: 'Public uplink', line_id: 3, line_name: 'China optimized', network_selector: 'bridge:br-public', state: 'active', verification_state: 'verified', ready: true }, gateway: '8.8.8.1', guest_prefix_length: 29, address_family: 4, gateway_on_link: false, allocation_start: null, allocation_end: null, max_allocations: 0, dns_servers: ['1.1.1.1'], reserved_ips: [], state: 'active', revision: 1, expected_revision: 1, live_revision: 1, sync_message: '已应用', occupied_count: 1, }], }, 7, 0); const nodes = descendants(test.get('host-network-pools-list')); const control = name => nodes.find(node => node.name === name); for (const name of ['network_attachment_id', 'cidr', 'gateway', 'guest_prefix_length', 'dns_servers']) { assert.equal(control(name)?.disabled, true, `${name} remained editable on an occupied pool.`); } assert.equal(control('reserved_ips')?.disabled, false, 'The disabled-IP list remained locked merely because another IP is occupied.'); assert.equal(control('name')?.disabled, false); assert.equal(control('state')?.disabled, false); assert.ok(nodes.some(node => /未占用的保留 \/ 禁用 IP/.test(node.textContent)), 'The occupied-pool warning did not explain the per-address safety rule.'); } { const test = fixture(); const get = test.get; get('host-network-pool-new-family').value = '4'; get('host-network-pool-new-gateway-on-link').value = '1'; test.syncNewNetworkPoolFamily(); assert.equal(get('host-network-pool-new-gateway-on-link').value, '0'); assert.equal(get('host-network-pool-new-gateway-on-link').disabled, true, 'IPv4 create mode exposed the unsupported on-link control.'); get('host-network-pool-new-attachment').value = '11'; get('host-network-pool-new-family').value = '6'; test.syncNewNetworkPoolFamily(); assert.equal(get('host-network-pool-new-gateway-on-link').disabled, false, 'IPv6 create mode did not enable on-link selection.'); get('host-network-pool-new-name').value = 'Public IPv6'; get('host-network-pool-new-cidr').value = '2404:c140:156:3a::/64'; get('host-network-pool-new-gateway').value = '2404:c140:156::1'; get('host-network-pool-new-gateway-on-link').value = '1'; get('host-network-pool-new-dns').value = '2606:4700:4700::1111'; get('host-network-pool-new-reserved').value = '2404:c140:156:3a::2'; get('host-network-pool-new-allocation-start').value = '2404:c140:156:3a::1000'; get('host-network-pool-new-allocation-end').value = '2404:c140:156:3a::1fff'; get('host-network-pool-new-max-allocations').value = '100'; get('host-network-pool-new-prefix').value = '64'; get('host-network-pool-new-state').value = 'active'; const form = get('host-network-pool-create-form'); form.dataset.requestKey = 'f'.repeat(32); const body = test.newNetworkPoolBody(form); assert.equal(body.address_family, 6); assert.equal(body.gateway_on_link, true); assert.equal(body.max_allocations, 100); assert.equal(body.allocation_start, '2404:c140:156:3a::1000'); } { const test = fixture(false); test.get('host-network-pool-new-family').value = '6'; test.syncNewNetworkPoolFamily(); assert.equal(test.get('host-network-pool-new-gateway-on-link').disabled, true, 'Read-only IPv6 create mode enabled the on-link control.'); } for (const [family, enabled] of [[4, false], [6, true]]) { const test = fixture(); test.state.hosts = [{ id: 7, default_network: 'bridge:br0' }]; test.state.networkPoolHostId = '7'; test.get('host-network-pools-drawer').open = true; test.renderHostNetworkPools({ host: { id: 7, name: 'Host' }, attachments: [{ id: 11, name: 'Public uplink', line_id: 3, line_name: 'International', network_selector: 'bridge:br-public', state: 'active', verification_state: 'verified', ready: true }], maximum: 32, items: [{ pool_key: String(family).repeat(32), name: `Public IPv${family}`, cidr: family === 4 ? '8.8.8.0/29' : '2404:c140:156:3a::/64', network_attachment_id: 11, attachment: { id: 11, name: 'Public uplink', line_id: 3, line_name: 'International', network_selector: 'bridge:br-public', state: 'active', verification_state: 'verified', ready: true }, gateway: family === 4 ? '8.8.8.1' : '2404:c140:156::1', guest_prefix_length: family === 4 ? 29 : 64, address_family: family, gateway_on_link: family === 6, allocation_start: family === 6 ? '2404:c140:156:3a::1000' : null, allocation_end: family === 6 ? '2404:c140:156:3a::1fff' : null, max_allocations: family === 6 ? 100 : 0, dns_servers: [family === 4 ? '1.1.1.1' : '2606:4700:4700::1111'], reserved_ips: [], state: 'active', revision: 1, expected_revision: 1, live_revision: 1, sync_message: '已应用', occupied_count: 0, }], }, 7, 0); const gatewayOnLink = descendants(test.get('host-network-pools-list')) .find(node => node.name === 'gateway_on_link'); assert.equal(gatewayOnLink?.disabled, !enabled, `IPv${family} edit mode exposed the wrong on-link state.`); if (family === 4) assert.equal(gatewayOnLink?.value, '0'); } { const test = fixture(); const sourceKey = 'a'.repeat(32); const targetKey = 'b'.repeat(32); const panel = test.get('replacement-panel'); panel.dataset.poolReplacementPanel = sourceKey; const payload = { can_start: true, source_pool: { pool_key: sourceKey, name: 'Old pool', expected_revision: 4, line: { name: 'International' }, network_selector: 'bridge:br-old', assigned_instance_count: 3, }, target_options: [{ pool_key: targetKey, name: 'New pool', expected_revision: 7, network_selector: 'bridge:br-new', available_count: 8, }], active_batch: null, history: [], }; test.renderNetworkPoolReplacementPanel(panel, payload, '7', payload.source_pool); const nodes = descendants(panel); const target = nodes.find(node => node.tag === 'select'); const confirm = nodes.find(node => node.tag === 'input' && node.type === 'checkbox'); assert.equal(target.children[1].value, targetKey); target.value = targetKey; confirm.checked = true; const body = test.networkPoolReplacementRequest(payload, target, true, panel); assert.equal(body.target_pool_key, targetKey); assert.equal(body.expected_source_revision, 4); assert.equal(body.expected_target_revision, 7); assert.equal(body.confirm_replacement, true); assert.match(body.request_key, /^[0-9a-f]{32}$/); } { const test = fixture(); const panel = test.get('replacement-attention-panel'); const sourceKey = 'c'.repeat(32); test.renderNetworkPoolReplacementPanel(panel, { source_pool: { pool_key: sourceKey, expected_revision: 2 }, target_options: [{ pool_key: 'd'.repeat(32), expected_revision: 3 }], active_batch: { batch_key: 'e'.repeat(32), parent_job_id: 91, state: 'unknown', counts: { total: 4, queued: 1, running: 2, succeeded: 0, failed: 0, unknown: 1 }, items: [{ instance_id: '17', child_job_id: '92', state: 'unknown' }], job_url: '/admin/operations?q=91', }, history: [], }, '7', { pool_key: sourceKey }); const labels = descendants(panel).map(node => node.textContent).filter(Boolean); assert.ok(labels.includes('效果未知')); assert.ok(labels.includes('查看任务中心')); assert.ok(labels.some(label => /实例进度 1 \/ 4 · 等待 1 · 执行 2/.test(label)), 'Batch display ignored the durable count projection.'); const links = descendants(panel).filter(node => node.tag === 'a'); const childRecovery = links.find(node => node.textContent === '核对子任务 #92'); assert.equal(childRecovery?.href, '/admin/operations?q=92', 'An effect-unknown child remained unreachable from the replacement batch.'); assert.ok(labels.some(label => /按上方子任务编号逐项核对/.test(label)), 'The blocked-batch guidance still pointed administrators at the local parent task.'); const buttons = descendants(panel).filter(node => node.tag === 'button'); assert.equal(buttons.some(node => /重试/.test(node.textContent)), false, 'An effect-unknown pool replacement exposed a retry action.'); } { const test = fixture(false); test.state.hosts = [{ id: 7, default_network: 'bridge:br0' }]; test.state.networkPoolHostId = '7'; test.get('host-network-pools-drawer').open = true; test.renderHostNetworkPools({ host: { id: 7, name: 'Host' }, attachments: [{ id: 11, name: 'Public uplink', line_id: 3, line_name: 'International', network_selector: 'bridge:br-public', state: 'active', verification_state: 'verified', ready: true }], maximum: 32, items: [{ pool_key: 'f'.repeat(32), name: 'Retired pool', cidr: '203.0.113.0/29', network_attachment_id: 11, attachment: { id: 11, name: 'Public uplink', line_id: 3, line_name: 'International', network_selector: 'bridge:br-public', state: 'active', verification_state: 'verified', ready: true }, gateway: '203.0.113.1', guest_prefix_length: 29, address_family: 6, gateway_on_link: true, allocation_start: '2404:c140:156:3a::1000', allocation_end: '2404:c140:156:3a::1fff', max_allocations: 100, dns_servers: ['1.1.1.1'], reserved_ips: [], state: 'disabled', revision: 5, expected_revision: 5, live_revision: 5, sync_message: '已应用', occupied_count: 0, replacement_history_count: 2, has_replacement_history: true, active_replacement: null, }], }, 7, 0); const buttons = descendants(test.get('host-network-pools-list')) .filter(node => node.tag === 'button'); const gatewayOnLink = descendants(test.get('host-network-pools-list')) .find(node => node.name === 'gateway_on_link'); assert.equal(gatewayOnLink?.disabled, true, 'Read-only IPv6 edit mode enabled the on-link control.'); const history = buttons.find(node => node.textContent === '查看换池记录'); assert.ok(history && history.hidden !== true, 'A completed replacement history became unreachable after source occupancy reached zero.'); assert.equal(history.disabled, false, 'A read-only administrator could not open completed replacement history.'); } console.log('Host network defaults, attachments, canonical writes, legacy blocking, read-only controls, pool binding and occupied-pool safety passed.');