import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import vm from 'node:vm'; const source = await readFile(new URL('../public/cloud/admin-operations.js', import.meta.url), 'utf8'); class Node { constructor(tag = 'div') { this.tagName = tag.toUpperCase(); this.children = []; this.dataset = {}; this.parentNode = null; this.attributes = new Map(); this.listeners = new Map(); this.hidden = false; this.disabled = false; this.isConnected = true; this.open = false; this.value = ''; this._text = ''; this.style = { setProperty() {}, removeProperty() {} }; const classes = new Set(); this.classList = { add: value => classes.add(value), remove: value => classes.delete(value), contains: value => classes.has(value) }; } set textContent(value) { this.replaceChildren(); this._text = String(value); } get textContent() { return this._text + this.children.map(child => child.textContent).join(''); } set innerHTML(_) { throw new Error('Task content must never be interpreted as HTML.'); } get options() { return this.children; } append(...children) { for (const child of children) { if (child.parentNode) child.parentNode.children = child.parentNode.children.filter(node => node !== child); child.parentNode = this; child.isConnected = this.isConnected; this.children.push(child); } } add(option) { this.append(option); } replaceChildren(...children) { this._text = ''; for (const child of this.children) { child.parentNode = null; child.isConnected = false; } this.children = []; this.append(...children); } setAttribute(key, value) { this.attributes.set(key, String(value)); } getAttribute(key) { return this.attributes.get(key) ?? null; } addEventListener(name, listener) { const listeners = this.listeners.get(name) || []; listeners.push(listener); this.listeners.set(name, listeners); } dispatch(name, fields = {}) { const event = { target: this, currentTarget: this, button: 0, defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, ...fields }; for (const listener of this.listeners.get(name) || []) listener(event); } closest(selector) { if (selector === '[data-operation-cancel]' && this.dataset.operationCancel) return this; if (selector === '[data-operation-detail]' && this.dataset.operationDetail) return this; if (selector === 'a[href]' && this.tagName === 'A' && this.getAttribute('href')) return this; return null; } querySelector(selector) { if (selector.startsWith('[data-operation-cancel="')) { const id = selector.slice(24, -2); return this.walk().find(node => node.dataset.operationCancel === id) || null; } return null; } walk() { return [this, ...this.children.flatMap(child => child.walk())]; } focus() {} getBoundingClientRect() { return { left: 0, right: 500, top: 0, bottom: 800 }; } showModal() { this.open = true; } close() { this.open = false; } } class SelectNode extends Node {} class OptionNode extends Node { constructor(label, value) { super('option'); this.textContent = label; this.value = String(value); } } const flush = async () => { for (let turn = 0; turn < 20; turn += 1) await Promise.resolve(); }; function job(id, changes = {}) { return { id: String(id), operation_id: 'a'.repeat(32), kind: 'snapshot_delete', status: 'uncertain', can_cancel: true, cancel_reason: '将停止后续重试,已派发操作仍需核查', attempts: 4, error: '等待核对结果', phase: '正在删除快照', host_id: '7', host_name: '测试宿主机', region: 'test', actor_id: '1', actor_name: '管理员', actor_email: 'a***@example.test', owner_id: '2', owner_name: '用户', owner_email: 'u***@example.test', instance_id: '9', instance_name: 'vm-test', instance_uuid: '11111111-1111-4111-8111-111111111111', instance_status: 'deleting', order_id: null, created_at: 1000, updated_at: 1010, dispatched_at: 1001, available_at: 1000, lease_until: 0, attention: true, attention_reason: 'uncertain', links: { instance: null, billing: null }, display: { kind: '删除快照', status: '待核对', attention: '等待结果核对', lease: '无执行租约' }, ...changes, }; } function page(items = [job(41)]) { return { items, pagination: { page: 1, per_page: 20, total: items.length, total_pages: 1, from: items.length ? 1 : 0, to: items.length }, summary: { total: items.length, attention: items.length, failed: 0, uncertain: items.length, queued_delayed: 0, lease_expired: 0 }, filters: { status: 'attention', kind: '', host_id: null, q: '', page: 1, per_page: 20 }, hosts: [{ id: '7', name: '测试宿主机', region: 'test' }], kinds: [{ value: 'snapshot_delete', label: '删除快照' }], generated_at: 1000, }; } function fixture(canManage) { const ids = [ 'admin-operations-bootstrap', 'operation-detail', 'operation-detail-body', 'operation-detail-cancel', 'operation-detail-close', 'operation-detail-links', 'operation-detail-state', 'operation-detail-title', 'operations-body', 'operations-count', 'operations-health-body', 'operations-health-refresh', 'operations-health-state', 'operations-host', 'operations-kind', 'operations-next', 'operations-notice', 'operations-page-label', 'operations-pagination', 'operations-previous', 'operations-refresh', 'operations-reset', 'operations-shown-filters', 'operations-filter', 'operations-summary-total', 'operations-summary-failed', 'operations-summary-uncertain', 'operations-summary-delayed', ]; const nodes = Object.fromEntries(ids.map(id => [id, id === 'operations-filter' ? new Node('form') : new Node(id === 'operation-detail' ? 'dialog' : 'div')])); nodes['operation-detail-cancel'].hidden = true; // Match the live template: the stable cancel button is a sibling of the // replaceable link area, so an actual DOM lookup survives each rerender. const detailFooter = new Node('footer'); detailFooter.append(nodes['operation-detail-cancel'], nodes['operation-detail-links']); nodes['admin-operations-bootstrap'].textContent = JSON.stringify(page()); nodes['operations-filter'].elements = { namedItem: key => { const map = { q: new Node('input'), status: new SelectNode('select'), kind: nodes['operations-kind'], host_id: nodes['operations-host'], per_page: new SelectNode('select') }; map.status.value = 'attention'; map.per_page.value = '20'; return map[key]; } }; const root = new Node('main'); root.dataset.canManage = canManage ? '1' : '0'; const document = new Node(); document.hidden = true; document.visibilityState = 'hidden'; document.documentElement = new Node(); document.body = new Node(); document.getElementById = id => nodes[id]?.isConnected ? nodes[id] : null; document.createElement = tag => tag === 'select' ? new SelectNode(tag) : new Node(tag); document.querySelector = selector => selector === '[data-admin-operations]' ? root : null; const window = new Node(); window.ADMIN_CSRF_TOKEN = 'csrf-test-token'; window.scrollX = 0; window.scrollY = 0; window.confirm = () => true; window.VenixDrawerMotion = { openDrawerWithMotion(dialog) { dialog.open = true; }, closeDrawerWithMotion(dialog) { dialog.open = false; return Promise.resolve(true); } }; const location = { origin: 'https://example.test', href: 'https://example.test/admin/operations' }; const history = { state: null, pushState(value, _, url) { this.state = value; location.href = String(url); }, replaceState(value) { this.state = value; } }; const requests = []; const fetch = (url, options) => new Promise((resolve, reject) => requests.push({ url: String(url), options, resolve, reject, settled: false })); vm.runInNewContext(source, { document, window, location, history, URL, Node, HTMLSelectElement: SelectNode, Option: OptionNode, AbortController, fetch, setTimeout: () => 1, clearTimeout() {}, requestAnimationFrame: callback => callback(), console }, { filename: 'admin-operations.js' }); return { nodes, root, requests, window, async click(target) { if (target.dataset.operationCancel || target.dataset.operationDetail) root.dispatch('click', { target }); else target.dispatch('click', { target }); await flush(); }, async respond(payload, request = requests.find(item => !item.settled), status = 200) { assert.ok(request, 'A response requires an outstanding request.'); request.settled = true; request.resolve({ status, ok: status >= 200 && status < 300, json: async () => payload }); await flush(); }, }; } function findButton(test, attribute, value) { return test.nodes['operations-body'].walk().find(node => node.dataset[attribute] === String(value)) || null; } // Read-only administrators do not receive the mutation control. { const test = fixture(false); await test.click(test.nodes['operations-refresh']); await test.respond(page()); assert.equal(findButton(test, 'operationCancel', 41), null); assert.equal(test.nodes['operation-detail-cancel'].hidden, true); const detail = findButton(test, 'operationDetail', 41); await test.click(detail); await test.respond({ job: job(41), notes: [] }); assert.equal(test.nodes['operation-detail-cancel'].hidden, true, 'A forged can_cancel field does not override the page role boundary.'); } // Confirmation rejection is side-effect free; a confirmed action carries CSRF // and refreshes the row into a terminal state. { const test = fixture(true); await test.click(test.nodes['operations-refresh']); await test.respond(page()); const cancel = findButton(test, 'operationCancel', 41); assert.ok(cancel); test.window.confirm = () => false; await test.click(cancel); assert.equal(test.requests.some(request => request.options.method === 'POST'), false); test.window.confirm = () => true; await test.click(cancel); const mutation = test.requests.find(request => request.options.method === 'POST'); assert.ok(mutation); assert.equal(mutation.url, '/api/v1/admin/operations/jobs/41/cancel'); assert.equal(mutation.options.headers['X-CSRF-Token'], 'csrf-test-token'); assert.equal(mutation.options.headers['Content-Type'], 'application/json'); assert.equal(mutation.options.body, '{}'); await test.respond({ job: job(41, { status: 'cancelled', can_cancel: false, error: '管理员已中止后续重试' }), notes: [] }, mutation); const refresh = test.requests.find(request => !request.settled && request.options.method === 'GET'); assert.ok(refresh); await test.respond(page([job(41, { status: 'cancelled', can_cancel: false, error: '管理员已中止后续重试' })]), refresh); assert.equal(findButton(test, 'operationCancel', 41), null); } // Opening and rendering a detail keeps the cancellation button usable after // links are rebuilt; the button is not detached and looked up as null. { const test = fixture(true); await test.click(test.nodes['operations-refresh']); await test.respond(page()); const detail = findButton(test, 'operationDetail', 41); assert.ok(detail); await test.click(detail); const detailRequest = test.requests.find(request => request.url.endsWith('/api/v1/admin/operations/jobs/41')); assert.ok(detailRequest); await test.respond({ job: job(41), notes: [] }, detailRequest); assert.equal(test.nodes['operation-detail-cancel'].hidden, false); const stableButton = test.nodes['operation-detail-cancel']; await test.click(detail); const rerenderRequest = test.requests.find(request => !request.settled && request.url.endsWith('/api/v1/admin/operations/jobs/41')); await test.respond({ job: job(41, { phase: '核对重试中' }), notes: [] }, rerenderRequest); assert.equal(test.nodes['operation-detail-cancel'], stableButton); assert.equal(stableButton.isConnected, true); assert.equal(stableButton.hidden, false); await test.click(stableButton); const mutation = test.requests.find(request => request.options.method === 'POST'); assert.ok(mutation); await test.respond({ job: job(41, { status: 'cancelled', can_cancel: false }), notes: [] }, mutation); assert.equal(stableButton.hidden, true, 'The confirmed terminal result immediately removes the detail control.'); const refresh = test.requests.find(request => !request.settled && request.url === '/api/v1/admin/operations'); assert.ok(refresh); await test.respond(page([job(41, { status: 'cancelled', can_cancel: false })]), refresh); const terminalDetail = test.requests.find(request => !request.settled && request.url.endsWith('/api/v1/admin/operations/jobs/41')); assert.ok(terminalDetail); await test.respond({ job: job(41, { status: 'cancelled', can_cancel: false }), notes: [] }, terminalDetail); assert.equal(stableButton.hidden, true); } // Rejected HTTP responses preserve the server's controlled detail instead of // turning a CSRF or authorization error into an unrelated generic message. { const test = fixture(true); await test.click(test.nodes['operations-refresh']); await test.respond(page()); await test.click(findButton(test, 'operationCancel', 41)); const mutation = test.requests.find(request => request.options.method === 'POST'); await test.respond({ detail: 'CSRF 校验失败,请刷新页面' }, mutation, 403); assert.match(test.nodes['operations-notice'].textContent, /CSRF 校验失败/); assert.ok(findButton(test, 'operationCancel', 41), 'A rejected cancellation does not invent terminal state.'); } // A missing management token cannot send an outbound mutation at all. { const test = fixture(true); await test.click(test.nodes['operations-refresh']); await test.respond(page()); test.window.ADMIN_CSRF_TOKEN = ''; await test.click(findButton(test, 'operationCancel', 41)); assert.equal(test.requests.some(request => request.options.method === 'POST'), false); assert.match(test.nodes['operations-notice'].textContent, /安全令牌缺失/); } console.log('Admin operations cancellation UI permissions, confirmation, CSRF POST, refresh and detail rerender passed.');