From ff1ca4e558265c2e0a1eadc9b8e89d01c8e25659 Mon Sep 17 00:00:00 2001 From: codex Date: Sat, 31 Oct 2026 07:49:33 +0800 Subject: [PATCH] refactor(admin): unify action safety runtime --- web/public/cloud/admin-danger-dialog.js | 179 +++++++++++++ web/public/cloud/admin-instance-backups.js | 60 ++--- web/public/cloud/admin-instance-migration.js | 19 +- web/public/cloud/admin-instance-transport.js | 98 ++------ web/public/cloud/admin-instances.js | 3 +- web/public/cloud/admin-object-storage.css | 84 ------- web/public/cloud/admin-object-storage.js | 81 ++---- web/public/cloud/admin-operations.js | 82 +++--- web/public/cloud/admin-request-runtime.js | 168 +++++++++++++ web/public/cloud/admin-resources.js | 37 +-- web/public/cloud/admin-vpc.js | 34 +-- web/public/cloud/admin.js | 80 ++++-- web/public/cloud/agent-settings.js | 19 +- web/public/theme/venix/css/admin-home.css | 187 ++++++++++++++ .../venix/admin/components/danger_dialog.tpl | 22 ++ .../views/venix/admin/object_storage.tpl | 12 - .../views/venix/admin/static_footer.tpl | 2 + .../views/venix/admin/static_header.tpl | 1 + web/resources/views/venix/layout_assets.tpl | 2 +- web/tests/AdminAcceptedTaskBehaviorTest.mjs | 9 +- web/tests/AdminActionRuntimeContractTest.php | 79 ++++++ web/tests/AdminDangerDialogBehaviorTest.mjs | 235 ++++++++++++++++++ web/tests/AdminHostNetworkBehaviorTest.mjs | 19 +- .../AdminOperationsCancelBehaviorTest.mjs | 4 +- web/tests/AdminRequestRuntimeBehaviorTest.mjs | 165 ++++++++++++ .../AdminResourceSchedulingContractTest.php | 3 +- ...AdminTemplateStartupScriptBehaviorTest.mjs | 14 +- web/tests/CloudAgentPanelContractTest.php | 2 +- .../CloudObjectStorageAdminContractTest.php | 8 +- .../CloudObjectStorageSubmitBehaviorTest.mjs | 16 +- web/tests/CloudObjectStorageViewTest.php | 9 +- ...CloudPortableBackupAdminUiContractTest.php | 3 +- web/tests/CloudTaskObserverBehaviorTest.mjs | 12 +- 33 files changed, 1313 insertions(+), 435 deletions(-) create mode 100644 web/public/cloud/admin-danger-dialog.js create mode 100644 web/public/cloud/admin-request-runtime.js create mode 100644 web/resources/views/venix/admin/components/danger_dialog.tpl create mode 100644 web/tests/AdminActionRuntimeContractTest.php create mode 100644 web/tests/AdminDangerDialogBehaviorTest.mjs create mode 100644 web/tests/AdminRequestRuntimeBehaviorTest.mjs diff --git a/web/public/cloud/admin-danger-dialog.js b/web/public/cloud/admin-danger-dialog.js new file mode 100644 index 00000000..b95d97ff --- /dev/null +++ b/web/public/cloud/admin-danger-dialog.js @@ -0,0 +1,179 @@ +(function (global) { + 'use strict'; + + var activeRequest = null; + var fallbackMode = false; + var ignoredCloseEvents = 0; + + function byId(id) { return global.document ? global.document.getElementById(id) : null; } + function value(input, fallback) { + return input === null || input === undefined || String(input).trim() === '' + ? fallback : String(input); + } + function safeTone(input) { return input === 'warning' ? 'warning' : 'danger'; } + + function elements() { + var dialog = byId('admin-danger-dialog'); + var form = byId('admin-danger-dialog-form'); + var result = { + dialog: dialog, + form: form, + title: byId('admin-danger-dialog-title'), + message: byId('admin-danger-dialog-message'), + kicker: dialog ? dialog.querySelector('.admin-danger-dialog-kicker') : null, + mark: dialog ? dialog.querySelector('.admin-danger-dialog-mark') : null, + close: byId('admin-danger-dialog-close'), + cancel: byId('admin-danger-dialog-cancel'), + confirm: byId('admin-danger-dialog-confirm'), + verification: byId('admin-danger-dialog-verification'), + verificationInput: byId('admin-danger-dialog-verification-input'), + verificationLabel: byId('admin-danger-dialog-verification-label'), + verificationHint: byId('admin-danger-dialog-verification-hint'), + }; + result.ready = Object.keys(result).every(function (key) { + return key === 'ready' || result[key]; + }); + return result; + } + + function matchesRequiredText(nodes) { + return activeRequest && activeRequest.requiredText !== null + && nodes.verificationInput.value === activeRequest.requiredText; + } + + function updateVerification(nodes) { + if (!activeRequest || activeRequest.requiredText === null) { + nodes.confirm.disabled = false; + nodes.verificationInput.removeAttribute('aria-invalid'); + nodes.verification.classList.remove('is-matched'); + nodes.verificationHint.classList.remove('is-mismatch'); + nodes.verificationHint.textContent = ''; + return; + } + var matched = matchesRequiredText(nodes); + var hasValue = nodes.verificationInput.value.length > 0; + nodes.confirm.disabled = !matched; + nodes.verificationInput.setAttribute('aria-invalid', hasValue && !matched ? 'true' : 'false'); + nodes.verification.classList.toggle('is-matched', matched); + nodes.verificationHint.classList.toggle('is-mismatch', hasValue && !matched); + nodes.verificationHint.textContent = matched ? '名称已匹配,可以继续。' + : (hasValue ? '名称不匹配,请完整输入:' : '请输入:') + activeRequest.requiredText; + } + + function restoreFocus(node) { + if (!node || typeof node.focus !== 'function' || node.isConnected === false) return; + try { node.focus({ preventScroll: true }); } catch (error) { node.focus(); } + } + + function closeDialog(nodes) { + global.document.documentElement.classList.remove('admin-danger-dialog-open'); + nodes.dialog.classList.remove('is-dialog-fallback'); + if (nodes.dialog.open && typeof nodes.dialog.close === 'function') { + ignoredCloseEvents += 1; + nodes.dialog.close(); + } else { + nodes.dialog.removeAttribute('open'); + } + fallbackMode = false; + } + + function settle(nodes, confirmed) { + if (!activeRequest) return; + var request = activeRequest; + activeRequest = null; + closeDialog(nodes); + nodes.verificationInput.value = ''; + restoreFocus(request.opener); + request.resolve(confirmed === true); + } + + function focusableControls(nodes) { + return [nodes.close, nodes.verification.hidden ? null : nodes.verificationInput, + nodes.cancel, nodes.confirm].filter(function (control) { + return control && !control.disabled && !control.hidden; + }); + } + + function ensureListeners(nodes) { + if (nodes.dialog.dataset.adminDangerReady === '1') return; + nodes.dialog.dataset.adminDangerReady = '1'; + nodes.close.addEventListener('click', function () { settle(nodes, false); }); + nodes.cancel.addEventListener('click', function () { settle(nodes, false); }); + nodes.verificationInput.addEventListener('input', function () { updateVerification(nodes); }); + nodes.form.addEventListener('submit', function (event) { + event.preventDefault(); + if (activeRequest && activeRequest.requiredText !== null && !matchesRequiredText(nodes)) return; + settle(nodes, true); + }); + nodes.dialog.addEventListener('cancel', function (event) { + event.preventDefault(); + settle(nodes, false); + }); + nodes.dialog.addEventListener('close', function () { + if (ignoredCloseEvents > 0) { ignoredCloseEvents -= 1; return; } + settle(nodes, false); + }); + nodes.dialog.addEventListener('click', function (event) { + if (event.target === nodes.dialog) settle(nodes, false); + }); + nodes.dialog.addEventListener('keydown', function (event) { + if (event.key === 'Escape') { + event.preventDefault(); + settle(nodes, false); + return; + } + if (!fallbackMode || event.key !== 'Tab') return; + var controls = focusableControls(nodes); + if (!controls.length) return; + var first = controls[0]; + var last = controls[controls.length - 1]; + if (event.shiftKey && global.document.activeElement === first) { + event.preventDefault(); last.focus(); + } else if (!event.shiftKey && global.document.activeElement === last) { + event.preventDefault(); first.focus(); + } + }); + } + + function confirmAction(options) { + var nodes = elements(); + if (!nodes.ready || activeRequest) return Promise.resolve(false); + ensureListeners(nodes); + var config = options && typeof options === 'object' ? options : {}; + var requiredText = typeof config.requiredText === 'string' && config.requiredText.length > 0 + ? config.requiredText : null; + var tone = safeTone(config.tone); + return new Promise(function (resolve) { + activeRequest = { + opener: global.document.activeElement, + requiredText: requiredText, + resolve: resolve, + }; + nodes.dialog.dataset.tone = tone; + nodes.kicker.textContent = tone === 'warning' ? '操作确认' : '高风险操作'; + nodes.title.textContent = value(config.title, '确认操作'); + nodes.message.textContent = value(config.message, '请确认是否继续。'); + nodes.cancel.textContent = value(config.cancelText, '取消'); + nodes.confirm.textContent = value(config.confirmText, '确认'); + nodes.confirm.className = tone === 'warning' ? 'btn btn-warning' : 'btn btn-danger'; + nodes.verification.hidden = requiredText === null; + nodes.verificationInput.value = ''; + nodes.verificationLabel.textContent = value(config.requiredLabel, '输入完整名称以确认'); + if (requiredText === null) nodes.verificationInput.removeAttribute('required'); + else nodes.verificationInput.setAttribute('required', 'required'); + nodes.verificationInput.setAttribute('aria-required', requiredText === null ? 'false' : 'true'); + updateVerification(nodes); + global.document.documentElement.classList.add('admin-danger-dialog-open'); + if (typeof nodes.dialog.showModal === 'function') nodes.dialog.showModal(); + else { + fallbackMode = true; + nodes.dialog.classList.add('is-dialog-fallback'); + nodes.dialog.setAttribute('open', 'open'); + } + if (requiredText !== null) nodes.verificationInput.focus(); + else nodes.cancel.focus(); + }); + } + + global.VenixAdminDangerDialog = Object.freeze({ confirm: confirmAction }); +}(typeof window !== 'undefined' ? window : globalThis)); diff --git a/web/public/cloud/admin-instance-backups.js b/web/public/cloud/admin-instance-backups.js index 748fb95a..95ba27ae 100644 --- a/web/public/cloud/admin-instance-backups.js +++ b/web/public/cloud/admin-instance-backups.js @@ -63,6 +63,7 @@ export function createAdminInstanceBackups({ byId, read, mutate, + mutateJson, createMigration, announceTaskAccepted, observeTask, @@ -72,7 +73,8 @@ export function createAdminInstanceBackups({ onNotice, } = {}) { if (typeof byId !== 'function' || typeof read !== 'function' - || typeof mutate !== 'function' || typeof createMigration !== 'function') { + || typeof mutate !== 'function' || typeof mutateJson !== 'function' + || typeof createMigration !== 'function') { throw new TypeError('Instance backup dependencies are incomplete'); } const state = { @@ -184,45 +186,17 @@ export function createAdminInstanceBackups({ }); async function deleteObject(vmId, backup, controller, library = false) { - if (location.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) { - throw new Error('请通过 HTTPS 删除备份。'); - } - const timeout = setTimeout(() => controller.abort('timeout'), 30000); - try { - const response = await fetch(mutationUrl(vmId, backup.id, '', library), { - method: 'DELETE', - headers: { - Accept: 'application/json', 'X-CSRF-Token': window.ADMIN_CSRF_TOKEN || '', - 'Idempotency-Key': globalThis.crypto?.randomUUID?.() - || `admin-${Date.now()}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`, - }, - credentials: 'same-origin', cache: 'no-store', signal: controller.signal, - }); - if (response.status === 401) throw new Error('登录已过期,请重新登录。'); - let payload; - try { payload = await response.json(); } - catch { throw new Error('服务返回异常,请检查服务器日志后重试。'); } - if (!response.ok || payload?.ret === 0) { - const error = new Error(typeof payload?.detail === 'string' - ? payload.detail : (payload?.message || `请求失败 (${response.status})`)); - error.status = response.status; throw error; - } - if (payload?.deleted !== true && payload?.requires_reconciliation !== true - && payload?.requires_attention !== true) { - const error = new Error('删除回执状态无效,请勿重复删除,先刷新核对。'); - error.mutationMayHaveApplied = true; throw error; - } - return payload; - } catch (error) { - if (controller.signal.reason === 'timeout') { - const timeoutError = new Error('删除请求超时,结果无法确认。请刷新后使用“核对删除状态”,不要重复删除。'); - timeoutError.mutationMayHaveApplied = true; throw timeoutError; - } - if (error?.status >= 500 || (!error?.status && error?.name !== 'AbortError')) { - error.mutationMayHaveApplied = true; - } + const payload = await mutateJson( + mutationUrl(vmId, backup.id, '', library), undefined, controller, 'DELETE', + ); + if (payload?.deleted !== true && payload?.requires_reconciliation !== true + && payload?.requires_attention !== true) { + const error = new Error('删除回执状态无效,请勿重复删除,先刷新核对。'); + error.mutationMayHaveApplied = true; + error.safeToRetry = false; throw error; - } finally { clearTimeout(timeout); } + } + return payload; } function deleteButton(vmId, backup, library = false) { @@ -232,7 +206,13 @@ export function createAdminInstanceBackups({ button.type = 'button'; button.addEventListener('click', async () => { if (state.mutationRequest || backup.can_delete !== true) return; - if (!reconcile && !window.confirm(`确定删除备份“${String(backup.name || backup.id)}”吗?对象存储中的系统盘对象将被删除,且无法恢复。`)) return; + if (!reconcile && !await globalThis.VenixAdminDangerDialog.confirm({ + title: '永久删除云备份', + message: `对象存储中的备份“${String(backup.name || backup.id)}”及其精确系统盘对象将被删除,且无法恢复。请输入备份名称继续。`, + requiredText: String(backup.name || backup.id), + requiredLabel: '输入完整备份名称', + confirmText: '永久删除', + })) return; const controller = new AbortController(); state.mutationRequest = controller; button.disabled = true; surfaceNotice(reconcile ? '正在核对准确对象版本;只有两次间隔证据一致才会创建新的删除代次。' diff --git a/web/public/cloud/admin-instance-migration.js b/web/public/cloud/admin-instance-migration.js index b698a047..935ae9ae 100644 --- a/web/public/cloud/admin-instance-migration.js +++ b/web/public/cloud/admin-instance-migration.js @@ -104,10 +104,14 @@ export function createAdminInstanceMigration({ ? 'btn btn-outline-danger btn-sm' : 'btn btn-outline-primary btn-sm', label); button.type = 'button'; button.addEventListener('click', async () => { - const warning = aborting - ? '确定中止本次迁移并将源实例恢复到迁移前电源与自启状态吗?' - : `确定${label}吗?`; - if (isBusy?.() || !window.confirm(warning)) return; + if (isBusy?.() || !await globalThis.VenixAdminDangerDialog.confirm({ + tone: aborting ? 'danger' : 'warning', + title: label, + message: aborting + ? '本次迁移会被中止,系统将尝试把源实例恢复到迁移前的电源与自启状态。' + : `系统将创建新的“${label}”恢复任务;不会重放原任务。`, + confirmText: aborting ? '中止并恢复源实例' : '创建恢复任务', + })) return; for (const item of recoveryBox.querySelectorAll('button')) item.disabled = true; notice?.(`正在创建“${label}”任务,请勿重复提交。`); try { @@ -132,8 +136,11 @@ export function createAdminInstanceMigration({ const cleanup = el('button', 'btn btn-outline-danger btn-sm', '清理源宿主机副本'); cleanup.type = 'button'; cleanup.addEventListener('click', async () => { - if (isBusy?.() - || !window.confirm('确定删除源宿主机上的旧虚拟机及其托管磁盘吗?目标实例和账单不会删除。')) return; + if (isBusy?.() || !await globalThis.VenixAdminDangerDialog.confirm({ + title: '清理迁移源副本', + message: '源宿主机上的旧虚拟机及其面板托管磁盘将被永久删除;目标实例与账单不会删除。', + confirmText: '删除源副本', + })) return; cleanup.disabled = true; notice?.('正在创建源副本清理任务,请勿重复提交。'); try { await submitTask({ diff --git a/web/public/cloud/admin-instance-transport.js b/web/public/cloud/admin-instance-transport.js index 0947919e..a47dade2 100644 --- a/web/public/cloud/admin-instance-transport.js +++ b/web/public/cloud/admin-instance-transport.js @@ -1,95 +1,35 @@ -function mutationId() { - return globalThis.crypto?.randomUUID?.() - || `admin-${Date.now()}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`; -} - -function messageFromPayload(payload, status) { - const detail = Array.isArray(payload?.detail) - ? payload.detail.map(item => item?.msg || '输入错误').join(';') - : payload?.detail; - return typeof detail === 'string' - ? detail : (payload?.message || `请求失败 (${status})`); -} - export function createAdminInstanceTransport({ taskUrl, fetchImpl = globalThis.fetch?.bind(globalThis), locationImpl = globalThis.location, csrfToken = () => globalThis.ADMIN_CSRF_TOKEN || '', timeoutMs = 30000, + runtimeFactory = globalThis.VenixAdminRequestRuntime?.create, } = {}) { if (typeof taskUrl !== 'function') throw new TypeError('taskUrl is required'); - if (typeof fetchImpl !== 'function') throw new TypeError('fetch is unavailable'); + if (typeof runtimeFactory !== 'function') { + throw new TypeError('administrator request runtime is unavailable'); + } + + const runtime = runtimeFactory({ + fetchImpl, locationImpl, csrfToken, taskReceiptValidator: taskUrl, + }); - async function requestJson(path, controller, options = {}) { - const timeout = setTimeout(() => controller.abort('timeout'), timeoutMs); - try { - const response = await fetchImpl(path, { - headers: { Accept: 'application/json', ...(options.headers || {}) }, - credentials: 'same-origin', cache: 'no-store', signal: controller.signal, - ...options, - }); - if (response.status === 401) { - throw new Error(options.method ? '登录已过期,请重新登录。' : '登录已过期,请重新登录后刷新。'); - } - let payload; - try { payload = await response.json(); } - catch { throw new Error('服务返回异常,请检查服务器日志后重试。'); } - if (!response.ok || payload?.ret === 0) { - const error = new Error(messageFromPayload(payload, response.status)); - error.status = response.status; - throw error; - } - return { payload, response }; - } finally { - clearTimeout(timeout); - } + function read(path, controller) { + return runtime.read(path, { signal: controller.signal, timeoutMs }); } - async function read(path, controller) { - try { - const { payload } = await requestJson(path, controller); - return payload; - } catch (error) { - if (controller.signal.reason === 'timeout') throw new Error('请求超时,请稍后重试。'); - throw error; - } + function mutate(path, body, controller, method = 'PATCH') { + return runtime.mutate(path, { + method, body, signal: controller.signal, timeoutMs, response: 'task', + }); } - async function mutate(path, body, controller, method = 'PATCH') { - if (locationImpl?.protocol !== 'https:' - && !['localhost', '127.0.0.1', '[::1]'].includes(locationImpl?.hostname)) { - throw new Error('请通过 HTTPS 修改实例配置。'); - } - try { - const { payload, response } = await requestJson(path, controller, { - method, - headers: { - 'Content-Type': 'application/json', - 'X-CSRF-Token': csrfToken(), - 'Idempotency-Key': mutationId(), - }, - body: JSON.stringify(body), - }); - if (response.status !== 202 || !taskUrl(payload)) { - const error = new Error('请求已送达,但任务回执协议无效。请勿重复提交,并联系管理员核查。'); - error.status = response.status; - error.mutationMayHaveApplied = true; - throw error; - } - return payload; - } catch (error) { - if (controller.signal.reason === 'timeout') { - const timeoutError = new Error('请求超时,结果无法确认。请勿重复提交,并联系管理员核查。'); - timeoutError.mutationMayHaveApplied = true; - throw timeoutError; - } - if (error?.status >= 500 || (!error?.status && error?.name !== 'AbortError')) { - error.mutationMayHaveApplied = true; - } - throw error; - } + function mutateJson(path, body, controller, method = 'POST') { + return runtime.mutate(path, { + method, body, signal: controller.signal, timeoutMs, response: 'json', + }); } - return Object.freeze({ read, mutate }); + return Object.freeze({ read, mutate, mutateJson }); } diff --git a/web/public/cloud/admin-instances.js b/web/public/cloud/admin-instances.js index 3cb87a11..86b38b85 100644 --- a/web/public/cloud/admin-instances.js +++ b/web/public/cloud/admin-instances.js @@ -24,7 +24,7 @@ const [{ const root = document.querySelector('[data-admin-instances]'); const byId = id => document.getElementById(id); -const { read, mutate } = createAdminInstanceTransport({ taskUrl }); +const { read, mutate, mutateJson } = createAdminInstanceTransport({ taskUrl }); function mutationBlockMessage(task, action) { if (task?.blocks_mutation !== true) return ''; @@ -116,6 +116,7 @@ if (root) { byId, read, mutate, + mutateJson, createMigration: createAdminInstanceMigration, announceTaskAccepted, observeTask, diff --git a/web/public/cloud/admin-object-storage.css b/web/public/cloud/admin-object-storage.css index bd0b78a6..0bcc76eb 100644 --- a/web/public/cloud/admin-object-storage.css +++ b/web/public/cloud/admin-object-storage.css @@ -741,82 +741,6 @@ body.os-drawer-open { overflow: hidden; } -.os-confirm-layer { - position: fixed; - z-index: 1090; - inset: 0; - display: grid; - place-items: center; - padding: 20px; -} - -.os-confirm-layer[hidden] { - display: none; -} - -.os-confirm-backdrop { - position: absolute; - inset: 0; - width: 100%; - border: 0; - background: rgba(15, 32, 49, 0.56); - backdrop-filter: blur(2px); -} - -.os-confirm-dialog { - position: relative; - display: grid; - grid-template-columns: auto minmax(0, 1fr); - gap: 15px; - width: min(470px, 100%); - padding: 24px; - border-radius: 16px; - background: #fff; - box-shadow: 0 28px 80px rgba(15, 32, 49, 0.28); -} - -.os-confirm-icon { - display: inline-flex; - align-items: center; - justify-content: center; - width: 42px; - height: 42px; - border-radius: 12px; - color: #c13d3d; - background: #fff0f0; - font-size: 23px; -} - -.os-confirm-dialog.is-primary .os-confirm-icon { - color: #0b858d; - background: #e9f8f8; -} - -.os-confirm-copy h2 { - margin: 1px 0 7px; - color: #1d344b; - font-size: 19px; -} - -.os-confirm-copy p { - margin: 0; - color: #6f8398; - font-size: 13px; - line-height: 1.65; -} - -.os-confirm-actions { - display: flex; - grid-column: 1 / -1; - justify-content: flex-end; - gap: 9px; - padding-top: 4px; -} - -body.os-dialog-open { - overflow: hidden; -} - @media (max-width: 1100px) { .os-summary, .os-connection-details { @@ -1043,14 +967,6 @@ body.os-dialog-open { flex: 1 1 0; } - .os-confirm-dialog { - padding: 20px; - } - - .os-confirm-actions .btn { - flex: 1 1 0; - } - .os-cleanup-legend { display: grid; } diff --git a/web/public/cloud/admin-object-storage.js b/web/public/cloud/admin-object-storage.js index 79c6e8a1..2d327445 100644 --- a/web/public/cloud/admin-object-storage.js +++ b/web/public/cloud/admin-object-storage.js @@ -1,29 +1,17 @@ (function () { 'use strict'; + var runtime = window.VenixAdminRequestRuntime.create(); + function request(url, payload) { - return fetch(url, { + return runtime.mutate(url, { method: 'POST', - credentials: 'same-origin', - headers: { - Accept: 'application/json', - 'Content-Type': 'application/json', - 'X-Requested-With': 'XMLHttpRequest', - }, - body: JSON.stringify(payload), - }).then(function (response) { - return response.text().then(function (body) { - var result; - try { - result = JSON.parse(body); - } catch (error) { - throw new Error('服务器未返回有效结果(HTTP ' + response.status + ')'); - } - if (!response.ok || Number(result.ret) !== 1) { - throw new Error(result.msg || '请求失败'); - } - return result; - }); + headers: { 'X-Requested-With': 'XMLHttpRequest' }, + body: payload, + response: 'json', + }).then(function (result) { + if (Number(result && result.ret) !== 1) throw new Error(result && result.msg || '请求失败'); + return result; }); } @@ -33,51 +21,13 @@ node.className = 'os-notice is-show ' + (ok ? 'is-ok' : 'is-error'); } - function initializeConfirmation() { - var layer = document.getElementById('osConfirmDialog'); - if (!layer) return null; - var dialog = layer.querySelector('[role="alertdialog"]'); - var title = document.getElementById('osConfirmTitle'); - var message = document.getElementById('osConfirmMessage'); - var submit = document.getElementById('osConfirmSubmit'); - var cancelButtons = layer.querySelectorAll('[data-os-confirm-cancel]'); - var pending = null; - var previousFocus = null; - - function close(result) { - if (!pending) return; - var resolve = pending; - pending = null; - layer.hidden = true; - document.body.classList.remove('os-dialog-open'); - if (previousFocus && typeof previousFocus.focus === 'function') { - previousFocus.focus({ preventScroll: true }); - } - previousFocus = null; - resolve(result); - } - - cancelButtons.forEach(function (button) { - button.addEventListener('click', function () { close(false); }); + function confirmAction(options) { + return window.VenixAdminDangerDialog.confirm({ + title: options.title, + message: options.message, + confirmText: options.confirmLabel, + tone: options.tone === 'primary' ? 'warning' : 'danger', }); - submit.addEventListener('click', function () { close(true); }); - document.addEventListener('keydown', function (event) { - if (event.key === 'Escape' && !layer.hidden) close(false); - }); - - return function confirmAction(options) { - if (pending) return Promise.resolve(false); - title.textContent = options.title; - message.textContent = options.message; - submit.textContent = options.confirmLabel; - submit.className = options.tone === 'primary' ? 'btn btn-primary' : 'btn btn-danger'; - dialog.classList.toggle('is-primary', options.tone === 'primary'); - previousFocus = document.activeElement; - layer.hidden = false; - document.body.classList.add('os-dialog-open'); - submit.focus({ preventScroll: true }); - return new Promise(function (resolve) { pending = resolve; }); - }; } function initializeConfiguration(confirmAction) { @@ -310,7 +260,6 @@ } function initialize() { - var confirmAction = initializeConfirmation(); initializeTabs(); initializeConfigurationDrawer(); initializeConfiguration(confirmAction); diff --git a/web/public/cloud/admin-operations.js b/web/public/cloud/admin-operations.js index 1ac2e060..a6208864 100644 --- a/web/public/cloud/admin-operations.js +++ b/web/public/cloud/admin-operations.js @@ -12,6 +12,9 @@ const { taskSucceededWithoutRecovery, } = await import(versionedModuleUrl('./task-observer.js')); +const requestRuntime = window.VenixAdminRequestRuntime.create({ taskReceiptValidator: taskUrl }); +const confirmDanger = options => window.VenixAdminDangerDialog.confirm(options); + const root = document.querySelector('[data-admin-operations]'); const byId = id => document.getElementById(id); const filterNames = ['q', 'status', 'kind', 'host_id', 'per_page']; @@ -101,34 +104,15 @@ function historyData(changes = {}) { } async function api(path, controller, timeoutMs = 15000, options = {}) { - const timer = setTimeout(() => controller.abort('timeout'), timeoutMs); - try { - const method = String(options.method || 'GET').toUpperCase(); - const headers = { Accept: 'application/json', ...(options.headers || {}) }; - const request = { method, headers, credentials: 'same-origin', cache: 'no-store', signal: controller.signal }; - if (!['GET', 'HEAD'].includes(method)) { - if (!window.ADMIN_CSRF_TOKEN) throw new Error('页面安全令牌缺失,请刷新页面。'); - headers['X-CSRF-Token'] = window.ADMIN_CSRF_TOKEN; - headers['Content-Type'] = 'application/json'; - request.body = options.body === undefined ? '{}' : options.body; - } - const response = await fetch(path, request); - if (response.status === 401) throw new Error('登录已过期,请重新登录。'); - let payload; - try { payload = await response.json(); } - catch { throw new Error('服务器返回了无效数据。'); } - if (!response.ok || payload?.ret === 0) { - throw new Error(typeof payload?.detail === 'string' ? payload.detail - : (payload?.message || payload?.error || `请求失败 (${response.status})`)); - } - if (options.expectedStatus !== undefined && response.status !== options.expectedStatus) { - throw new Error(`服务未返回预期的 HTTP ${options.expectedStatus} 任务回执;为避免重复执行,请勿再次提交并联系管理员。`); - } - return payload; - } catch (error) { - if (controller.signal.reason === 'timeout') throw new Error('请求超时,请稍后刷新。'); - throw error; - } finally { clearTimeout(timer); } + const method = String(options.method || 'GET').toUpperCase(); + const common = { signal: controller.signal, timeoutMs, headers: options.headers || {} }; + if (['GET', 'HEAD'].includes(method)) return requestRuntime.read(path, { ...common, method }); + return requestRuntime.mutate(path, { + ...common, + method, + body: options.body, + response: options.expectedStatus === 202 ? 'task' : 'json', + }); } async function acceptedTask(path, controller, timeoutMs, options = {}) { @@ -497,7 +481,7 @@ async function inspectOperation(id) { renderDetailActions(); detailNotice('正在执行一次宿主机只读检查;不会执行 Agent 操作。'); try { const payload = await api(`/api/v1/admin/operations/jobs/${encodeURIComponent(id)}/inspect`, controller, 30000, { - method: 'POST', body: '{}', + method: 'POST', body: {}, }); if (String(payload?.job?.id || '') !== String(id)) throw new Error('只读检查结果与当前任务不匹配。'); if (state.detailId !== String(id) || !byId('operation-detail').open) return; @@ -523,12 +507,17 @@ async function resolveEffect(id) { detailNotice('审计说明必须为 20–500 个字符。', true); return; } const label = resolution === 'applied' ? '操作效果已经发生' : '操作效果未发生'; - if (!window.confirm(`确认将人工核实结果记录为“${label}”?\n\n原任务仍保持失败,不会重放 Agent 或支付请求。服务端仅会在可原子收敛相关业务账本时写入结论。`)) return; + if (!await confirmDanger({ + tone: 'warning', + title: '记录人工核实结论', + message: `将人工核实结果记录为“${label}”。原任务仍保持失败,不会重放 Agent 或支付请求;服务端仅在可原子收敛相关业务账本时写入结论。`, + confirmText: '记录结论', + })) return; const controller = new AbortController(); controller.kind = 'resolve-effect'; state.actionRequest = controller; renderDetailActions(); detailNotice('正在核验最新证据并原子写入人工审计结论…'); try { const payload = await api(`/api/v1/admin/operations/jobs/${encodeURIComponent(id)}/resolve-effect`, controller, 45000, { - method: 'POST', body: JSON.stringify({ resolution, reason }), + method: 'POST', body: { resolution, reason }, }); if (String(payload?.job?.id || '') !== String(id)) throw new Error('审计结果与当前任务不匹配。'); if (state.detailId !== String(id) || !byId('operation-detail').open) return; @@ -548,12 +537,18 @@ async function resolveEffect(id) { async function forceDelete(id) { if (!canManage() || state.detailId !== String(id) || state.detailJob?.can_force_delete !== true || state.actionRequest || state.forceDeleteAccepted || state.forceDeleteBlocked) return; - if (!window.confirm('这是强制删除的数据丢失确认。\n\n继续会创建一个新的后台任务,并允许宿主机强制断电;未刷入磁盘的数据可能永久丢失。\n\n确认承担风险并继续?')) return; + if (!await confirmDanger({ + title: '强制删除实例资源', + message: '继续会创建新的后台任务并允许宿主机强制断电;未刷入磁盘的数据可能永久丢失。请输入当前任务编号确认承担风险。', + requiredText: String(id), + requiredLabel: '输入当前任务编号', + confirmText: '强制删除', + })) return; const controller = new AbortController(); state.actionRequest = controller; renderDetailActions(); detailNotice('正在提交强制删除请求…'); try { const payload = await acceptedTask(`/api/v1/admin/operations/jobs/${encodeURIComponent(id)}/force-delete`, controller, 30000, { - method: 'POST', body: JSON.stringify({ ack_data_loss: true }), + method: 'POST', body: { ack_data_loss: true }, }); state.forceDeleteAccepted = true; state.forceDeleteAcceptedIds.add(String(id)); @@ -601,13 +596,18 @@ async function repairVpc(id) { if (!canManage() || state.detailId !== String(id) || state.detailJob?.can_repair_vpc !== true || state.actionRequest || state.vpcRepairAccepted) return; - if (!window.confirm('系统将先执行一次只读宿主机检查;只有原 VPC 操作仍处于影响未知且 Agent 可达时,才会创建新的修复任务。\n\n原操作不会重放,修复任务使用新的操作标识并保留继任关系。确认继续?')) return; + if (!await confirmDanger({ + tone: 'warning', + title: '创建 VPC 修复任务', + message: '系统会先执行只读宿主机检查;仅当原 VPC 操作仍为影响未知且 Agent 可达时才创建修复任务。原操作不会重放,新任务使用独立操作标识并保留继任关系。', + confirmText: '检查并创建', + })) return; const controller = new AbortController(); controller.kind = 'repair-vpc'; state.actionRequest = controller; renderDetailActions(); detailNotice('正在检查宿主机并创建精确 VPC 修复任务…'); try { const payload = await acceptedTask(`/api/v1/admin/operations/jobs/${encodeURIComponent(id)}/repair-vpc`, controller, 45000, { - method: 'POST', body: JSON.stringify({ acknowledge_repair: true }), + method: 'POST', body: { acknowledge_repair: true }, }); state.vpcRepairAccepted = true; state.vpcRepairAcceptedIds.add(String(id)); @@ -654,17 +654,23 @@ async function retireVpcHost(id) { detailNotice('退役依据需为 20 至 500 个字符。', true); return; } - if (!window.confirm('这是物理宿主机永久退役确认,不会联系 Agent,也不会重试原操作。\n\n确认该宿主机已永久退出服务且不会带着原本地 VPC 状态重新上线?')) return; + if (!await confirmDanger({ + title: '确认宿主机永久退役', + message: '该操作不会联系 Agent,也不会重试原操作。请确认宿主机已永久退出服务,且不会携带原本地 VPC 状态重新上线。请输入当前任务编号继续。', + requiredText: String(id), + requiredLabel: '输入当前任务编号', + confirmText: '记录永久退役', + })) return; const controller = new AbortController(); controller.kind = 'retire-vpc-host'; state.actionRequest = controller; renderDetailActions(); detailNotice('正在核对宿主机资源账本…'); try { const payload = await api(`/api/v1/admin/operations/jobs/${encodeURIComponent(id)}/retire-vpc-host`, controller, 45000, { method: 'POST', - body: JSON.stringify({ + body: { acknowledge_permanent_retirement: true, reason: normalized, - }), + }, }); if (payload?.retired !== true || String(payload.task_id || '') !== String(id)) { throw new Error('退役响应与当前任务不一致。'); diff --git a/web/public/cloud/admin-request-runtime.js b/web/public/cloud/admin-request-runtime.js new file mode 100644 index 00000000..dfdcb48c --- /dev/null +++ b/web/public/cloud/admin-request-runtime.js @@ -0,0 +1,168 @@ +(function (global) { + 'use strict'; + + function mutationId(cryptoImpl) { + return cryptoImpl && typeof cryptoImpl.randomUUID === 'function' + ? cryptoImpl.randomUUID() + : 'admin-' + Date.now() + '-' + Math.random().toString(36).slice(2) + + '-' + Math.random().toString(36).slice(2); + } + + function messageFromPayload(payload, status) { + var detail = Array.isArray(payload && payload.detail) + ? payload.detail.map(function (item) { return item && item.msg ? item.msg : '输入错误'; }).join(';') + : payload && payload.detail; + return typeof detail === 'string' && detail + ? detail : String(payload && (payload.message || payload.error || payload.msg) + || '请求失败 (' + status + ')'); + } + + function createError(message, properties) { + var error = new Error(message); + Object.keys(properties || {}).forEach(function (key) { error[key] = properties[key]; }); + return error; + } + + function isLocalLocation(locationImpl) { + return locationImpl && ['localhost', '127.0.0.1', '[::1]'].indexOf(locationImpl.hostname) !== -1; + } + + function create(options) { + var config = options && typeof options === 'object' ? options : {}; + var fetchImpl = config.fetchImpl || (global.fetch && global.fetch.bind(global)); + var locationImpl = config.locationImpl || global.location; + var cryptoImpl = config.cryptoImpl || global.crypto; + var csrfToken = typeof config.csrfToken === 'function' + ? config.csrfToken : function () { return global.ADMIN_CSRF_TOKEN || ''; }; + var taskReceiptValidator = typeof config.taskReceiptValidator === 'function' + ? config.taskReceiptValidator : null; + var setTimer = config.setTimeoutImpl || global.setTimeout.bind(global); + var clearTimer = config.clearTimeoutImpl || global.clearTimeout.bind(global); + var AbortControllerImpl = config.AbortControllerImpl || global.AbortController; + if (typeof fetchImpl !== 'function') throw new TypeError('fetch is unavailable'); + if (typeof AbortControllerImpl !== 'function') throw new TypeError('AbortController is unavailable'); + + async function execute(path, input, mutation) { + var request = input && typeof input === 'object' ? input : {}; + var method = String(request.method || (mutation ? 'POST' : 'GET')).toUpperCase(); + var allowed = mutation + ? ['POST', 'PUT', 'PATCH', 'DELETE'] : ['GET', 'HEAD']; + if (allowed.indexOf(method) === -1) { + throw new TypeError(mutation + ? 'mutation method must be POST, PUT, PATCH or DELETE' + : 'read method must be GET or HEAD'); + } + var timeoutMs = Math.max(1000, Number(request.timeoutMs) || (mutation ? 30000 : 15000)); + var responseKind = mutation ? String(request.response || 'json') : 'json'; + if (mutation && responseKind !== 'json' && responseKind !== 'task') { + throw new TypeError('mutation response must be json or task'); + } + if (mutation && locationImpl && locationImpl.protocol !== 'https:' && !isLocalLocation(locationImpl)) { + throw createError('请通过 HTTPS 执行管理员修改操作。', { + code: 'https_required', mutationMayHaveApplied: false, safeToRetry: true, + }); + } + var token = mutation ? String(csrfToken() || '') : ''; + if (mutation && !/^[a-f0-9]{64}$/.test(token)) { + throw createError('页面安全令牌缺失,请刷新页面。', { + code: 'csrf_missing', mutationMayHaveApplied: false, safeToRetry: true, + }); + } + var controller = new AbortControllerImpl(); + var externalSignal = request.signal; + var externallyAborted = externalSignal && externalSignal.aborted; + if (externallyAborted) { + throw createError('请求已取消。', { + code: 'cancelled', mutationMayHaveApplied: false, safeToRetry: true, + }); + } + var forwardAbort = function () { controller.abort(externalSignal.reason || 'cancelled'); }; + if (externalSignal && typeof externalSignal.addEventListener === 'function') { + externalSignal.addEventListener('abort', forwardAbort, { once: true }); + if (externalSignal.aborted) forwardAbort(); + } + var timeout = setTimer(function () { controller.abort('timeout'); }, timeoutMs); + var headers = new Headers({ Accept: 'application/json' }); + Object.keys(request.headers || {}).forEach(function (key) { headers.set(key, request.headers[key]); }); + var idempotencyKey = ''; + if (mutation) { + idempotencyKey = String(request.idempotencyKey || mutationId(cryptoImpl)); + headers.set('X-Admin-CSRF-Token', token); + headers.set('Idempotency-Key', idempotencyKey); + if (request.body !== undefined) headers.set('Content-Type', 'application/json'); + } + var dispatched = false; + try { + dispatched = true; + var response = await fetchImpl(path, { + method: method, + headers: headers, + credentials: 'same-origin', + cache: 'no-store', + signal: controller.signal, + body: request.body === undefined ? undefined : JSON.stringify(request.body), + }); + var payload = null; + if (response.status !== 204) { + try { payload = await response.json(); } + catch (error) { + throw createError('服务返回了无效数据。', { + code: 'invalid_json', status: response.status, + mutationMayHaveApplied: mutation, safeToRetry: !mutation, + idempotencyKey: idempotencyKey, + }); + } + } + if (!response.ok || (payload && payload.ret === 0)) { + var uncertain = mutation && (response.status >= 500 || response.status === 408); + throw createError(messageFromPayload(payload, response.status), { + code: response.status === 401 ? 'unauthorized' : 'http_error', + status: response.status, + mutationMayHaveApplied: uncertain, + safeToRetry: !uncertain, + idempotencyKey: idempotencyKey, + }); + } + if (mutation && responseKind === 'task') { + if (response.status !== 202 || !taskReceiptValidator || !taskReceiptValidator(payload)) { + throw createError('请求已送达,但任务回执协议无效。请勿重复提交,并联系管理员核查。', { + code: 'invalid_task_receipt', status: response.status, + mutationMayHaveApplied: true, safeToRetry: false, + idempotencyKey: idempotencyKey, + }); + } + } + return request.returnMeta === true + ? Object.freeze({ payload: payload, status: response.status }) : payload; + } catch (error) { + if (error && Object.prototype.hasOwnProperty.call(error, 'mutationMayHaveApplied')) throw error; + var reason = controller.signal.reason; + if (!mutation) { + if (reason === 'timeout') throw createError('请求超时,请稍后重试。', { code: 'timeout', safeToRetry: true }); + throw error; + } + throw createError(reason === 'timeout' + ? '请求超时,操作结果无法确认。请勿重复提交,并联系管理员核查。' + : '请求连接中断,操作结果无法确认。请勿重复提交,并联系管理员核查。', { + code: reason === 'timeout' ? 'timeout' : 'transport_error', + mutationMayHaveApplied: dispatched, + safeToRetry: !dispatched, + idempotencyKey: idempotencyKey, + cause: error, + }); + } finally { + clearTimer(timeout); + if (externalSignal && typeof externalSignal.removeEventListener === 'function') { + externalSignal.removeEventListener('abort', forwardAbort); + } + } + } + + return Object.freeze({ + read: function (path, options) { return execute(path, options, false); }, + mutate: function (path, options) { return execute(path, options, true); }, + }); + } + + global.VenixAdminRequestRuntime = Object.freeze({ create: create }); +}(typeof window !== 'undefined' ? window : globalThis)); diff --git a/web/public/cloud/admin-resources.js b/web/public/cloud/admin-resources.js index 1b80162e..4954a345 100644 --- a/web/public/cloud/admin-resources.js +++ b/web/public/cloud/admin-resources.js @@ -9,6 +9,7 @@ const labels = { line: { singular: '线路', endpoint: '/api/v1/admin/network-lines' }, pool: { singular: '资源池', endpoint: '/api/v1/admin/resource-pools' }, }; +const requestRuntime = window.VenixAdminRequestRuntime.create(); function byId(id) { return document.getElementById(id); } function asText(value, fallback = '未记录') { @@ -45,30 +46,14 @@ function setEditorNotice(message, tone = '') { } async function api(path, options = {}) { - const controller = new AbortController(); - const timer = window.setTimeout(() => controller.abort('timeout'), 20000); - try { - const response = await fetch(path, { - credentials: 'same-origin', cache: 'no-store', signal: controller.signal, - ...options, - headers: { - Accept: 'application/json', - 'Content-Type': 'application/json', - 'X-CSRF-Token': window.ADMIN_CSRF_TOKEN || '', - ...(options.headers || {}), - }, - }); - let payload = null; - try { payload = await response.json(); } catch { /* handled below */ } - if (!response.ok || payload?.ret === 0) { - const message = payload?.detail || payload?.message || payload?.msg; - throw new Error(typeof message === 'string' && message ? message : `请求失败 (${response.status})`); - } - return payload; - } catch (error) { - if (controller.signal.reason === 'timeout') throw new Error('请求超时,请稍后重试。'); - throw error; - } finally { window.clearTimeout(timer); } + const method = String(options.method || 'GET').toUpperCase(); + if (['GET', 'HEAD'].includes(method)) { + return requestRuntime.read(path, { method, timeoutMs: 20000, headers: options.headers }); + } + return requestRuntime.mutate(path, { + method, body: options.body, timeoutMs: 20000, + headers: options.headers, response: 'json', + }); } function openDrawer(dialog, opener) { @@ -224,7 +209,7 @@ byId('resource-editor-form')?.addEventListener('submit', async event => { const submit = byId('resource-editor-submit'); submit.disabled = true; setEditorNotice('正在保存…', 'loading'); try { - await api(`${meta.endpoint}${id ? `/${id}` : ''}`, { method: id ? 'PATCH' : 'POST', body: JSON.stringify(body) }); + await api(`${meta.endpoint}${id ? `/${id}` : ''}`, { method: id ? 'PATCH' : 'POST', body }); setEditorNotice(`${meta.singular}已保存,正在刷新…`, 'success'); location.reload(); } catch (error) { @@ -241,7 +226,7 @@ byId('network-line-feature-form')?.addEventListener('submit', async event => { submit.disabled = true; setNotice('正在保存线路开关…'); try { await api('/api/v1/admin/resources/settings', { - method: 'PUT', body: JSON.stringify({ network_lines_enabled: form.elements.namedItem('network_lines_enabled').checked }), + method: 'PUT', body: { network_lines_enabled: form.elements.namedItem('network_lines_enabled').checked }, }); setNotice('线路开关已保存,正在刷新…'); location.reload(); diff --git a/web/public/cloud/admin-vpc.js b/web/public/cloud/admin-vpc.js index 316a22bf..69955481 100644 --- a/web/public/cloud/admin-vpc.js +++ b/web/public/cloud/admin-vpc.js @@ -10,6 +10,7 @@ const state = { poolEditingId: '', requestKey: '', }; +const requestRuntime = window.VenixAdminRequestRuntime.create({ csrfToken: () => state.csrf }); function readBootstrap() { try { @@ -32,30 +33,19 @@ function notice(message, tone = 'success') { box.className = `admin-config-status is-${tone}`; } -function errorMessage(payload, status) { - return String(payload?.detail || payload?.error || `请求失败 (${status})`); -} - async function api(path, options = {}) { - const method = (options.method || 'GET').toUpperCase(); - const headers = new Headers({ Accept: 'application/json' }); - if (!['GET', 'HEAD'].includes(method)) { - headers.set('Content-Type', 'application/json'); - headers.set('X-CSRF-Token', state.csrf); - } - 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; - try { payload = await response.json(); } catch { throw new Error('服务返回非 JSON 响应。'); } - if (response.status === 401) { - location.assign('/auth/login'); - throw new Error('登录已过期。'); + const method = String(options.method || 'GET').toUpperCase(); + try { + if (['GET', 'HEAD'].includes(method)) { + return await requestRuntime.read(path, { method, signal: options.signal }); + } + return await requestRuntime.mutate(path, { + method, body: options.body, signal: options.signal, response: 'json', + }); + } catch (error) { + if (error?.status === 401) location.assign('/auth/login'); + throw error; } - if (!response.ok) throw new Error(errorMessage(payload, response.status)); - return payload; } function create(tag, className = '', text = '') { diff --git a/web/public/cloud/admin.js b/web/public/cloud/admin.js index 9351af03..87002e18 100644 --- a/web/public/cloud/admin.js +++ b/web/public/cloud/admin.js @@ -15,33 +15,53 @@ const { const root = document.querySelector('[data-cloud-admin]'); const byId = id => document.getElementById(id); const state = { csrf: window.ADMIN_CSRF_TOKEN || '', hosts: [], hostRegions: [], hostSummary: {}, expandedHostRegions: new Set(), hostRegionsInitialized: false, selectedHost: '', busy: false, epoch: 0, configBusy: false, configOpener: null, configScroll: null, storageBusy: false, storageOpener: null, storageScroll: null, storageObserver: null, schedulingBusy: false, schedulingOpener: null, schedulingScroll: null, networkPoolBusy: false, networkPoolOpener: null, networkPoolScroll: null, networkPoolPayload: null, networkPoolEpoch: 0, networkPoolHostId: '', vpcTransportBusy: false, vpcTransportOpener: null, vpcTransportScroll: null, vpcTransportHostId: '', vpcTransportCandidates: [], taskObservers: new Set() }; +const requestRuntime = window.VenixAdminRequestRuntime.create({ + csrfToken: () => state.csrf, + taskReceiptValidator: taskUrl, +}); +const confirmDanger = options => window.VenixAdminDangerDialog.confirm(options); // Permission state is rendered by the server on the page. API endpoints keep // the authoritative authorization check; this only controls the UI affordances. const canManage = root?.dataset.canManage === '1'; const collection = (payload, key = 'items') => Array.isArray(payload) ? payload : Array.isArray(payload?.[key]) ? payload[key] : Array.isArray(payload?.items) ? payload.items : []; function element(tag, className = '', content) { const node = document.createElement(tag); node.className = className; if (content !== undefined) node.textContent = String(content); return node; } function notice(message, error = false) { const box = byId('cloud-admin-status'); box.textContent = message; box.className = `alert ${error ? 'alert-danger' : 'alert-info'} cloud-admin-notice`; } -function errorMessage(payload, status) { if (Array.isArray(payload?.detail)) return payload.detail.map(item => item.msg || '输入错误').join(';'); return String(payload?.detail || payload?.message || payload?.msg || `请求失败 (${status})`); } +function uploadErrorMessage(payload, status) { if (Array.isArray(payload?.detail)) return payload.detail.map(item => item.msg || '输入错误').join(';'); return String(payload?.detail || payload?.message || payload?.msg || `请求失败 (${status})`); } async function requestJson(path, options = {}) { - const method = (options.method || 'GET').toUpperCase(); const headers = new Headers({ Accept: 'application/json' }); - if (!['GET', 'HEAD'].includes(method)) { if (location.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) throw new Error('请通过 HTTPS 修改宿主机及镜像配置。'); headers.set('X-CSRF-Token', state.csrf); headers.set('Content-Type', options.raw ? 'application/octet-stream' : 'application/json'); } - const response = await fetch(path, { ...options, method, headers, credentials: 'same-origin', cache: 'no-store', body: options.body === undefined ? undefined : options.raw ? options.body : JSON.stringify(options.body) }); - let payload = null; if (response.status !== 204) { try { payload = 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) throw new Error(errorMessage(payload, response.status)); - return { payload, status: response.status }; + const method = String(options.method || 'GET').toUpperCase(); + try { + if (['GET', 'HEAD'].includes(method)) { + return await requestRuntime.read(path, { + method, signal: options.signal, timeoutMs: options.timeoutMs, + headers: options.headers, returnMeta: true, + }); + } + return await requestRuntime.mutate(path, { + method, body: options.body, signal: options.signal, + timeoutMs: options.timeoutMs, headers: options.headers, + response: 'json', returnMeta: true, + }); + } catch (error) { + if (error?.status === 401) location.assign('/auth/login'); + if (error?.mutationMayHaveApplied === true) error.keepMutationLocked = true; + throw error; + } } async function api(path, options = {}) { return (await requestJson(path, options)).payload; } async function acceptedTask(path, options = {}) { - const { payload, status } = await requestJson(path, options); - if (status !== 202 || !taskUrl(payload)) { - const error = new Error('请求已送达,但服务未返回严格的 202 任务回执。请勿再次提交,并联系管理员核查。'); - error.keepMutationLocked = true; + try { + return await requestRuntime.mutate(path, { + method: options.method || 'POST', body: options.body, + signal: options.signal, timeoutMs: options.timeoutMs, + headers: options.headers, response: 'task', + }); + } catch (error) { + if (error?.status === 401) location.assign('/auth/login'); + if (error?.mutationMayHaveApplied === true) error.keepMutationLocked = true; throw error; } - return payload; } function uploadApi(path, file, onProgress) { if (location.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) return Promise.reject(new Error('请通过 HTTPS 上传云镜像。')); @@ -50,7 +70,7 @@ function uploadApi(path, file, onProgress) { request.open('POST', path, true); request.withCredentials = true; request.setRequestHeader('Accept', 'application/json'); - request.setRequestHeader('X-CSRF-Token', state.csrf); + request.setRequestHeader('X-Admin-CSRF-Token', state.csrf); request.setRequestHeader('Content-Type', 'application/octet-stream'); request.upload.addEventListener('progress', event => { if (event.lengthComputable && typeof onProgress === 'function') onProgress(event.loaded, event.total); @@ -65,7 +85,7 @@ function uploadApi(path, file, onProgress) { return; } if (request.status === 401) { location.assign('/auth/login'); reject(new Error('登录已过期。')); return; } - if (request.status < 200 || request.status >= 300 || payload?.ret === 0) { reject(new Error(errorMessage(payload, request.status))); return; } + if (request.status < 200 || request.status >= 300 || payload?.ret === 0) { reject(new Error(uploadErrorMessage(payload, request.status))); return; } resolve(payload); }); request.addEventListener('error', () => reject(new Error('云镜像上传失败,请检查网络或反代限制。'))); @@ -964,7 +984,12 @@ async function repairTemplateReplica(entry, replica, button) { const action = String(replica?.repair_action || ''); if (!['import', 'metadata'].includes(action)) return; const verb = action === 'metadata' ? '同步元数据' : '补齐副本'; - if (!confirm(`确定为“${entry.name}”在 ${replica.host_name || `宿主机 #${replica.host_id}`}执行${verb}?`)) return; + if (!await confirmDanger({ + tone: 'warning', + title: `${verb} · ${entry.name}`, + message: `系统会在 ${replica.host_name || `宿主机 #${replica.host_id}`} 创建独立任务;不会重放旧任务。`, + confirmText: verb, + })) return; state.busy = true; button.disabled = true; try { @@ -1085,7 +1110,13 @@ function bindCloudTemplateActions(entry, form, name, save, remove, startup) { : cleanupReason === 'artifact_delete_attention' ? `云镜像模版“${entry.name}”的宿主机副本已删除,但对象存储主副本需要重新核对。确定只重试主副本清理?不会再次向宿主机发送删除请求。` : `删除全局云镜像模版“${entry.name}”?删除后不能再用于新建或重装;已创建实例不受影响。`; - if (!confirm(message)) return; + if (!await confirmDanger({ + title: partialCleanup ? '清理云镜像残留' : '永久删除云镜像版本', + message, + requiredText: String(entry.name), + requiredLabel: '输入完整镜像名称', + confirmText: partialCleanup ? '清理残留' : '永久删除', + })) return; remove.disabled = true; state.busy = true; try { const result = await api(`${catalogPath()}/${encodeURIComponent(entry.id)}`, { @@ -1185,7 +1216,12 @@ function rescueReplicaStateView(entry, replica) { } async function repairRescueReplica(entry, replica, button) { if (state.busy || replica?.repair_action !== 'import') return; - if (!confirm(`确定在 ${replica.host_name || `宿主机 #${replica.host_id}`} 补齐救援 ISO“${entry.name}”的精确副本?`)) return; + if (!await confirmDanger({ + tone: 'warning', + title: `补齐救援 ISO · ${entry.name}`, + message: `系统会在 ${replica.host_name || `宿主机 #${replica.host_id}`} 创建独立分发任务,以补齐内容一致的精确副本。`, + confirmText: '补齐副本', + })) return; state.busy = true; button.disabled = true; try { const { payload, status } = await requestJson( @@ -1280,7 +1316,13 @@ function rescueTemplateCard(entry) { const remove = element('button', 'btn btn-outline-danger', String(entry.state || '') === 'retiring' ? '正在退役' : '退役并清理'); remove.type = 'button'; remove.disabled = !canManage || String(entry.state || '') === 'retiring'; remove.addEventListener('click', async () => { - if (state.busy || !confirm(`退役全局救援 ISO“${entry.name}”?系统会停止新挂载,并异步删除全部宿主机副本和对象存储精确版本。`)) return; + if (state.busy || !await confirmDanger({ + title: '退役并清理救援 ISO', + message: `全局救援 ISO“${entry.name}”会立即停止新挂载,并异步删除全部宿主机副本与对象存储精确版本。请输入完整名称继续。`, + requiredText: String(entry.name), + requiredLabel: '输入完整救援 ISO 名称', + confirmText: '退役并清理', + })) return; state.busy = true; remove.disabled = true; try { const result = await api(`${catalogPath()}/${encodeURIComponent(entry.id)}`, { diff --git a/web/public/cloud/agent-settings.js b/web/public/cloud/agent-settings.js index df6a96ac..4414a2d1 100644 --- a/web/public/cloud/agent-settings.js +++ b/web/public/cloud/agent-settings.js @@ -8,6 +8,7 @@ const state = { secretDraft: '', secretDraftHostId: null, secretVisible: false, rotationConfirmed: false, }; +const requestRuntime = window.VenixAdminRequestRuntime.create({ csrfToken: () => state.csrf }); function notice(message, error = false) { const box = byId('agent-settings-status'); @@ -16,21 +17,9 @@ function notice(message, error = false) { } async function api(path, options = {}) { - const headers = { Accept: 'application/json' }; - let body; - if (options.body !== undefined) { - headers['Content-Type'] = 'application/json'; - body = JSON.stringify(options.body); - } - if (options.method && options.method !== 'GET') headers['X-Admin-CSRF-Token'] = state.csrf; - const response = await fetch(path, { - method: options.method || 'GET', headers, body, - credentials: 'same-origin', cache: 'no-store', redirect: 'error', - }); - let payload = {}; - try { payload = await response.json(); } catch {} - if (!response.ok) throw new Error(payload.error || payload.detail || 'Agent API 请求失败。'); - return payload; + const method = String(options.method || 'GET').toUpperCase(); + if (['GET', 'HEAD'].includes(method)) return requestRuntime.read(path, { method }); + return requestRuntime.mutate(path, { method, body: options.body, response: 'json' }); } function text(tag, className, value) { diff --git a/web/public/theme/venix/css/admin-home.css b/web/public/theme/venix/css/admin-home.css index d388074a..b6e21452 100644 --- a/web/public/theme/venix/css/admin-home.css +++ b/web/public/theme/venix/css/admin-home.css @@ -5,6 +5,193 @@ background: #f3f5f9; } +html.admin-danger-dialog-open { + overflow: hidden; +} + +.admin-danger-dialog { + width: min(560px, calc(100vw - 32px)); + max-width: 560px; + padding: 0; + border: 0; + border-radius: 20px; + background: transparent; + color: #1f3044; + box-shadow: 0 28px 80px rgba(16, 30, 54, 0.28); +} + +.admin-danger-dialog::backdrop { + background: rgba(15, 29, 50, 0.54); + backdrop-filter: blur(3px); +} + +.admin-danger-dialog.is-dialog-fallback { + position: fixed; + inset: 50% auto auto 50%; + z-index: 1100; + transform: translate(-50%, -50%); +} + +.admin-danger-dialog-card { + overflow: hidden; + border: 1px solid #e2e9f1; + border-radius: inherit; + background: #fff; +} + +.admin-danger-dialog-header { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto; + gap: 16px; + align-items: start; + padding: 24px 24px 20px; +} + +.admin-danger-dialog-mark { + display: grid; + width: 48px; + height: 48px; + place-items: center; + border-radius: 15px; + background: #fff0f1; + color: #d83c4d; + font-size: 25px; +} + +.admin-danger-dialog[data-tone="warning"] .admin-danger-dialog-mark { + background: #fff7df; + color: #b77900; +} + +.admin-danger-dialog-heading { + min-width: 0; +} + +.admin-danger-dialog-kicker { + display: block; + margin-bottom: 4px; + color: #d83c4d; + font-size: 12px; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.admin-danger-dialog[data-tone="warning"] .admin-danger-dialog-kicker { + color: #9a6700; +} + +.admin-danger-dialog-heading h2 { + margin: 0; + color: #17283d; + font-size: 20px; + font-weight: 700; +} + +.admin-danger-dialog-heading p { + margin: 10px 0 0; + color: #61738a; + line-height: 1.7; + white-space: pre-line; +} + +.admin-danger-dialog-close { + display: grid; + width: 38px; + height: 38px; + padding: 0; + place-items: center; + border: 0; + border-radius: 12px; + background: #f2f5f8; + color: #65768a; + font-size: 20px; +} + +.admin-danger-dialog-close:hover, +.admin-danger-dialog-close:focus-visible { + background: #e7edf3; + color: #23364c; +} + +.admin-danger-dialog-verification { + margin: 0 24px 22px; + padding: 16px; + border: 1px solid #f1c7cc; + border-radius: 14px; + background: #fff8f8; +} + +.admin-danger-dialog-verification label { + display: block; + margin-bottom: 8px; + color: #384b61; + font-weight: 600; +} + +.admin-danger-dialog-verification small { + display: block; + min-height: 20px; + margin-top: 7px; + color: #7c8da1; +} + +.admin-danger-dialog-verification.is-matched { + border-color: #a7dfc4; + background: #f4fcf8; +} + +.admin-danger-dialog-verification.is-matched small { + color: #16865d; +} + +.admin-danger-dialog-verification small.is-mismatch { + color: #c43d4d; +} + +.admin-danger-dialog-actions { + display: flex; + justify-content: flex-end; + gap: 10px; + padding: 18px 24px 24px; + border-top: 1px solid #edf1f5; + background: #fbfcfd; +} + +@media (max-width: 575.98px) { + .admin-danger-dialog { + width: calc(100vw - 20px); + margin: auto; + border-radius: 18px; + } + + .admin-danger-dialog-header { + grid-template-columns: auto minmax(0, 1fr); + gap: 12px; + padding: 20px 18px 16px; + } + + .admin-danger-dialog-close { + position: absolute; + top: 14px; + right: 14px; + } + + .admin-danger-dialog-heading { + padding-right: 34px; + } + + .admin-danger-dialog-verification { + margin: 0 18px 18px; + } + + .admin-danger-dialog-actions { + display: grid; + grid-template-columns: 1fr 1fr; + padding: 16px 18px 18px; + } +} + .admin-template#app-layout { min-height: 100vh; min-height: 100dvh; diff --git a/web/resources/views/venix/admin/components/danger_dialog.tpl b/web/resources/views/venix/admin/components/danger_dialog.tpl new file mode 100644 index 00000000..e0c5eda1 --- /dev/null +++ b/web/resources/views/venix/admin/components/danger_dialog.tpl @@ -0,0 +1,22 @@ + +
+
+ +
+ 高风险操作 +

确认操作

+

+
+ +
+ +
+ + +
+
+
diff --git a/web/resources/views/venix/admin/object_storage.tpl b/web/resources/views/venix/admin/object_storage.tpl index d6a97b1c..4ff5a9c2 100644 --- a/web/resources/views/venix/admin/object_storage.tpl +++ b/web/resources/views/venix/admin/object_storage.tpl @@ -241,17 +241,5 @@ {/if} - - {include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/admin/static_footer.tpl b/web/resources/views/venix/admin/static_footer.tpl index 771a5d9a..65aa9fa1 100644 --- a/web/resources/views/venix/admin/static_footer.tpl +++ b/web/resources/views/venix/admin/static_footer.tpl @@ -12,6 +12,8 @@ +{include file='admin/components/danger_dialog.tpl'} + {literal} + {literal} ', + requiredText: 'vm-prod-01', + confirmText: '永久删除', + }); + assert.equal(test.title.textContent, dangerous); + assert.equal(test.verification.hidden, false); + assert.equal(test.confirm.disabled, true); + assert.equal(test.document.activeElement, test.input); + test.input.value = 'vm-prod-01 '; + test.input.dispatch('input'); + assert.equal(test.confirm.disabled, true); + assert.equal(test.input.getAttribute('aria-invalid'), 'true'); + test.input.value = 'vm-prod-01'; + test.input.dispatch('input'); + assert.equal(test.confirm.disabled, false); + assert.match(test.hint.textContent, /名称已匹配/); + test.form.dispatch('submit'); + assert.equal(await promise, true); +} + +// A concurrent confirmation cannot replace the active high-risk decision. +{ + const test = fixture(); + const first = test.api.confirm({ title: '第一项', message: '保持打开' }); + const firstState = await settled(first); + const second = test.api.confirm({ title: '第二项', message: '不能覆盖' }); + assert.equal(await second, false); + assert.equal(firstState().done, false); + assert.equal(test.title.textContent, '第一项'); + test.dialog.dispatch('cancel'); + assert.equal(await first, false); +} + +console.log('Administrator danger dialog behavior checks passed.'); diff --git a/web/tests/AdminHostNetworkBehaviorTest.mjs b/web/tests/AdminHostNetworkBehaviorTest.mjs index aa8c583f..2d3b9236 100644 --- a/web/tests/AdminHostNetworkBehaviorTest.mjs +++ b/web/tests/AdminHostNetworkBehaviorTest.mjs @@ -3,6 +3,8 @@ import { readFile } from 'node:fs/promises'; import vm from 'node:vm'; const adminSource = await readFile(new URL('../public/cloud/admin.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, renderHostNetworkPools, state };'; @@ -16,8 +18,10 @@ function fixture(canManage = true) { 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); } @@ -35,19 +39,26 @@ function fixture(canManage = true) { let saved = null; const context = { document: { querySelector: () => root, getElementById: get, createElement: tag => new Element(tag) }, - window: { ADMIN_CSRF_TOKEN: 'csrf-token', addEventListener() {} }, + 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, + Headers, AbortController, 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: 'csrf-token' }; + 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.js' }); return { ...context.hostUI, get, requests, writes: () => requests.filter(request => request.method !== 'GET') }; } @@ -62,7 +73,7 @@ function fixture(canManage = true) { 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-CSRF-Token'), 'csrf-token'); + 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'; diff --git a/web/tests/AdminOperationsCancelBehaviorTest.mjs b/web/tests/AdminOperationsCancelBehaviorTest.mjs index 5df95ab3..0b7380ca 100644 --- a/web/tests/AdminOperationsCancelBehaviorTest.mjs +++ b/web/tests/AdminOperationsCancelBehaviorTest.mjs @@ -60,13 +60,13 @@ assert.doesNotMatch(source, /setInterval\(/); // action with an explicit result and a 20-500 character reason; neither route // retries or changes the original task to success in the browser. assert.match(source, /\/inspect`/); -assert.match(source, /method: 'POST', body: '\{\}'/); +assert.match(source, /method: 'POST', body: \{\}/); assert.match(source, /state\.inspection\.completion_delivery_error/); assert.match(source, /infoList\(\[\['回执异常', completionDeliveryError\]\]\)/); assert.match(source, /if \(content !== undefined\) node\.textContent = String\(content\)/); assert.doesNotMatch(source, /completion_delivery_error[^\n]*innerHTML/); assert.match(source, /\/resolve-effect`/); -assert.match(source, /JSON\.stringify\(\{ resolution, reason \}\)/); +assert.match(source, /body: \{ resolution, reason \}/); assert.match(source, /reason\.length < 20 \|\| reason\.length > 500/); assert.match(shipped, /原任务仍保持失败/); assert.match(shipped, /不会重放 Agent 或支付请求/); diff --git a/web/tests/AdminRequestRuntimeBehaviorTest.mjs b/web/tests/AdminRequestRuntimeBehaviorTest.mjs new file mode 100644 index 00000000..11545832 --- /dev/null +++ b/web/tests/AdminRequestRuntimeBehaviorTest.mjs @@ -0,0 +1,165 @@ +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-request-runtime.js', import.meta.url), + 'utf8', +); + +function response(status, payload, jsonError = null) { + return { + status, + ok: status >= 200 && status < 300, + json: async () => { + if (jsonError) throw jsonError; + return payload; + }, + }; +} + +function fixture(fetchImpl, options = {}) { + const context = { + Headers, AbortController, setTimeout, clearTimeout, + console, Date, Math, Error, TypeError, Object, Array, String, Number, Promise, + }; + context.window = context; + context.globalThis = context; + vm.runInNewContext(source, context, { filename: 'admin-request-runtime.js' }); + const runtime = context.VenixAdminRequestRuntime.create({ + fetchImpl, + locationImpl: options.locationImpl || { protocol: 'https:', hostname: 'panel.test' }, + csrfToken: options.csrfToken || (() => 'a'.repeat(64)), + cryptoImpl: { randomUUID: () => '11111111-2222-4333-8444-555555555555' }, + taskReceiptValidator: payload => payload?.task_id === '42' + && payload?.status_url === '/api/v1/tasks/42', + setTimeoutImpl: options.setTimeoutImpl, + clearTimeoutImpl: options.clearTimeoutImpl, + }); + return runtime; +} + +async function rejection(promise) { + try { + await promise; + assert.fail('Expected request to reject.'); + } catch (error) { + return error; + } +} + +// Reads stay header-light and may expose status metadata only when a caller +// has an endpoint-specific protocol decision to make. +{ + const calls = []; + const runtime = fixture(async (url, options) => { + calls.push({ url, options }); + return response(200, { ok: true }); + }); + assert.deepEqual(await runtime.read('/api/read'), { ok: true }); + const metadata = await runtime.read('/api/read-meta', { returnMeta: true }); + assert.equal(metadata.status, 200); + assert.deepEqual(metadata.payload, { ok: true }); + assert.equal(calls.length, 2); + assert.equal(calls[0].options.method, 'GET'); + assert.equal(calls[0].options.headers.get('X-Admin-CSRF-Token'), null); + assert.equal(calls[0].options.headers.get('Idempotency-Key'), null); +} + +// A task mutation is sent exactly once with the canonical security and +// idempotency headers, and only a strict HTTP 202 task receipt is accepted. +{ + const calls = []; + const runtime = fixture(async (url, options) => { + calls.push({ url, options }); + return response(202, { task_id: '42', status_url: '/api/v1/tasks/42' }); + }); + const receipt = await runtime.mutate('/api/task', { + method: 'POST', body: { acknowledge: true }, response: 'task', + }); + assert.equal(receipt.task_id, '42'); + assert.equal(calls.length, 1); + assert.equal(calls[0].options.headers.get('X-Admin-CSRF-Token'), 'a'.repeat(64)); + assert.equal(calls[0].options.headers.get('Idempotency-Key'), + '11111111-2222-4333-8444-555555555555'); + assert.equal(calls[0].options.body, JSON.stringify({ acknowledge: true })); +} + +// Client-side preconditions fail before dispatch and remain safe to retry. +for (const [name, options, code] of [ + ['http', { locationImpl: { protocol: 'http:', hostname: 'panel.test' } }, 'https_required'], + ['csrf', { csrfToken: () => 'invalid' }, 'csrf_missing'], +]) { + let calls = 0; + const runtime = fixture(async () => { calls += 1; return response(200, {}); }, options); + const error = await rejection(runtime.mutate('/api/write', { body: {} })); + assert.equal(error.code, code, `${name} precondition returned the wrong error.`); + assert.equal(error.mutationMayHaveApplied, false); + assert.equal(error.safeToRetry, true); + assert.equal(calls, 0); +} + +// The two public interfaces cannot be used to bypass their security role by +// swapping safe and unsafe HTTP methods. +{ + let calls = 0; + const runtime = fixture(async () => { calls += 1; return response(200, {}); }); + await assert.rejects(runtime.read('/api/read', { method: 'POST' }), TypeError); + await assert.rejects(runtime.mutate('/api/write', { method: 'GET' }), TypeError); + assert.equal(calls, 0); +} + +// Explicit validation errors are known not to have applied; server failures, +// transport loss and protocol-invalid receipts are fenced as unknown effect. +{ + const validation = fixture(async () => response(422, { detail: '输入错误' })); + const validationError = await rejection(validation.mutate('/api/write', { body: {} })); + assert.equal(validationError.status, 422); + assert.equal(validationError.mutationMayHaveApplied, false); + assert.equal(validationError.safeToRetry, true); + + const server = fixture(async () => response(503, { detail: '暂不可用' })); + const serverError = await rejection(server.mutate('/api/write', { body: {} })); + assert.equal(serverError.mutationMayHaveApplied, true); + assert.equal(serverError.safeToRetry, false); + + let transportCalls = 0; + const transport = fixture(async () => { + transportCalls += 1; + throw new Error('connection reset'); + }); + const transportError = await rejection(transport.mutate('/api/write', { body: {} })); + assert.equal(transportCalls, 1, 'The shared runtime must never replay a mutation.'); + assert.equal(transportError.mutationMayHaveApplied, true); + assert.equal(transportError.safeToRetry, false); + + const invalidReceipt = fixture(async () => response(200, + { task_id: '42', status_url: '/api/v1/tasks/42' })); + const receiptError = await rejection(invalidReceipt.mutate('/api/task', { + body: {}, response: 'task', + })); + assert.equal(receiptError.code, 'invalid_task_receipt'); + assert.equal(receiptError.mutationMayHaveApplied, true); + assert.equal(receiptError.safeToRetry, false); +} + +// Once timeout handling begins, the mutation is still dispatched only once +// and the caller receives the unknown-effect contract. +{ + let calls = 0; + const runtime = fixture(async (url, options) => { + calls += 1; + assert.equal(options.signal.aborted, true); + throw new Error('aborted'); + }, { + setTimeoutImpl: callback => { callback(); return 1; }, + clearTimeoutImpl: () => {}, + }); + const error = await rejection(runtime.mutate('/api/slow', { body: {} })); + assert.equal(calls, 1); + assert.equal(error.code, 'timeout'); + assert.equal(error.mutationMayHaveApplied, true); + assert.equal(error.safeToRetry, false); +} + +console.log('Administrator request runtime behavior checks passed.'); diff --git a/web/tests/AdminResourceSchedulingContractTest.php b/web/tests/AdminResourceSchedulingContractTest.php index 75518329..f5842e22 100644 --- a/web/tests/AdminResourceSchedulingContractTest.php +++ b/web/tests/AdminResourceSchedulingContractTest.php @@ -135,7 +135,8 @@ $assert(str_contains($template, '{if $admin_can_manage|default:false} root, createElement: () => new Element() }, - window: { ADMIN_CSRF_TOKEN: 'csrf-token' }, + ADMIN_CSRF_TOKEN: 'a'.repeat(64), + VenixAdminDangerDialog: { confirm: async () => true }, + taskUrl: value => value?.task_id && value?.status_url ? value.status_url : '', location: { protocol: 'https:', hostname: 'panel.test', assign() {} }, - confirm: () => true, - Headers, TextEncoder, + Headers, TextEncoder, AbortController, setTimeout, clearTimeout, fetch(path, options) { return new Promise(resolve => requests.push({ path, ...options, resolve })); }, }; + context.window = context; + vm.runInNewContext(requestRuntimeSource, context, { filename: 'admin-request-runtime.js' }); vm.runInNewContext(source, context, { filename: 'admin.js' }); return { ...context.__scripts, get, requests, @@ -72,6 +77,7 @@ function fixture(canManage = true) { const repair = findText(test.get('catalog-list'), '补齐副本'); assert.ok(repair, 'A proven missing eligible replica has no repair control.'); const repairing = repair.listeners.get('click')(); + await flush(); const request = test.requests[1]; assert.equal(request.path, '/api/v1/admin/cloud-templates/debian-12-template/replicas/7/repair'); assert.equal(request.method, 'POST'); @@ -108,7 +114,7 @@ function fixture(canManage = true) { const saving = test.saveStartupScript(submit); const request = test.requests[2]; assert.equal(request.method, 'PATCH'); - assert.equal(request.headers.get('X-CSRF-Token'), 'csrf-token'); + assert.equal(request.headers.get('X-Admin-CSRF-Token'), 'a'.repeat(64)); assert.deepEqual(JSON.parse(request.body), { script: '#!/bin/bash\necho "中文"\n', expected_revision: 2, diff --git a/web/tests/CloudAgentPanelContractTest.php b/web/tests/CloudAgentPanelContractTest.php index 6e603ecf..6cfe02a5 100644 --- a/web/tests/CloudAgentPanelContractTest.php +++ b/web/tests/CloudAgentPanelContractTest.php @@ -109,7 +109,7 @@ $assert(str_contains($page, 'data-cloud-agent-settings') && !str_contains($page, 'agent-settings-endpoint') && str_contains($sidebar, 'href="/admin/agents"') && str_contains($browser, "'/api/v1/admin/agents'") - && str_contains($browser, "'X-Admin-CSRF-Token'") + && str_contains($browser, 'VenixAdminRequestRuntime.create') && str_contains($browser, 'function clearSecretDraft(') && str_contains($browser, "window.addEventListener('pagehide'"), 'Agent settings page lost navigation, permission, CSRF or secret clearing behavior.'); diff --git a/web/tests/CloudObjectStorageAdminContractTest.php b/web/tests/CloudObjectStorageAdminContractTest.php index 6bdfd418..4f0e7545 100644 --- a/web/tests/CloudObjectStorageAdminContractTest.php +++ b/web/tests/CloudObjectStorageAdminContractTest.php @@ -80,8 +80,8 @@ $assert(str_contains($template, "admin_title value='对象存储'") && str_contains($template, '$item.next_check_at') && str_contains($template, '$item.attention_at') && !str_contains($template, '') - && str_contains($template, 'id="osConfirmDialog"') - && str_contains($template, 'role="alertdialog"') + && !str_contains($template, 'id="osConfirmDialog"') + && !str_contains($template, 'role="alertdialog"') && str_contains($template, '/cloud/admin-object-storage.css?v={$venix_asset_version}') && str_contains($template, '/cloud/admin-object-storage.js?v={$venix_asset_version}') && !str_contains($template, '