refactor(admin): unify action safety runtime

go
codex 3 weeks ago
parent a167e55212
commit ff1ca4e558

@ -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));

@ -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
? '正在核对准确对象版本;只有两次间隔证据一致才会创建新的删除代次。'

@ -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({

@ -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 });
}

@ -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,

@ -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;
}

@ -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);

@ -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('退役响应与当前任务不一致。');

@ -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));

@ -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();

@ -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 = '') {

@ -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)}`, {

@ -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) {

@ -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;

@ -0,0 +1,22 @@
<dialog class="admin-danger-dialog" id="admin-danger-dialog" aria-modal="true" aria-labelledby="admin-danger-dialog-title" aria-describedby="admin-danger-dialog-message admin-danger-dialog-verification-hint">
<form class="admin-danger-dialog-card" id="admin-danger-dialog-form" method="dialog" novalidate>
<header class="admin-danger-dialog-header">
<span class="admin-danger-dialog-mark" aria-hidden="true"><i class="mdi mdi-shield-alert-outline"></i></span>
<div class="admin-danger-dialog-heading">
<span class="admin-danger-dialog-kicker">高风险操作</span>
<h2 id="admin-danger-dialog-title">确认操作</h2>
<p id="admin-danger-dialog-message"></p>
</div>
<button class="admin-danger-dialog-close" id="admin-danger-dialog-close" type="button" aria-label="关闭确认窗口"><i class="mdi mdi-close" aria-hidden="true"></i></button>
</header>
<div class="admin-danger-dialog-verification" id="admin-danger-dialog-verification" hidden>
<label id="admin-danger-dialog-verification-label" for="admin-danger-dialog-verification-input">输入完整名称以确认</label>
<input class="form-control" id="admin-danger-dialog-verification-input" type="text" autocomplete="off" spellcheck="false" aria-describedby="admin-danger-dialog-verification-hint">
<small id="admin-danger-dialog-verification-hint" aria-live="polite"></small>
</div>
<footer class="admin-danger-dialog-actions">
<button class="btn btn-light" id="admin-danger-dialog-cancel" type="button">取消</button>
<button class="btn btn-danger" id="admin-danger-dialog-confirm" type="submit">确认</button>
</footer>
</form>
</dialog>

@ -241,17 +241,5 @@
</div>
{/if}
<div class="os-confirm-layer" id="osConfirmDialog" hidden>
<button class="os-confirm-backdrop" type="button" data-os-confirm-cancel aria-label="取消操作"></button>
<section class="os-confirm-dialog" role="alertdialog" aria-modal="true" aria-labelledby="osConfirmTitle" aria-describedby="osConfirmMessage" tabindex="-1">
<span class="os-confirm-icon"><i class="mdi mdi-alert-outline"></i></span>
<div class="os-confirm-copy"><h2 id="osConfirmTitle">确认操作</h2><p id="osConfirmMessage"></p></div>
<div class="os-confirm-actions">
<button class="btn btn-light" type="button" data-os-confirm-cancel>取消</button>
<button class="btn btn-danger" id="osConfirmSubmit" type="button">确认</button>
</div>
</section>
</div>
<script src="/cloud/admin-object-storage.js?v={$venix_asset_version}"></script>
{include file='admin/static_footer.tpl'}

@ -12,6 +12,8 @@
</footer>
</div>
</div>
{include file='admin/components/danger_dialog.tpl'}
<script src="/cloud/admin-danger-dialog.js?v={$venix_asset_version}"></script>
{literal}
<script>
(function () {

@ -14,6 +14,7 @@
{if isset($admin_extra_css)}{$admin_extra_css}{/if}
<script>window.ADMIN_CSRF_TOKEN = '{$admin_csrf_token|default:''|escape:"javascript"}';</script>
<script src="/theme/venix/js/admin-csrf.js?v={$venix_asset_version}"></script>
<script src="/cloud/admin-request-runtime.js?v={$venix_asset_version}"></script>
<script src="/cloud/drawer-motion.js?v={$venix_asset_version}"></script>
{literal}
<script>

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

@ -2,6 +2,9 @@ import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
const source = await readFile(new URL('../public/cloud/admin.js', import.meta.url), 'utf8');
const requestRuntime = await readFile(
new URL('../public/cloud/admin-request-runtime.js', import.meta.url), 'utf8',
);
globalThis.location = { href: 'https://panel.test/admin/cloud', origin: 'https://panel.test' };
const { taskUrl } = await import('../public/cloud/task-observer.js');
@ -9,7 +12,9 @@ const { taskUrl } = await import('../public/cloud/task-observer.js');
// strict helper. Existing synchronous and hybrid endpoints continue through
// api(), so their 200 responses remain valid.
assert.match(source, /async function acceptedTask\(path, options = \{\}\)/);
assert.match(source, /status !== 202 \|\| !taskUrl\(payload\)/);
assert.match(source, /response: 'task'/);
assert.match(source, /taskReceiptValidator: taskUrl/);
assert.match(requestRuntime, /response\.status !== 202 \|\| !taskReceiptValidator/);
assert.match(source, /taskSucceededWithoutRecovery, taskUrl/);
assert.equal(taskUrl({ task_id: 42, status_url: '/api/v1/tasks/42' }), '/api/v1/tasks/42');
assert.equal(taskUrl({ task_id: 42, status_url: '/api/v1/tasks/42', status: 'active' }), '');
@ -34,7 +39,7 @@ assert.match(storageObserver, /旧任务已终止且不会重放/);
assert.doesNotMatch(storageObserver, /task\.safe_to_resubmit/);
assert.doesNotMatch(storage + storageObserver, /setInterval\(/);
const catalog = source.slice(source.indexOf('async function loadCatalog'), source.indexOf('function taskFailureMessage'));
const catalog = source.slice(source.indexOf('function bindCloudTemplateActions'), source.indexOf('function cloudTemplateVersion'));
assert.match(catalog, /acceptedTask\(`\$\{catalogPath\(\)\}\/\$\{encodeURIComponent\(entry\.id\)\}`/);
assert.match(catalog, /importProgress\(receipt, '同步镜像名称'/);
assert.match(catalog, /await loadCatalog\(\);\s*notice\('名称已保存。'\);/);

@ -0,0 +1,79 @@
<?php
$root = dirname(__DIR__);
$read = static function (string $path) use ($root): string {
$contents = file_get_contents($root . '/' . $path);
if ($contents === false) {
throw new RuntimeException('Unable to read ' . $path);
}
return $contents;
};
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$header = $read('resources/views/venix/admin/static_header.tpl');
$footer = $read('resources/views/venix/admin/static_footer.tpl');
$dialog = $read('resources/views/venix/admin/components/danger_dialog.tpl');
$runtime = $read('public/cloud/admin-request-runtime.js');
$dialogRuntime = $read('public/cloud/admin-danger-dialog.js');
$assets = $read('resources/views/venix/layout_assets.tpl');
$assert(substr_count($header,
'/cloud/admin-request-runtime.js?v={$venix_asset_version}') === 1,
'The administrator shell must load the shared request runtime exactly once.');
$assert(substr_count($footer,
"{include file='admin/components/danger_dialog.tpl'}") === 1
&& substr_count($footer,
'/cloud/admin-danger-dialog.js?v={$venix_asset_version}') === 1,
'The administrator shell must own one shared dangerous-action dialog.');
$assert(substr_count($dialog, 'id="admin-danger-dialog"') === 1
&& str_contains($dialog, 'aria-labelledby="admin-danger-dialog-title"')
&& str_contains($dialog, 'aria-describedby="admin-danger-dialog-message admin-danger-dialog-verification-hint"')
&& str_contains($dialog, 'aria-live="polite"'),
'The shared dangerous-action dialog lost its accessible identity or verification feedback.');
$assert(str_contains($runtime, "headers.set('X-Admin-CSRF-Token', token)")
&& str_contains($runtime, "headers.set('Idempotency-Key', idempotencyKey)")
&& str_contains($runtime, "responseKind === 'task'")
&& str_contains($runtime, "mutationMayHaveApplied: true")
&& !str_contains($runtime, 'setInterval(')
&& !preg_match('/\b(?:retry|retries)\s*\(/', $runtime),
'The request runtime lost its canonical mutation headers, strict task receipt, or no-replay boundary.');
$assert(str_contains($dialogRuntime, 'textContent = value(config.title')
&& str_contains($dialogRuntime, 'textContent = value(config.message')
&& !str_contains($dialogRuntime, 'innerHTML')
&& str_contains($dialogRuntime, 'activeRequest')
&& str_contains($dialogRuntime, 'requiredText'),
'The dangerous-action dialog lost text-only rendering, concurrency exclusion, or typed confirmation.');
$consumers = [
'public/cloud/admin-operations.js',
'public/cloud/admin-instance-transport.js',
'public/cloud/admin-instance-migration.js',
'public/cloud/admin-instance-backups.js',
'public/cloud/admin.js',
'public/cloud/admin-vpc.js',
'public/cloud/admin-resources.js',
'public/cloud/agent-settings.js',
'public/cloud/admin-object-storage.js',
];
$combined = '';
foreach ($consumers as $consumer) {
$source = $read($consumer);
$combined .= "\n" . $source;
$assert(!str_contains($source, 'window.confirm(')
&& preg_match('/(?<![A-Za-z0-9_.])confirm\s*\(/', $source) !== 1,
'A migrated administrator surface still uses a browser-native confirm: ' . $consumer);
}
$assert(substr_count($combined, 'VenixAdminRequestRuntime') >= 6
&& substr_count($combined, 'VenixAdminDangerDialog') >= 4,
'Administrator consumers are not wired to the shared action modules.');
$assert(str_contains($combined, 'XMLHttpRequest')
&& str_contains($combined, "request.upload.addEventListener('progress'"),
'The cloud-template file upload must retain its dedicated progress transport.');
$assert(preg_match("/venix_asset_version value='2026103118'/", $assets) === 1,
'Shared administrator assets must use the current cache version.');
echo "Administrator shared action runtime contract passed.\n";

@ -0,0 +1,235 @@
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-danger-dialog.js', import.meta.url),
'utf8',
);
class FakeNode {
constructor(tag, documentRef) {
this.tagName = String(tag).toUpperCase();
this.ownerDocument = documentRef;
this.children = [];
this.parentNode = null;
this.listeners = new Map();
this.attributes = new Map();
this.dataset = {};
this.hidden = false;
this.disabled = false;
this.open = false;
this.value = '';
this._text = '';
const classes = new Set();
this.classList = {
add: (...names) => names.forEach(name => classes.add(name)),
remove: (...names) => names.forEach(name => classes.delete(name)),
contains: name => classes.has(name),
toggle: (name, force) => {
const active = force === undefined ? !classes.has(name) : Boolean(force);
if (active) classes.add(name); else classes.delete(name);
return active;
},
};
}
set id(value) { this.setAttribute('id', value); }
get id() { return this.getAttribute('id') || ''; }
set className(value) {
this.setAttribute('class', value);
String(value).split(/\s+/).filter(Boolean).forEach(name => this.classList.add(name));
}
get className() { return this.getAttribute('class') || ''; }
set textContent(value) { this._text = String(value ?? ''); }
get textContent() { return this._text; }
get isConnected() {
let node = this;
while (node) {
if (node === this.ownerDocument?.documentElement) return true;
node = node.parentNode;
}
return false;
}
append(...nodes) {
nodes.forEach(node => {
node.parentNode = this;
this.children.push(node);
});
}
setAttribute(name, value) {
this.attributes.set(String(name), String(value));
if (name === 'hidden') this.hidden = true;
}
getAttribute(name) { return this.attributes.get(String(name)) ?? null; }
hasAttribute(name) { return this.attributes.has(String(name)); }
removeAttribute(name) {
this.attributes.delete(String(name));
if (name === 'hidden') this.hidden = false;
}
addEventListener(type, listener) {
const listeners = this.listeners.get(type) || [];
listeners.push(listener);
this.listeners.set(type, listeners);
}
dispatch(type, fields = {}) {
const event = {
type,
target: fields.target || this,
currentTarget: this,
key: fields.key,
shiftKey: fields.shiftKey === true,
defaultPrevented: false,
preventDefault() { this.defaultPrevented = true; },
};
for (const listener of [...(this.listeners.get(type) || [])]) listener.call(this, event);
return event;
}
matches(selector) {
if (selector.startsWith('.')) return this.classList.contains(selector.slice(1));
return false;
}
querySelector(selector) {
for (const child of this.children) {
if (child.matches(selector)) return child;
const nested = child.querySelector(selector);
if (nested) return nested;
}
return null;
}
focus(options) {
this.ownerDocument.activeElement = this;
this.lastFocusOptions = options;
}
showModal() { this.open = true; this.setAttribute('open', ''); }
close() {
this.open = false;
this.removeAttribute('open');
this.dispatch('close');
}
}
class FakeDocument {
constructor() {
this.documentElement = new FakeNode('html', this);
this.body = new FakeNode('body', this);
this.documentElement.append(this.body);
this.activeElement = this.body;
}
createElement(tag) { return new FakeNode(tag, this); }
getElementById(id) {
const visit = node => {
if (node.id === id) return node;
for (const child of node.children) {
const match = visit(child);
if (match) return match;
}
return null;
};
return visit(this.documentElement);
}
}
function fixture() {
const document = new FakeDocument();
const make = (tag, id, className = '') => {
const node = document.createElement(tag);
node.id = id;
node.className = className;
return node;
};
const dialog = make('dialog', 'admin-danger-dialog', 'admin-danger-dialog');
const form = make('form', 'admin-danger-dialog-form');
const kicker = make('span', '', 'admin-danger-dialog-kicker');
const mark = make('span', '', 'admin-danger-dialog-mark');
const title = make('h2', 'admin-danger-dialog-title');
const message = make('p', 'admin-danger-dialog-message');
const close = make('button', 'admin-danger-dialog-close');
const cancel = make('button', 'admin-danger-dialog-cancel');
const confirm = make('button', 'admin-danger-dialog-confirm');
const verification = make('div', 'admin-danger-dialog-verification');
const input = make('input', 'admin-danger-dialog-verification-input');
const label = make('label', 'admin-danger-dialog-verification-label');
const hint = make('small', 'admin-danger-dialog-verification-hint');
verification.hidden = true;
verification.append(label, input, hint);
form.append(mark, kicker, title, message, close, verification, cancel, confirm);
dialog.append(form);
document.body.append(dialog);
const context = { document, console, Promise, Object, String, Error };
context.window = context;
context.globalThis = context;
vm.runInNewContext(source, context, { filename: 'admin-danger-dialog.js' });
return { document, dialog, form, title, message, close, cancel, confirm, verification, input, hint,
api: context.VenixAdminDangerDialog };
}
async function settled(promise) {
let result = { done: false };
promise.then(value => { result = { done: true, value }; });
await Promise.resolve();
return () => result;
}
// A normal dialog starts on the safe action, fails closed on cancellation and
// restores focus to the control that opened it.
{
const test = fixture();
const opener = test.document.createElement('button');
test.document.body.append(opener);
opener.focus();
const promise = test.api.confirm({
tone: 'warning', title: '创建修复任务', message: '不会重放旧任务。', confirmText: '继续',
});
assert.equal(test.dialog.open, true);
assert.equal(test.document.activeElement, test.cancel);
assert.equal(test.title.textContent, '创建修复任务');
assert.equal(test.message.textContent, '不会重放旧任务。');
test.cancel.dispatch('click');
assert.equal(await promise, false);
assert.equal(test.document.activeElement, opener);
}
// Typed confirmation is literal, stays disabled for near matches, renders
// caller copy as text and resolves only after an exact match.
{
const test = fixture();
const dangerous = '<img src=x onerror=alert(1)>';
const promise = test.api.confirm({
title: dangerous,
message: '<script>bad()</script>',
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.');

@ -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';

@ -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 或支付请求/);

@ -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.');

@ -135,7 +135,8 @@ $assert(str_contains($template, '{if $admin_can_manage|default:false}<button')
'Resource management controls, line switch, shared drawer and sidebar link are incomplete.');
$assert(str_contains($script, 'window.VenixDrawerMotion')
&& str_contains($script, "'X-CSRF-Token': window.ADMIN_CSRF_TOKEN")
&& str_contains($script, 'window.VenixAdminRequestRuntime.create()')
&& !str_contains($script, 'X-CSRF-Token')
&& str_contains($script, "method: id ? 'PATCH' : 'POST'")
&& str_contains($script, "method: 'PUT'")
&& !str_contains($script, 'is_super_admin')

@ -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();', '')
+ '\n;globalThis.__scripts = { startupScriptState, openStartupScript, closeStartupScript, saveStartupScript, loadCatalog };\n';
@ -38,12 +40,15 @@ function fixture(canManage = true) {
const requests = [];
const context = {
document: { getElementById: get, querySelector: () => 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,

@ -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.');

@ -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, '<table>')
&& 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, '<style>')
@ -93,7 +93,9 @@ $assert(str_contains($template, "admin_title value='对象存储'")
&& str_contains($pageJs, 'function initialize()')
&& str_contains($pageJs, 'function initializeTabs()')
&& str_contains($pageJs, 'function initializeConfigurationDrawer()')
&& str_contains($pageJs, 'function initializeConfirmation()')
&& str_contains($pageJs, 'VenixAdminRequestRuntime.create()')
&& str_contains($pageJs, 'VenixAdminDangerDialog.confirm')
&& !str_contains($pageJs, 'function initializeConfirmation()')
&& !str_contains($pageJs, 'window.confirm(')
&& preg_match("/venix_asset_version value='[0-9]+'/", $assets) === 1
&& !str_contains($template, '$item.object_version_id'),

@ -14,6 +14,10 @@ const pageSource = await readFile(
new URL('../public/cloud/admin-object-storage.js', import.meta.url),
'utf8',
);
const requestRuntimeSource = await readFile(
new URL('../public/cloud/admin-request-runtime.js', import.meta.url),
'utf8',
);
assert.match(template, /\/cloud\/admin-object-storage\.js\?v=\{\$venix_asset_version\}/);
assert.match(template, /\/cloud\/admin-object-storage\.css\?v=\{\$venix_asset_version\}/);
@ -86,15 +90,20 @@ const context = {
location: {
href: 'https://panel.test/admin/object-storage',
origin: 'https://panel.test',
protocol: 'https:',
hostname: 'panel.test',
assign() {},
reload() {},
},
setTimeout() {},
clearTimeout() {},
AbortController,
fetch(url, options) {
requests.push({ url, options });
return Promise.resolve({
ok: true,
status: 200,
text: async () => JSON.stringify({ ret: 1, msg: 'saved' }),
json: async () => ({ ret: 1, msg: 'saved' }),
});
},
console,
@ -103,11 +112,12 @@ context.window = context;
context.ADMIN_CSRF_TOKEN = 'a'.repeat(64);
vm.runInNewContext(csrfSource, context, { filename: 'admin-csrf.js' });
vm.runInNewContext(requestRuntimeSource, context, { filename: 'admin-request-runtime.js' });
vm.runInNewContext(pageSource, context, { filename: 'admin-object-storage.js' });
documentListeners.get('submit')({ target: form });
form.listeners.get('submit')({ preventDefault() {}, target: form });
await Promise.resolve();
for (let turn = 0; turn < 8; turn += 1) await Promise.resolve();
assert.equal(requests.length, 1);
assert.equal(requests[0].url, '/admin/object-storage/config');
@ -116,6 +126,8 @@ assert.equal(
context.ADMIN_CSRF_TOKEN,
'Object-storage save lost the administrator CSRF header.',
);
assert.ok(requests[0].options.headers.get('Idempotency-Key'),
'Object-storage save lost its per-submission idempotency identity.');
assert.deepEqual(JSON.parse(requests[0].options.body), {
expected_revision: '4',
name: 'Vultr Object Storage',

@ -161,8 +161,11 @@ $assert(str_contains($html, 'window.ADMIN_CSRF_TOKEN ='),
'Shared administrator CSRF bootstrap is missing from object-storage page.');
$assert($xpath->query('//details[contains(concat(" ",normalize-space(@class)," ")," os-boundaries ")]')->length === 1,
'Object-storage runtime boundaries are not available as secondary detail.');
$assert($xpath->query('//*[@id="osConfirmDialog" and @hidden]//*[@role="alertdialog"]')->length === 1
&& $xpath->query('//*[@id="osConfirmSubmit"]')->length === 1,
'Object-storage destructive actions lost the accessible in-page confirmation dialog.');
$footer = file_get_contents(dirname(__DIR__) . '/resources/views/venix/admin/static_footer.tpl');
$assert(is_string($footer)
&& str_contains($footer, "{include file='admin/components/danger_dialog.tpl'}")
&& str_contains($footer, '/cloud/admin-danger-dialog.js?v={$venix_asset_version}')
&& $xpath->query('//*[@id="osConfirmDialog"]')->length === 0,
'Object-storage destructive actions are not delegated to the shared administrator confirmation dialog.');
echo "Object-storage administrator template rendering passed.\n";

@ -153,7 +153,8 @@ $assert(str_contains($runtime,
&& str_contains($runtime, 'confirm_new_instance: true'),
'Ordinary backup creation must default to automatic filesystem consistency while maintenance migration remains crash-consistent.');
$assert(str_contains($runtime, "method: 'DELETE'")
$assert(str_contains($runtime, "mutateJson")
&& str_contains($runtime, "controller, 'DELETE'")
&& str_contains($runtime, '核对删除状态')
&& str_contains($runtime, '两次间隔证据一致')
&& str_contains($runtime, 'requires_reconciliation'),

@ -466,7 +466,7 @@ const protocolFailure = task => {
assert.match(appSource, /const assetVersion = new URL\(import\.meta\.url\)\.searchParams\.get\('v'\);/);
assert.match(appSource, /function versionedModuleUrl\(path\)/);
assert.match(appSource, /url\.searchParams\.set\('v', assetVersion\)/);
assert.match(appSource, /await import\(versionedModuleUrl\('\.\/task-center\.js'\)\)/);
assert.match(appSource, /import\(versionedModuleUrl\('\.\/task-center\.js'\)\)/);
assert.doesNotMatch(appSource, /task-center\.js\?v=[0-9]+/);
assert.match(clientCss,
/\.panel-announcements-close\.button:focus,\s*\.panel-task-close\.button:focus,\s*\.panel-account-drawer-close\.button:focus\s*\{/,
@ -510,9 +510,15 @@ const protocolFailure = task => {
assert.match(detailSource, /taskSucceededWithoutRecovery\(task\)/);
assert.doesNotMatch(detailSource, /task\.status === 'succeeded'/);
const adminInstancesSource = `${await readFile(adminInstancesUrl, 'utf8')}\n${await readFile(adminInstanceTransportUrl, 'utf8')}\n${await readFile(adminInstanceConfigurationUrl, 'utf8')}\n${await readFile(adminInstanceBackupsUrl, 'utf8')}`;
const adminInstanceTransportSource = await readFile(adminInstanceTransportUrl, 'utf8');
const adminRequestRuntimeSource = await readFile(
new URL('../public/cloud/admin-request-runtime.js', import.meta.url), 'utf8');
const adminInstancesSource = `${await readFile(adminInstancesUrl, 'utf8')}\n${adminInstanceTransportSource}\n${await readFile(adminInstanceConfigurationUrl, 'utf8')}\n${await readFile(adminInstanceBackupsUrl, 'utf8')}`;
assert.doesNotMatch(adminInstancesSource, /state\.networkRequest \|\| activeJob/);
assert.match(adminInstancesSource, /response\.status !== 202 \|\| !taskUrl\(payload\)/);
assert.match(adminInstanceTransportSource, /taskReceiptValidator: taskUrl/);
assert.match(adminInstanceTransportSource, /response: 'task'/);
assert.match(adminRequestRuntimeSource,
/response\.status !== 202 \|\| !taskReceiptValidator \|\| !taskReceiptValidator\(payload\)/);
assert.match(adminInstancesSource, /await onRefresh\?\.\(vm\.id\)/);
assert.match(adminInstancesSource, /recoveryTaskFailureNotice\(task\)/);
assert.match(adminInstancesSource, /PHP 本地账本收尾尚未完成/);

Loading…
Cancel
Save