refactor(admin): unify action safety runtime
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));
|
||||
@ -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>
|
||||
@ -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'}
|
||||
|
||||
@ -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.');
|
||||
@ -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.');
|
||||
Loading…
Reference in New Issue