fix(i18n): secure shared task feedback

go
codex 2 weeks ago
parent 48e2cdfbd4
commit 521df54d43

@ -15,6 +15,7 @@ const pageModules = Object.freeze({
const page = document.body.dataset.cloudPage || '';
const assetVersion = new URL(import.meta.url).searchParams.get('v');
const i18n = globalThis.VenixUserCopy;
function versionedModuleUrl(path) {
const url = new URL(path, import.meta.url);
@ -34,7 +35,7 @@ function showPageError(message) {
async function initializeCloudApp() {
const modulePath = pageModules[page];
if (!modulePath) {
showPageError('页面类型无效,请返回实例列表。');
showPageError(i18n.text('common.page.error.invalid'));
return;
}
@ -47,9 +48,9 @@ void import(versionedModuleUrl('./task-center.js')).then(module => {
module.initializeTaskCenter();
}).catch(() => {
const target = document.getElementById('panel-task-state');
if (target) target.textContent = '任务中心暂时无法加载,请刷新页面重试。';
if (target) target.textContent = i18n.text('common.tasks.error.unavailable');
});
initializeCloudApp().catch(error => {
showPageError(error?.message || '页面加载失败,请刷新后重试。');
initializeCloudApp().catch(() => {
showPageError(i18n.text('common.page.error.load_failed'));
});

@ -75,7 +75,7 @@ function firstText(...values) {
function terminalTaskProblem(task, fallback) {
const message = fallback;
if (task?.effect_may_have_applied === true) {
if (task?.recovery?.pending === true || task?.effect_may_have_applied === true) {
return t('billing.error.terminal_effect_unknown', { message });
}
return task?.safe_to_resubmit === false

@ -28,6 +28,21 @@ const state = {
readRequest: null, badgeRequest: null, csrfToken: '', reloadRequested: false,
};
class TaskCenterError extends Error {
constructor(copyKey, copyParameters = {}) {
super();
this.copyKey = copyKey;
this.copyParameters = copyParameters;
}
}
function taskCenterErrorText(error) {
if (error instanceof TaskCenterError) {
return i18n.text(error.copyKey, error.copyParameters);
}
return i18n.text('common.tasks.error.unavailable');
}
function element(tag, className = '', value = undefined) {
const node = document.createElement(tag);
node.className = className;
@ -192,7 +207,8 @@ function detailBlock(task, raw) {
if (task.recovery?.pending === true) {
append(i18n.text('common.tasks.details.recovery_status'),
i18n.text('common.tasks.recovery.continuing'));
append(i18n.text('common.tasks.details.last_error'), task.recovery.message);
append(i18n.text('common.tasks.details.last_error'),
recoveryTaskFailureNotice(task));
append(i18n.text('common.tasks.details.last_check'),
dateText(task.recovery.last_checked_at));
append(i18n.text('common.tasks.details.next_check'),
@ -240,8 +256,8 @@ function renderItems(emptyMessage = i18n.text('common.tasks.empty')) {
if (resolvedNotice) {
article.append(element('p', 'panel-task-warning', resolvedNotice));
} else {
article.append(element('p', 'panel-task-error', task.error
|| i18n.text('common.tasks.error.execution_failed')));
article.append(element('p', 'panel-task-error',
i18n.text('common.tasks.error.execution_failed')));
if (recoveryNotice) {
article.append(element('p', 'panel-task-warning', recoveryNotice));
} else if (raw?.kind === 'host_storage_configure') {
@ -352,10 +368,11 @@ async function requestPage(taskState, cursor, controller) {
});
let payload;
try { payload = await response.json(); }
catch { throw new Error(i18n.text('common.tasks.error.invalid_response')); }
catch { throw new TaskCenterError('common.tasks.error.invalid_response'); }
if (!response.ok) {
const error = new Error(payload?.error || payload?.message
|| i18n.text('common.tasks.error.unavailable_http', { status: response.status }));
const error = new TaskCenterError('common.tasks.error.unavailable_http', {
status: response.status,
});
error.status = response.status;
throw error;
}
@ -363,12 +380,12 @@ async function requestPage(taskState, cursor, controller) {
|| !validCount(payload?.active_count)
|| !validCount(payload?.recovering_count)
|| !validCount(payload?.unread_count)) {
throw new Error(i18n.text('common.tasks.error.invalid_data'));
throw new TaskCenterError('common.tasks.error.invalid_data');
}
return payload;
} catch (error) {
if (controller.signal.reason === 'timeout') {
throw new Error(i18n.text('common.tasks.error.timeout'));
throw new TaskCenterError('common.tasks.error.timeout');
}
throw error;
} finally { clearTimeout(timeout); }
@ -429,7 +446,7 @@ async function load(cursor = '', source = 'manual') {
renderItems(i18n.text('common.tasks.empty_unavailable'));
}
if (source !== 'auto' || !state.items.length) {
setMessage(error.message || i18n.text('common.tasks.error.unavailable'), 'error');
setMessage(taskCenterErrorText(error), 'error');
}
} finally {
if (serial === state.serial) {

@ -3,14 +3,17 @@ const TERMINAL_STATES = new Set(['succeeded', 'failed']);
// load the user-locale runtime. Their Chinese-only fallback is not a target
// translation; ordinary user pages resolve these keys from the publication.
const adminFallback = Object.freeze({
'common.tasks.error.protocol': '任务状态协议无效,请联系管理员核查。', // user-copy: allow admin-only-fallback
'common.tasks.error.invalid_response': '任务状态服务返回了无效数据。', // user-copy: allow admin-only-fallback
'common.tasks.error.http': '任务状态读取失败(状态码 {status})。', // user-copy: allow admin-only-fallback
'common.tasks.resolved.partial': '原任务失败;系统已确认部分宿主机已应用、部分未应用,未确认状态已收敛,资源锁已解除。', // user-copy: allow admin-only-fallback
'common.tasks.resolved.applied': '原任务失败,但系统已确认操作已应用,资源锁已解除。', // user-copy: allow admin-only-fallback
'common.tasks.resolved.not_applied': '原任务失败,但系统已确认操作未应用,资源锁已解除。', // user-copy: allow admin-only-fallback
'common.tasks.error.protocol': '任务状态协议无效,请联系管理员核查。', // user-copy: allow admin-compatibility shared administrator task transport fallback
'common.tasks.error.invalid_response': '任务状态服务返回了无效数据。', // user-copy: allow admin-compatibility shared administrator task transport fallback
'common.tasks.error.http': '任务状态读取失败(状态码 {status})。', // user-copy: allow admin-compatibility shared administrator task transport fallback
'common.tasks.error.execution_failed': '任务执行失败。', // user-copy: allow admin-compatibility shared administrator task transport fallback
'common.tasks.recovery.continuing': '持续自动核对', // user-copy: allow admin-compatibility shared administrator task transport fallback
'common.tasks.resolved.partial': '原任务失败;系统已确认部分宿主机已应用、部分未应用,未确认状态已收敛,资源锁已解除。', // user-copy: allow admin-compatibility shared administrator task transport fallback
'common.tasks.resolved.applied': '原任务失败,但系统已确认操作已应用,资源锁已解除。', // user-copy: allow admin-compatibility shared administrator task transport fallback
'common.tasks.resolved.not_applied': '原任务失败,但系统已确认操作未应用,资源锁已解除。', // user-copy: allow admin-compatibility shared administrator task transport fallback
});
const i18n = globalThis.VenixUserCopy || {
const hasUserCopyRuntime = typeof globalThis.VenixUserCopy?.text === 'function';
const i18n = hasUserCopyRuntime ? globalThis.VenixUserCopy : {
text(key, parameters = {}) {
return (adminFallback[key] || key).replace(/\{([a-z_]+)\}/g,
(match, name) => Object.prototype.hasOwnProperty.call(parameters, name)
@ -34,6 +37,24 @@ function firstText(...values) {
return '';
}
function taskErrorText(raw, status) {
if (hasUserCopyRuntime) {
return status === 'failed' ? i18n.text('common.tasks.error.execution_failed') : '';
}
return firstText(raw.error); // user-copy: allow admin-compatibility shared administrator task diagnostics
}
function recoveryMessageText(candidate) {
if (hasUserCopyRuntime) return i18n.text('common.tasks.recovery.continuing');
return firstText(candidate.message); // user-copy: allow admin-compatibility shared administrator recovery diagnostics
}
function responseErrorText(payload, status) {
if (hasUserCopyRuntime) return i18n.text('common.tasks.error.http', { status });
return firstText(payload?.error, payload?.message, payload?.detail) // user-copy: allow admin-compatibility shared administrator HTTP diagnostics
|| i18n.text('common.tasks.error.http', { status });
}
function taskIdentifier(value) {
const normalized = typeof value === 'string' ? value.trim()
: (typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? String(value) : '');
@ -90,18 +111,19 @@ export function normalizeTask(payload) {
let recovery = null;
if (terminal && Object.prototype.hasOwnProperty.call(raw, 'recovery')) {
const candidate = asObject(raw.recovery);
const message = typeof candidate.message === 'string'
const rawRecoveryMessage = typeof candidate.message === 'string'
? candidate.message.trim() : '';
const timestamp = value => value === null
? null
: (Number.isSafeInteger(value) && value > 0 ? value : undefined);
const lastCheckedAt = timestamp(candidate.last_checked_at);
const nextCheckAt = timestamp(candidate.next_check_at);
if (candidate.pending === true && message && message.length <= 400
if (candidate.pending === true && rawRecoveryMessage
&& rawRecoveryMessage.length <= 400
&& lastCheckedAt !== undefined && nextCheckAt !== undefined) {
recovery = {
pending: true,
message,
message: recoveryMessageText(candidate),
last_checked_at: lastCheckedAt,
next_check_at: nextCheckAt,
};
@ -123,7 +145,7 @@ export function normalizeTask(payload) {
effect_scope: effectScope,
recovery,
safe_to_resubmit: safeToResubmit,
error: firstText(raw.error),
error: taskErrorText(raw, status),
error_code: firstText(raw.error_code),
result: raw.result ?? null,
};
@ -197,8 +219,7 @@ export async function readTask(url, { fetchImpl = fetch, signal } = {}) {
catch { throw new Error(i18n.text('common.tasks.error.invalid_response')); }
}
if (!response.ok) {
const error = new Error(firstText(payload?.error, payload?.message, payload?.detail)
|| i18n.text('common.tasks.error.http', { status: response.status }));
const error = new Error(responseErrorText(payload, response.status));
error.status = response.status;
throw error;
}

@ -30,6 +30,10 @@ return [
$common('common.action.submitting', '提交中…', 'status'),
$common('common.action.generating', '生成中…', 'status'),
$common('common.action.resetting', '重置中…', 'status'),
$common('common.page.error.invalid',
'页面类型无效,请返回实例列表。', 'warning'),
$common('common.page.error.load_failed',
'页面加载失败,请刷新后重试。', 'warning'),
$common('common.drawer.account.description',
'管理账户资料、双重认证、登录邮箱和密码。', 'description'),

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

@ -15,7 +15,7 @@ $assert = static function (bool $condition, string $message): void {
};
$assert(is_string($assets)
&& str_contains($assets, "venix_asset_version value='2026110701'")
&& str_contains($assets, "venix_asset_version value='2026110702'")
&& is_string($cloudShell)
&& str_contains($cloudShell, '/cloud/app.js?v={$venix_asset_version}'),
'The cloud application entry must use the shared Venix asset version.');

@ -5,6 +5,10 @@ import vm from 'node:vm';
const source = (await readFile(new URL('../public/cloud/app.js', import.meta.url), 'utf8'))
.replaceAll('import.meta.url', JSON.stringify('https://panel.example.test/cloud/app.js?v=fixture'))
.replaceAll('import(', 'loadModule(');
const copyFixture = {
'common.page.error.load_failed': '页面加载失败,请刷新后重试。',
'common.tasks.error.unavailable': '任务中心暂时不可用。',
};
const tick = () => new Promise(resolve => setImmediate(resolve));
const deferred = () => {
let resolve;
@ -17,6 +21,7 @@ async function start(taskModule, pageModule) {
const nodes = new Map(['cloud-page-error', 'panel-task-state'].map(id => [id, { textContent: '', hidden: true }]));
vm.runInNewContext(source, {
URL,
VenixUserCopy: { text: key => copyFixture[key] || key },
document: { body: { dataset: { cloudPage: 'deploy' } }, getElementById: id => nodes.get(id) },
loadModule: async href => {
const path = new URL(href).pathname;
@ -53,8 +58,12 @@ async function start(taskModule, pageModule) {
const test = await start(() => ({ initializeTaskCenter() { taskReady = true; } }),
() => ({ initialize: async () => { throw new Error('fixture page failure'); } }));
assert.equal(taskReady, true);
assert.equal(test.nodes.get('cloud-page-error').textContent, 'fixture page failure',
'An asynchronous page initialization error escapes the shared error handler.');
assert.equal(test.nodes.get('cloud-page-error').textContent,
copyFixture['common.page.error.load_failed'],
'An asynchronous page initialization error did not use the safe copy catalog.');
assert.doesNotMatch(test.nodes.get('cloud-page-error').textContent,
/fixture page failure/,
'An asynchronous page initialization error escaped the shared safe-copy handler.');
}
const runtime = await readFile(new URL('../public/cloud/runtime.js', import.meta.url), 'utf8');

@ -4,6 +4,10 @@ import { readFile } from 'node:fs/promises';
globalThis.location = new URL('https://panel.example.test/user/cloud');
const copyFixture = {
'common.tasks.error.protocol': '任务状态协议无效,请联系管理员核查。',
'common.tasks.error.invalid_response': '任务状态服务返回了无效数据。',
'common.tasks.error.http': '任务状态读取失败(状态码 {status})。',
'common.tasks.error.execution_failed': '任务执行失败。',
'common.tasks.recovery.continuing': '持续自动核对',
'common.tasks.resolved.partial': '原任务失败;系统已确认部分宿主机已应用、部分未应用,未确认状态已收敛,资源锁已解除。',
'common.tasks.resolved.applied': '原任务失败,但系统已确认操作已应用,资源锁已解除。',
'common.tasks.resolved.not_applied': '原任务失败,但系统已确认操作未应用,资源锁已解除。',
@ -58,11 +62,13 @@ const protocolFailure = task => {
const running = normalizeTask({ id: '41', completed: false });
assert.equal(running.status, 'running');
assert.equal(running.terminal, false);
assert.equal(running.error, '');
for (const status of ['succeeded', 'failed']) {
const task = normalizeTask({ id: '41', completed: true, status });
assert.equal(task.status, status);
assert.equal(task.terminal, true);
assert.equal(task.error, status === 'failed' ? '任务执行失败。' : '');
assert.equal(taskSucceededWithoutRecovery(task), status === 'succeeded');
}
@ -88,14 +94,15 @@ const protocolFailure = task => {
});
assert.equal(failed.effect_may_have_applied, true);
assert.equal(failed.safe_to_resubmit, false, 'A possibly-applied task can never be resubmitted.');
assert.equal(failed.error, 'host result lost');
assert.equal(failed.error, '任务执行失败。');
assert.doesNotMatch(failed.error, /host result lost/);
assert.equal(Object.prototype.hasOwnProperty.call(failed, 'failure'), false);
const nestedOnly = normalizeTask({
id: '43', completed: true, status: 'failed',
failure: { error: 'legacy', effect_may_have_applied: true, safe_to_resubmit: true },
});
assert.equal(nestedOnly.error, '');
assert.equal(nestedOnly.error, '任务执行失败。');
assert.equal(nestedOnly.effect_may_have_applied, false);
assert.equal(nestedOnly.safe_to_resubmit, false);
@ -177,7 +184,7 @@ const protocolFailure = task => {
});
assert.deepEqual(recovering.recovery, {
pending: true,
message: 'Agent 回执与宿主机证据暂不一致;系统仍会继续自动核对。',
message: '持续自动核对',
last_checked_at: 1_600_000_000,
next_check_at: 1_600_000_030,
});
@ -198,7 +205,7 @@ const protocolFailure = task => {
assert.equal(taskSucceededWithoutRecovery(succeededWithInvalidLedger), false);
assert.equal(
recoveryTaskFailureNotice(succeededWithInvalidLedger),
succeededWithInvalidLedger.recovery.message,
'持续自动核对',
);
// A previously resolved failed task can become fenced again when its
@ -223,9 +230,21 @@ const protocolFailure = task => {
assert.equal(failedResolvedButFenced.effect_resolution, null);
assert.equal(failedResolvedButFenced.recovery?.pending, true);
assert.equal(resolvedTaskFailureNotice(failedResolvedButFenced), '');
assert.equal(recoveryTaskFailureNotice(failedResolvedButFenced), message);
assert.equal(recoveryTaskFailureNotice(failedResolvedButFenced), '持续自动核对');
assert.notEqual(recoveryTaskFailureNotice(failedResolvedButFenced), message);
}
const oversizedRecovery = normalizeTask({
id: '55', completed: true, status: 'failed',
effect_may_have_applied: true, safe_to_resubmit: false,
recovery: {
pending: true, message: 'x'.repeat(401),
last_checked_at: 1_600_000_000, next_check_at: 1_600_000_300,
},
});
assert.equal(oversizedRecovery.recovery, null,
'Catalog copy must not bypass the backend recovery-message protocol limit.');
for (const recovery of [
null,
{ pending: false, message: '伪造恢复状态' },
@ -282,6 +301,51 @@ const protocolFailure = task => {
protocolFailure(await readTask('/api/v1/tasks/1', {
fetchImpl: async () => response(200, { ret: 0, error: 'legacy envelope' }),
}));
await assert.rejects(readTask('/api/v1/tasks/1', {
fetchImpl: async () => response(503, {
error: 'raw infrastructure secret', message: 'raw backend detail',
}),
}), error => error.message === '任务状态读取失败(状态码 503)。'
&& !error.message.includes('raw'));
await assert.rejects(readTask('/api/v1/tasks/1', {
fetchImpl: async () => ({ status: 502, ok: false, json: async () => {
throw new SyntaxError('raw parser detail');
} }),
}), error => error.message === '任务状态服务返回了无效数据。');
}
// The transport is shared with the Chinese-only administrator surface. Only
// that surface may retain the already-sanitized backend diagnostic summary;
// the ordinary user runtime above must always resolve catalog copy.
{
const userRuntime = globalThis.VenixUserCopy;
globalThis.VenixUserCopy = {};
try {
const adminTasks = await import(`${observerUrl.href}?admin=${Date.now()}`);
const adminFailed = adminTasks.normalizeTask({
id: '56', completed: true, status: 'failed', error: 'admin diagnostic',
});
assert.equal(adminFailed.error, 'admin diagnostic');
const adminRecovering = adminTasks.normalizeTask({
id: '57', completed: true, status: 'failed',
effect_may_have_applied: true, safe_to_resubmit: false,
recovery: {
pending: true, message: 'admin recovery diagnostic',
last_checked_at: 1_600_000_000, next_check_at: 1_600_000_300,
},
});
assert.equal(adminRecovering.recovery.message, 'admin recovery diagnostic');
await assert.rejects(adminTasks.readTask('/api/v1/tasks/1', {
fetchImpl: async () => ({
status: 503, ok: false,
json: async () => ({ error: 'admin HTTP diagnostic' }),
}),
}), error => error.message === 'admin HTTP diagnostic');
} finally {
globalThis.VenixUserCopy = userRuntime;
}
}
// Reproduce hidden -> visible before the aborted request's finally block. The
@ -466,6 +530,12 @@ const protocolFailure = task => {
assert.match(source, /common\.tasks\.details\.next_check/);
assert.match(source, /common\.tasks\.status\.ledger_error/);
assert.match(source, /common\.tasks\.details\.duration/);
assert.match(source, /common\.tasks\.error\.execution_failed/);
assert.match(source, /common\.tasks\.error\.unavailable_http/);
assert.match(source, /recoveryTaskFailureNotice\(task\)/);
assert.doesNotMatch(source, /task\.error(?!_)/);
assert.doesNotMatch(source, /task\.recovery\.message/);
assert.doesNotMatch(source, /payload\?\.(?:error|message|detail)/);
assert.doesNotMatch(source, /复制任务编号|copyButton|panel-task-copy/);
assert.doesNotMatch(source, /重试任务|重新提交任务|data-task-retry/);
@ -473,6 +543,9 @@ const protocolFailure = task => {
assert.match(observerSource, /common\.tasks\.resolved\.partial/);
assert.match(observerSource, /common\.tasks\.resolved\.applied/);
assert.match(observerSource, /common\.tasks\.resolved\.not_applied/);
assert.match(observerSource,
/typeof globalThis\.VenixUserCopy\?\.text === 'function'/);
assert.match(observerSource, /user-copy: allow admin-compatibility/);
assert.doesNotMatch(observerSource, /finalization_error_code/);
const appSource = await readFile(appUrl, 'utf8');
@ -508,9 +581,11 @@ const protocolFailure = task => {
{
const detailSource = await readFile(detailUrl, 'utf8');
assert.match(detailSource, /resolvedTaskFailureNotice\(task\)/);
assert.match(detailSource, /resolvedTaskFailureNotice\(normalizeTask\(entry\)\)/);
assert.match(detailSource, /recoveryTaskFailureNotice\(task\)/);
assert.match(detailSource, /recoveryTaskFailureNotice\(normalizeTask\(entry\)\)/);
assert.match(detailSource, /const normalizedTask = normalizeTask\(entry\)/);
assert.match(detailSource, /resolvedTaskFailureNotice\(normalizedTask\)/);
assert.match(detailSource, /normalizedTask\.recovery\?\.pending === true/);
assert.match(detailSource, /taskFailureMessage\(normalizedTask\)/);
assert.match(detailSource, /task\?\.recovery\?\.pending === true/);
assert.match(detailSource, /task\.effect_resolution === 'applied'/);
assert.match(detailSource, /task\.effect_resolution === 'not_applied'/);
const firewallReceipt = detailSource.indexOf('expectedStatus: 202', detailSource.indexOf('async function saveVmFirewall'));
@ -544,7 +619,9 @@ const protocolFailure = task => {
const runtimeSource = await readFile(runtimeUrl, 'utf8');
assert.match(runtimeSource, /resolvedTaskFailureNotice\(task\)/);
assert.match(runtimeSource, /recoveryTaskFailureNotice\(task\)/);
assert.match(runtimeSource, /function taskFailureMessage\(task/);
assert.match(runtimeSource,
/task\?\.recovery\?\.pending === true \|\| task\?\.effect_may_have_applied/);
assert.match(runtimeSource, /task\.effect_resolution === 'applied'/);
assert.match(runtimeSource, /task\.effect_resolution === 'not_applied'/);
assert.match(runtimeSource, /expectedStatus: 202, requireTaskReceipt: true/);
@ -596,7 +673,9 @@ const protocolFailure = task => {
/taskSucceededWithoutRecovery\(task\)/);
const invoiceDetailRuntimeSource = await readFile(invoiceDetailRuntimeUrl, 'utf8');
assert.match(invoiceDetailRuntimeSource, /taskSucceededWithoutRecovery\(task\)/);
assert.match(invoiceDetailRuntimeSource, /recoveryTaskFailureNotice\(task\)/);
assert.match(invoiceDetailRuntimeSource, /function terminalTaskProblem\(task/);
assert.match(invoiceDetailRuntimeSource,
/task\?\.recovery\?\.pending === true \|\| task\?\.effect_may_have_applied === true/);
assert.doesNotMatch(invoiceDetailRuntimeSource, /task\.status === 'succeeded'/);
const reinstallView = await readFile(reinstallViewUrl, 'utf8');

Loading…
Cancel
Save