diff --git a/web/public/cloud/iso-images.js b/web/public/cloud/iso-images.js index 3682ce26..628ad406 100644 --- a/web/public/cloud/iso-images.js +++ b/web/public/cloud/iso-images.js @@ -12,18 +12,21 @@ const [taskObserver, runtime] = await Promise.all([ import(versionedModuleUrl('/cloud/runtime.js')), ]); const { - announceTaskAccepted, observeTask, recoveryTaskFailureNotice, taskUrl, + announceTaskAccepted, observeTask, taskUrl, taskSucceededWithoutRecovery, } = taskObserver; const { api, bindPageCleanup, byId, initializeSession, readBootstrap, showError, state, toast, } = runtime; const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options) ?? Promise.resolve(false); +const i18n = globalThis.VenixUserCopy; +const t = (key, parameters = {}) => i18n.text(key, parameters); const pageState = { isos: [], canImport: true, busy: false, stopped: false, loadEpoch: 0, loadController: null, activeStatusUrl: '', importObserver: null, observers: new Set(), + uncertainMutations: new Set(), }; function element(tag, className = '', content = '') { @@ -34,12 +37,28 @@ function element(tag, className = '', content = '') { } function formatBytes(value) { - let amount = Number(value); - if (!Number.isFinite(amount) || amount < 0) return '大小未知'; - const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB']; - let index = 0; - while (amount >= 1024 && index < units.length - 1) { amount /= 1024; index += 1; } - return `${amount.toFixed(index === 0 ? 0 : amount < 10 ? 2 : 1)} ${units[index]}`; + const amount = Number(value); + return Number.isFinite(amount) && amount >= 0 + ? i18n.bytes(amount) : t('isos.error.size_unknown'); +} + +function isoMutationMayHaveApplied(error) { + const status = Number(error?.status); + return error?.mutationMayHaveApplied === true + || ![400, 401, 403, 404, 409, 422].includes(status); +} + +function safeIsoError(error, fallbackKey, mutation = false) { + if (mutation && isoMutationMayHaveApplied(error)) return t('isos.error.mutation_unknown'); + const status = Number(error?.status); + const byStatus = { + 401: 'isos.error.login_expired', 403: 'isos.error.forbidden', + 404: 'isos.error.not_found', 409: 'isos.error.conflict', + 422: 'isos.error.invalid_input', 503: 'isos.error.unavailable', + }; + if (byStatus[status]) return t(byStatus[status]); + return Number.isInteger(status) && status > 0 + ? t('isos.error.request', { status }) : t(fallbackKey); } function setImportStatus(message, failed = false) { @@ -52,8 +71,8 @@ function setImportStatus(message, failed = false) { function updateImportAvailability() { const running = Boolean(pageState.activeStatusUrl); const availability = byId('user-iso-availability'); - const message = running ? '已有 ISO 下载任务正在执行,完成前不能再次导入。' - : !pageState.canImport ? '账户的套餐购买及 ISO 上传服务已被管理员停用。' : ''; + const message = running ? t('isos.availability.running') + : !pageState.canImport ? t('isos.availability.disabled') : ''; availability.textContent = message; availability.hidden = !message; byId('user-iso-submit').disabled = pageState.busy || running || !pageState.canImport; @@ -62,16 +81,20 @@ function updateImportAvailability() { function renderIsos() { const container = byId('user-iso-list'); if (!pageState.isos.length) { - container.replaceChildren(element('p', 'muted', '还没有个人 ISO 镜像。')); + container.replaceChildren(element('p', 'muted', t('isos.empty'))); return; } const rows = pageState.isos.map(record => { const row = element('article', 'user-iso-row'); const details = element('div', 'user-iso-details'); const fingerprint = String(record.sha256 || ''); - details.append(element('strong', '', record.name || '未命名 ISO'), - element('small', '', `${formatBytes(record.size_bytes)}${fingerprint ? ` · SHA-256 ${fingerprint.slice(0, 12)}…` : ''}`)); - const canDelete = record.can_delete === true; + details.append(element('strong', '', record.name || t('isos.item.unnamed')), + element('small', '', fingerprint + ? t('isos.item.summary_digest', { + size: formatBytes(record.size_bytes), digest: fingerprint.slice(0, 12), + }) : formatBytes(record.size_bytes))); + const locallyUncertain = pageState.uncertainMutations.has(String(record.id)); + const canDelete = record.can_delete === true && !locallyUncertain; const cleanupReason = String(record.cleanup_reason || ''); const quotaCleanup = canDelete && cleanupReason === 'quota_exceeded_after_import'; @@ -79,36 +102,39 @@ function renderIsos() { const partialDeleteCleanup = canDelete && cleanupReason === 'partial_delete'; const partialCleanup = partialImportCleanup || partialDeleteCleanup; if (quotaCleanup) { - details.append(element('small', '', '该 ISO 已下载到宿主机,但导入后超出个人库配额;可删除以释放空间。')); + details.append(element('small', '', t('isos.item.cleanup.quota'))); } else if (partialImportCleanup) { - details.append(element('small', '', '部分宿主机已完成导入、部分未导入;可清理已存在的剩余副本。')); + details.append(element('small', '', t('isos.item.cleanup.partial_import'))); } else if (partialDeleteCleanup) { - details.append(element('small', '', '部分宿主机已删除、部分仍保留副本;可继续清理剩余副本。')); + details.append(element('small', '', t('isos.item.cleanup.partial_delete'))); } - const remove = element('button', 'row-button user-iso-delete', '删除'); + const remove = element('button', 'row-button user-iso-delete', t('isos.action.delete')); remove.type = 'button'; - if (quotaCleanup || partialCleanup) remove.textContent = '清理'; + if (quotaCleanup || partialCleanup) remove.textContent = t('isos.action.cleanup'); remove.disabled = !canDelete; if (!canDelete) { - remove.textContent = String(record.state || '') === 'deleting' ? '删除中' : '不可删除'; - remove.title = ['import_failed', 'delete_failed'].includes(String(record.state || '')) - ? '此前任务已失败,资源状态由服务端锁定,请联系管理员核查。' - : 'ISO 当前状态不允许删除。'; + remove.textContent = String(record.state || '') === 'deleting' + ? t('isos.action.deleting') : t('isos.action.unavailable'); + remove.title = locallyUncertain + || ['import_failed', 'delete_failed'].includes(String(record.state || '')) + ? t('isos.action.locked.tooltip') : t('isos.action.unavailable.tooltip'); } remove.addEventListener('click', async () => { if (!canDelete) return; const isoName = record.name || record.id; const confirmed = await requestUserConfirmation({ - title: quotaCleanup ? '清理已下载 ISO' - : partialCleanup ? '清理剩余 ISO 副本' : '删除个人 ISO', + title: quotaCleanup ? t('isos.confirm.cleanup_downloaded.title') + : partialCleanup ? t('isos.confirm.cleanup_partial_import.title') + : t('isos.confirm.delete.title'), message: quotaCleanup - ? `“${isoName}”已下载到宿主机,但导入后超出个人库配额。确定删除其宿主机副本并释放空间?` + ? t('isos.confirm.cleanup_downloaded.body', { name: isoName }) : partialImportCleanup - ? `“${isoName}”仅在部分宿主机导入成功。确定清理已存在的剩余副本?未导入的宿主机不会重复执行。` + ? t('isos.confirm.cleanup_partial_import.body', { name: isoName }) : partialDeleteCleanup - ? `“${isoName}”仍有部分宿主机副本未删除。确定继续清理剩余副本?已删除的宿主机不会重复执行。` - : `确定从个人镜像库删除“${isoName}”?存在未完成账单或仍在安装的实例时,服务端会阻止删除。`, - confirmText: quotaCleanup || partialCleanup ? '清理 ISO' : '删除 ISO', + ? t('isos.confirm.cleanup_partial_delete.body', { name: isoName }) + : t('isos.confirm.delete.body', { name: isoName }), + confirmText: quotaCleanup || partialCleanup + ? t('isos.confirm.cleanup.button') : t('isos.confirm.delete.button'), tone: 'danger', }); if (!confirmed) return; @@ -117,17 +143,21 @@ function renderIsos() { const result = await api(`/api/v1/user-isos/${encodeURIComponent(record.id)}`, { method: 'DELETE', expectedStatus: 202, requireTaskReceipt: true, }); - const observer = watchTask(result, partialCleanup ? '清理 ISO' : '删除 ISO', { + const observer = watchTask(result, + partialCleanup ? t('isos.task.cleanup') : t('isos.task.delete'), { onTerminal: task => { void (async () => { const refreshed = await loadIsos({ observeActive: false }); if (!refreshed) remove.disabled = task.safe_to_resubmit !== true; if (taskSucceededWithoutRecovery(task)) { toast(partialCleanup - ? 'ISO 剩余宿主机副本已清理。' - : 'ISO 已从全局个人库删除。', 'success'); + ? t('isos.toast.cleanup.ready.body') + : t('isos.toast.delete.ready.body'), 'success', partialCleanup + ? t('isos.toast.cleanup.ready.title') + : t('isos.toast.delete.ready.title')); } else { - showError('user-iso-list-error', taskFailureMessage(task, 'ISO 删除失败。')); + showError('user-iso-list-error', + taskFailureMessage(task, 'isos.task.failure.default')); } })(); }, @@ -136,16 +166,19 @@ function renderIsos() { void (async () => { const refreshed = await loadIsos({ observeActive: false }); if (!refreshed) remove.disabled = false; - showError('user-iso-list-error', '任务自动观察已停止,已按服务端最新状态更新删除入口;请在任务中心刷新最终结果。'); + showError('user-iso-list-error', t('isos.task.delete.observer_stopped')); })(); }, }); - if (observer) toast('任务已接收,可在任务中心查看结果。', 'success', '删除 ISO'); - else showError('user-iso-list-error', '删除请求已送达,但任务回执协议无效。请勿再次提交,并联系管理员核查。'); + if (observer) toast(t('isos.toast.task_accepted.body'), 'success', partialCleanup + ? t('isos.toast.cleanup.accepted.title') : t('isos.toast.delete.accepted.title')); + else showError('user-iso-list-error', t('isos.task.receipt.invalid')); } catch (error) { - showError('user-iso-list-error', error.message); + const uncertain = isoMutationMayHaveApplied(error); + if (uncertain) pageState.uncertainMutations.add(String(record.id)); + showError('user-iso-list-error', safeIsoError(error, 'isos.error.delete', true)); const refreshed = await loadIsos({ observeActive: false }); - if (!refreshed) remove.disabled = false; + if (!refreshed && !uncertain) remove.disabled = false; } }); row.append(details, remove); @@ -168,7 +201,7 @@ async function loadIsos({ observeActive = true } = {}) { return true; } catch (error) { if (epoch === pageState.loadEpoch && error.name !== 'AbortError') { - showError('user-iso-list-error', error.message); + showError('user-iso-list-error', safeIsoError(error, 'isos.error.load')); } return false; } @@ -188,7 +221,7 @@ function applyIsoPayload(result, observeActive = true) { && taskUrl(resumedReceipt) ? activeJobId : ''; if (jobId) { pageState.activeStatusUrl = jobId; - setImportStatus(job?.phase || '正在远程下载并校验 ISO…'); + setImportStatus(t('isos.import.status.importing')); updateImportAvailability(); if (observeActive) watchImport(resumedReceipt, false); } else if (!pageState.importObserver) { @@ -198,15 +231,20 @@ function applyIsoPayload(result, observeActive = true) { } } -function taskFailureMessage(task, fallback) { - const message = task?.error || fallback; - const recoveryNotice = recoveryTaskFailureNotice(task); - if (recoveryNotice) return recoveryNotice; - if (task?.effect_may_have_applied) { - return `${message} 任务已失败,操作效果可能已经发生,相关资源已锁定。请勿再次提交,并在任务中心查看任务编号后交由管理员核查。`; +function taskFailureMessage(task, fallbackKey) { + if (task?.recovery?.pending === true) return t('isos.task.failure.recovering'); + if (task?.effect_may_have_applied === true) { + if (task.effect_resolution === 'applied' && task.effect_scope === 'partial') { + return t('isos.task.failure.resolved_partial'); + } + if (task.effect_resolution === 'applied') return t('isos.task.failure.resolved_applied'); + if (task.effect_resolution === 'not_applied') { + return t('isos.task.failure.resolved_not_applied'); + } + return t('isos.task.failure.effect_unknown'); } return task?.safe_to_resubmit === false - ? `${message} 任务已失败且相关资源已锁定,请勿再次提交,并联系管理员核查。` : message; + ? t('isos.task.failure.locked') : t(fallbackKey); } function watchTask(receipt, title, handlers = {}, accepted = true) { @@ -220,17 +258,18 @@ function watchTask(receipt, title, handlers = {}, accepted = true) { function watchImport(receipt, accepted = true) { if (pageState.importObserver?.active) return pageState.importObserver; - const handle = watchTask(receipt, '导入 ISO', { + const handle = watchTask(receipt, t('isos.task.import'), { onTerminal: task => { void (async () => { pageState.importObserver = null; pageState.activeStatusUrl = ''; await loadIsos({ observeActive: false }); if (taskSucceededWithoutRecovery(task)) { - setImportStatus('ISO 已导入全局个人库。'); - toast('ISO 已保存,可用于所有地区。', 'success'); + setImportStatus(t('isos.import.status.ready')); + toast(t('isos.toast.import.ready.body'), 'success', + t('isos.toast.import.ready.title')); } else { - const message = taskFailureMessage(task, 'ISO 下载失败。'); + const message = taskFailureMessage(task, 'isos.task.failure.default'); setImportStatus(message, true); showError('user-iso-form-error', message); } @@ -243,7 +282,7 @@ function watchImport(receipt, accepted = true) { pageState.activeStatusUrl = ''; void (async () => { await loadIsos({ observeActive: false }); - setImportStatus('任务自动观察已停止,已按服务端最新状态更新导入入口;请在任务中心刷新最终结果。', true); + setImportStatus(t('isos.import.status.observer_stopped'), true); updateImportAvailability(); })(); }, @@ -258,18 +297,20 @@ async function importIso(event) { const name = byId('user-iso-name').value.trim(); const url = byId('user-iso-url').value.trim(); let parsed; - try { parsed = new URL(url); } catch { return showError('user-iso-form-error', '请输入有效的 HTTPS ISO 直链。'); } + try { parsed = new URL(url); } catch { + return showError('user-iso-form-error', t('isos.error.url_invalid')); + } if (parsed.protocol !== 'https:' || !parsed.hostname || parsed.username || parsed.password || (parsed.port && parsed.port !== '443') || parsed.hash) { - return showError('user-iso-form-error', '仅支持无需账号、使用 443 端口且不含片段的 HTTPS ISO 直链。'); + return showError('user-iso-form-error', t('isos.error.url_policy')); } if (!parsed.pathname.toLowerCase().endsWith('.iso')) { - return showError('user-iso-form-error', '下载地址的文件名必须以 .iso 结尾。'); + return showError('user-iso-form-error', t('isos.error.url_extension')); } pageState.busy = true; updateImportAvailability(); showError('user-iso-form-error', ''); - setImportStatus('正在建立远程下载任务…'); + setImportStatus(t('isos.import.status.starting')); try { const result = await api('/api/v1/user-isos', { method: 'POST', body: { name, url }, expectedStatus: 202, requireTaskReceipt: true, @@ -278,14 +319,18 @@ async function importIso(event) { pageState.activeStatusUrl = jobId; byId('user-iso-url').value = ''; watchImport(result); - setImportStatus('任务已接收,正在后台下载;可在任务中心查看结果。'); - toast('任务已接收,可在任务中心查看结果。', 'success', '导入 ISO'); + setImportStatus(t('isos.import.status.accepted')); + toast(t('isos.toast.task_accepted.body'), 'success', + t('isos.toast.import.accepted.title')); } catch (error) { if (error.name !== 'AbortError' && !pageState.stopped) { - setImportStatus(error.message, true); - showError('user-iso-form-error', error.message); + const uncertain = isoMutationMayHaveApplied(error); + const message = safeIsoError(error, 'isos.error.import', true); + setImportStatus(message, true); + showError('user-iso-form-error', message); pageState.activeStatusUrl = ''; await loadIsos({ observeActive: false }); + if (uncertain && !pageState.activeStatusUrl) pageState.activeStatusUrl = 'unknown'; } } finally { pageState.busy = false; @@ -313,5 +358,5 @@ export async function initialize() { byId('user-iso-form')?.addEventListener('submit', importIso); if (Array.isArray(bootstrap?.isos)) applyIsoPayload(bootstrap); else await loadIsos(); - } catch (error) { showError('cloud-page-error', error.message); } + } catch { showError('cloud-page-error', t('isos.error.initialize')); } } diff --git a/web/public/cloud/ssh-keys.js b/web/public/cloud/ssh-keys.js index 55790ac7..94872107 100644 --- a/web/public/cloud/ssh-keys.js +++ b/web/public/cloud/ssh-keys.js @@ -14,8 +14,25 @@ const { toast } = await import(versionedModuleUrl('./toast.js')); // deliberately does not load the all-feature VM runtime or a session endpoint. const byId = id => document.getElementById(id); const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options) ?? Promise.resolve(false); +const i18n = globalThis.VenixUserCopy; +const t = (key, parameters = {}) => i18n.text(key, parameters); const state = { csrfToken: '', keys: [], mutationBusy: false }; +class UiCopyError extends Error { + constructor(copyKey, parameters = {}, mutationMayHaveApplied = false) { + super(copyKey); + this.copyKey = copyKey; + this.parameters = parameters; + this.mutationMayHaveApplied = mutationMayHaveApplied; + } +} + +function errorText(error, fallbackKey) { + if (error instanceof UiCopyError) return t(error.copyKey, error.parameters); + if (error?.mutationMayHaveApplied === true) return t('ssh_keys.error.mutation_unknown'); + return t(fallbackKey); +} + function showError(id, message = '') { const target = byId(id); if (!target) return; @@ -26,7 +43,7 @@ function showError(id, message = '') { function requireSecureTransport() { if (location.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) { - throw new Error('请通过 HTTPS 管理 SSH 公钥。'); + throw new UiCopyError('ssh_keys.error.secure_transport'); } } @@ -38,28 +55,46 @@ async function api(path, options = {}) { headers.set('X-CSRF-Token', state.csrfToken); if (options.body !== undefined) headers.set('Content-Type', 'application/json'); } - const response = await fetch(path, { - ...options, - method, - headers, - credentials: 'same-origin', - cache: 'no-store', - body: options.body === undefined ? undefined : JSON.stringify(options.body), - }); + const mutating = !['GET', 'HEAD'].includes(method); + let response; + try { + response = await fetch(path, { + ...options, + method, + headers, + credentials: 'same-origin', + cache: 'no-store', + body: options.body === undefined ? undefined : JSON.stringify(options.body), + }); + } catch (error) { + if (error?.name === 'AbortError') throw error; + throw new UiCopyError(mutating + ? 'ssh_keys.error.mutation_unknown' : 'ssh_keys.error.unavailable', {}, mutating); + } let payload = null; if (response.status !== 204) { try { payload = await response.json(); } - catch { throw new Error('服务返回了非 JSON 数据,请检查 PHP 及反代配置。'); } + catch { + throw new UiCopyError(mutating + ? 'ssh_keys.error.mutation_unknown' : 'ssh_keys.error.non_json', {}, mutating); + } } if (response.status === 401) { location.assign('/auth/login'); - throw new Error('登录已过期。'); + throw new UiCopyError('ssh_keys.error.login_expired'); } if (!response.ok || payload?.ret === 0) { - const detail = Array.isArray(payload?.detail) - ? payload.detail.map(item => item.msg || '输入错误').join(';') : payload?.detail; - throw new Error(String(detail || payload?.message || payload?.msg || payload?.error - || `请求失败 (${response.status})`)); + if (mutating && ![400, 401, 403, 404, 409, 422].includes(response.status)) { + throw new UiCopyError('ssh_keys.error.mutation_unknown', {}, true); + } + const byStatus = { + 403: 'ssh_keys.error.forbidden', 404: 'ssh_keys.error.not_found', + 409: 'ssh_keys.error.conflict', 422: 'ssh_keys.error.invalid_input', + 503: 'ssh_keys.error.unavailable', + }; + if (byStatus[response.status]) throw new UiCopyError(byStatus[response.status]); + if (response.ok) throw new UiCopyError('ssh_keys.error.rejected'); + throw new UiCopyError('ssh_keys.error.request', { status: response.status }); } return payload; } @@ -74,20 +109,20 @@ function normalizeKey(value) { function readBootstrap() { const source = byId('ssh-keys-bootstrap'); - if (!source) throw new Error('公钥页面初始数据缺失,请刷新后重试。'); + if (!source) throw new UiCopyError('ssh_keys.error.bootstrap_missing'); let payload; try { payload = JSON.parse(source.textContent || '{}'); } - catch { throw new Error('公钥页面初始数据无效,请刷新后重试。'); } + catch { throw new UiCopyError('ssh_keys.error.bootstrap_invalid'); } const user = payload?.user; if (!user || typeof user !== 'object' || !/^[a-f0-9]{64}$/.test(String(user.csrf_token || '')) || !/^[1-9]\d*$/.test(String(user.user_id || '')) || !Array.isArray(payload?.ssh_keys)) { - throw new Error('公钥页面初始数据不完整,请刷新后重试。'); + throw new UiCopyError('ssh_keys.error.bootstrap_incomplete'); } const keys = payload.ssh_keys.map(normalizeKey); if (keys.some(key => key === null)) { - throw new Error('公钥列表数据无效,请刷新后重试。'); + throw new UiCopyError('ssh_keys.error.list_invalid'); } state.csrfToken = String(user.csrf_token); state.keys = keys; @@ -106,10 +141,10 @@ function renderKeys() { container.replaceChildren(); if (!state.keys.length) { const empty = makeElement('div', 'ssh-keys-empty'); - const action = makeElement('a', 'button button-outline', '添加第一个公钥'); + const action = makeElement('a', 'button button-outline', t('ssh_keys.empty.action')); action.href = '/user/cloud/ssh-keys?view=add'; - empty.append(makeElement('strong', '', '还没有 SSH 公钥'), - makeElement('p', '', '添加公钥后,部署或重装实例时可以直接选择。'), action); + empty.append(makeElement('strong', '', t('ssh_keys.empty.title')), + makeElement('p', '', t('ssh_keys.empty.body')), action); container.append(empty); return; } @@ -120,7 +155,8 @@ function renderKeys() { details.append(makeElement('strong', '', key.name), makeElement('small', '', key.fingerprint)); const actions = makeElement('div', 'ssh-key-actions'); - const button = makeElement('button', 'row-button ssh-key-delete', '删除'); + const button = makeElement('button', 'row-button ssh-key-delete', + t('ssh_keys.action.delete')); button.type = 'button'; button.dataset.sshKeyDelete = key.id; actions.append(button); @@ -144,18 +180,20 @@ async function addKey(event) { if (state.mutationBusy) return; setMutationBusy(true); showError('ssh-key-form-error'); + let keepLocked = false; try { const result = await api('/api/v1/ssh-keys', { method: 'POST', body: { name: byId('ssh-key-name').value.trim(), public_key: byId('ssh-key-public-key').value.trim(), } }); const key = normalizeKey(result); - if (!key) throw new Error('公钥已保存,但服务返回的列表数据无效,请刷新页面。'); + if (!key) throw new UiCopyError('ssh_keys.error.saved_invalid'); location.assign('/user/cloud/ssh-keys'); } catch (error) { - showError('ssh-key-form-error', error?.message || '公钥保存失败,请稍后重试。'); + keepLocked = error?.mutationMayHaveApplied === true; + showError('ssh-key-form-error', errorText(error, 'ssh_keys.error.save')); } finally { - setMutationBusy(false); + if (!keepLocked) setMutationBusy(false); } } @@ -165,23 +203,26 @@ async function deleteKey(button) { const key = state.keys.find(item => item.id === id); if (!key) return; const confirmed = await requestUserConfirmation({ - title: '删除 SSH 公钥', - message: `确定删除“${key.name}”?已经创建的实例不会受到影响。`, - confirmText: '删除公钥', + title: t('ssh_keys.confirm.delete.title'), + message: t('ssh_keys.confirm.delete.body', { name: key.name }), + confirmText: t('ssh_keys.confirm.delete.button'), tone: 'danger', }); if (!confirmed) return; setMutationBusy(true); showError('ssh-keys-list-error'); + let keepLocked = false; try { await api(`/api/v1/ssh-keys/${encodeURIComponent(id)}`, { method: 'DELETE' }); state.keys = state.keys.filter(item => item.id !== id); renderKeys(); - toast('公钥已删除。', 'success'); + toast(t('ssh_keys.toast.deleted.body'), 'success', + t('ssh_keys.toast.deleted.title')); } catch (error) { - showError('ssh-keys-list-error', error?.message || '公钥删除失败,请稍后重试。'); + keepLocked = error?.mutationMayHaveApplied === true; + showError('ssh-keys-list-error', errorText(error, 'ssh_keys.error.delete')); } finally { - setMutationBusy(false); + if (!keepLocked) setMutationBusy(false); } } @@ -196,8 +237,7 @@ export function initialize() { if (button) void deleteKey(button); }); } catch (error) { - showError('cloud-page-error', error?.message - || '公钥页面初始化失败,请刷新后重试。'); + showError('cloud-page-error', errorText(error, 'ssh_keys.error.initialize')); byId('ssh-key-save-button')?.setAttribute('disabled', ''); document.querySelectorAll('[data-ssh-key-delete]').forEach(button => { button.disabled = true; diff --git a/web/resources/user-copy/entries/media-keys.entries.php b/web/resources/user-copy/entries/media-keys.entries.php new file mode 100644 index 00000000..d3d2a2cb --- /dev/null +++ b/web/resources/user-copy/entries/media-keys.entries.php @@ -0,0 +1,266 @@ + 'string', 'digest' => 'string', + ]), + $iso('isos.item.cleanup.quota', + '该 ISO 已下载到宿主机,但导入后超出个人库配额;可删除以释放空间。', + 'warning'), + $iso('isos.item.cleanup.partial_import', + '部分宿主机已完成导入、部分未导入;可清理已存在的剩余副本。', + 'warning'), + $iso('isos.item.cleanup.partial_delete', + '部分宿主机已删除、部分仍保留副本;可继续清理剩余副本。', + 'warning'), + $iso('isos.action.delete', '删除', 'button'), + $iso('isos.action.cleanup', '清理', 'button'), + $iso('isos.action.deleting', '删除中', 'status'), + $iso('isos.action.unavailable', '不可删除', 'status'), + $iso('isos.action.locked.tooltip', + '此前任务已失败,资源状态由服务端锁定,请联系管理员核查。', + 'tooltip'), + $iso('isos.action.unavailable.tooltip', 'ISO 当前状态不允许删除。', 'tooltip'), + $iso('isos.confirm.cleanup_downloaded.title', '清理已下载 ISO', 'title'), + $iso('isos.confirm.cleanup_downloaded.body', + '“{name}”已下载到宿主机,但导入后超出个人库配额。确定删除其宿主机副本并释放空间?', + 'confirmation', ['name' => 'string']), + $iso('isos.confirm.cleanup_partial_import.title', '清理剩余 ISO 副本', 'title'), + $iso('isos.confirm.cleanup_partial_import.body', + '“{name}”仅在部分宿主机导入成功。确定清理已存在的剩余副本?未导入的宿主机不会重复执行。', + 'confirmation', ['name' => 'string']), + $iso('isos.confirm.cleanup_partial_delete.body', + '“{name}”仍有部分宿主机副本未删除。确定继续清理剩余副本?已删除的宿主机不会重复执行。', + 'confirmation', ['name' => 'string']), + $iso('isos.confirm.delete.title', '删除个人 ISO', 'title'), + $iso('isos.confirm.delete.body', + '确定从个人镜像库删除“{name}”?存在未完成账单或仍在安装的实例时,服务端会阻止删除。', + 'confirmation', ['name' => 'string']), + $iso('isos.confirm.cleanup.button', '清理 ISO', 'button'), + $iso('isos.confirm.delete.button', '删除 ISO', 'button'), + $iso('isos.task.import', '导入 ISO', 'title'), + $iso('isos.task.cleanup', '清理 ISO', 'title'), + $iso('isos.task.delete', '删除 ISO', 'title'), + $iso('isos.task.failure.default', 'ISO 任务执行失败。', 'warning'), + $iso('isos.task.failure.recovering', + 'ISO 任务执行失败,系统仍在自动核对操作结果。请勿重复提交,并在任务中心查看最新状态。', + 'warning'), + $iso('isos.task.failure.effect_unknown', + 'ISO 任务已失败,操作效果可能已经发生,相关资源已锁定。请勿再次提交,并在任务中心查看任务编号后交由管理员核查。', + 'warning'), + $iso('isos.task.failure.locked', + 'ISO 任务已失败且相关资源已锁定,请勿再次提交,并联系管理员核查。', + 'warning'), + $iso('isos.task.failure.resolved_partial', + 'ISO 任务已失败;系统已确认部分宿主机已应用、部分未应用,未确认状态已收敛。请刷新列表核对最终结果。', + 'warning'), + $iso('isos.task.failure.resolved_applied', + 'ISO 任务已失败,但系统已确认操作已经应用。请刷新列表核对最终结果。', + 'warning'), + $iso('isos.task.failure.resolved_not_applied', + 'ISO 任务已失败,但系统已确认操作未应用,可以刷新后重试。', + 'warning'), + $iso('isos.task.delete.observer_stopped', + '任务自动观察已停止,已按服务端最新状态更新删除入口;请在任务中心刷新最终结果。', + 'warning'), + $iso('isos.task.receipt.invalid', + '请求已送达,但任务回执协议无效。请勿再次提交,并联系管理员核查。', + 'warning'), + $iso('isos.toast.task_accepted.body', + '任务已接收,可在任务中心查看结果。', 'toast_body', [], 'success'), + $iso('isos.toast.import.accepted.title', '导入 ISO', 'toast_title', [], 'success'), + $iso('isos.toast.delete.accepted.title', '删除 ISO', 'toast_title', [], 'success'), + $iso('isos.toast.cleanup.accepted.title', '清理 ISO', 'toast_title', [], 'success'), + $iso('isos.toast.import.ready.body', + 'ISO 已保存,可用于所有地区。', 'toast_body', [], 'success'), + $iso('isos.toast.import.ready.title', 'ISO 导入完成', 'toast_title', [], 'success'), + $iso('isos.toast.delete.ready.body', + 'ISO 已从全局个人库删除。', 'toast_body', [], 'success'), + $iso('isos.toast.delete.ready.title', 'ISO 删除完成', 'toast_title', [], 'success'), + $iso('isos.toast.cleanup.ready.body', + 'ISO 剩余宿主机副本已清理。', 'toast_body', [], 'success'), + $iso('isos.toast.cleanup.ready.title', 'ISO 清理完成', 'toast_title', [], 'success'), + $iso('isos.error.size_unknown', '大小未知', 'status'), + $iso('isos.error.url_invalid', '请输入有效的 HTTPS ISO 直链。', 'warning'), + $iso('isos.error.url_policy', + '仅支持无需账号、使用 443 端口且不含片段的 HTTPS ISO 直链。', + 'warning'), + $iso('isos.error.url_extension', + '下载地址的文件名必须以 .iso 结尾。', 'warning'), + $iso('isos.error.load', 'ISO 列表加载失败,请稍后重试。', 'warning'), + $iso('isos.error.import', 'ISO 导入失败,请稍后重试。', 'warning'), + $iso('isos.error.delete', 'ISO 删除失败,请稍后重试。', 'warning'), + $iso('isos.error.initialize', + 'ISO 页面初始化失败,请刷新后重试。', 'warning'), + $iso('isos.error.login_expired', '登录已过期,请重新登录。', 'warning'), + $iso('isos.error.forbidden', '当前账户不能执行此 ISO 操作。', 'warning'), + $iso('isos.error.not_found', 'ISO 不存在或已被删除,请刷新页面。', 'warning'), + $iso('isos.error.conflict', + 'ISO 状态已变化或已有任务正在执行,请刷新页面后重试。', 'warning'), + $iso('isos.error.invalid_input', 'ISO 输入内容无效,请检查后重试。', 'warning'), + $iso('isos.error.unavailable', 'ISO 服务暂时不可用,请稍后重试。', 'warning'), + $iso('isos.error.request', + 'ISO 请求失败(状态码 {status}),请稍后重试。', 'warning', [ + 'status' => 'integer', + ]), + $iso('isos.error.mutation_unknown', + '请求已送达,但无法确认操作结果。请勿重复提交,并前往任务中心核对。', + 'warning'), + + $ssh('ssh_keys.add.eyebrow', '添加 SSH 公钥'), + $ssh('ssh_keys.add.title', '添加 SSH 公钥', 'title'), + $ssh('ssh_keys.add.description', '填写名称并粘贴 OpenSSH 公钥内容。', 'description'), + $ssh('ssh_keys.add.back', '返回公钥列表', 'navigation'), + $ssh('ssh_keys.add.panel.title', '添加公钥', 'title'), + $ssh('ssh_keys.add.panel.description', + '仅粘贴单行 OpenSSH 公钥;不要填写私钥或私钥口令。', + 'description'), + $ssh('ssh_keys.form.name.label', '公钥名称'), + $ssh('ssh_keys.form.name.placeholder', '例如 我的电脑', 'placeholder'), + $ssh('ssh_keys.form.key.label', 'OpenSSH 公钥'), + $ssh('ssh_keys.form.key.placeholder', 'ssh-ed25519 AAAA…', 'placeholder'), + $ssh('ssh_keys.form.save', '保存公钥', 'button'), + $ssh('ssh_keys.list.eyebrow', '账户 SSH 公钥'), + $ssh('ssh_keys.list.title', 'SSH 公钥', 'title'), + $ssh('ssh_keys.list.description', + '查看当前已经添加的 SSH 公钥;创建云镜像实例时可以直接选择。', + 'description'), + $ssh('ssh_keys.list.add', '+ 添加公钥', 'button'), + $ssh('ssh_keys.list.panel.title', '当前已添加的 SSH 公钥', 'title'), + $ssh('ssh_keys.list.panel.description', + '公钥不会向其他用户显示;删除后,不影响已经创建的实例。', + 'description'), + $ssh('ssh_keys.list.aria', '已保存的 SSH 公钥列表', 'aria_label'), + $ssh('ssh_keys.empty.title', '还没有 SSH 公钥', 'empty_state'), + $ssh('ssh_keys.empty.body', + '添加公钥后,部署或重装实例时可以直接选择。', 'empty_state'), + $ssh('ssh_keys.empty.action', '添加第一个公钥', 'button'), + $ssh('ssh_keys.action.delete', '删除', 'button'), + $ssh('ssh_keys.confirm.delete.title', '删除 SSH 公钥', 'title'), + $ssh('ssh_keys.confirm.delete.body', + '确定删除“{name}”?已经创建的实例不会受到影响。', + 'confirmation', ['name' => 'string']), + $ssh('ssh_keys.confirm.delete.button', '删除公钥', 'button'), + $ssh('ssh_keys.noscript', + '已保存的公钥可以正常查看;新增或删除公钥需要启用 JavaScript。', + 'notice'), + $ssh('ssh_keys.toast.deleted.body', + '公钥已删除。', 'toast_body', [], 'success'), + $ssh('ssh_keys.toast.deleted.title', + 'SSH 公钥已删除', 'toast_title', [], 'success'), + $ssh('ssh_keys.error.secure_transport', + '请通过 HTTPS 管理 SSH 公钥。', 'warning'), + $ssh('ssh_keys.error.non_json', + '公钥服务返回了无效数据,请稍后重试。', 'warning'), + $ssh('ssh_keys.error.unavailable', + '公钥服务暂时不可用,请稍后重试。', 'warning'), + $ssh('ssh_keys.error.login_expired', '登录已过期,请重新登录。', 'warning'), + $ssh('ssh_keys.error.forbidden', '当前账户不能执行此公钥操作。', 'warning'), + $ssh('ssh_keys.error.not_found', 'SSH 公钥不存在或已被删除。', 'warning'), + $ssh('ssh_keys.error.conflict', + '该公钥已存在或公钥状态已变化,请刷新页面后重试。', 'warning'), + $ssh('ssh_keys.error.invalid_input', + '公钥输入内容无效,请检查名称和 OpenSSH 公钥后重试。', + 'warning'), + $ssh('ssh_keys.error.request', + '公钥请求失败(状态码 {status}),请稍后重试。', 'warning', [ + 'status' => 'integer', + ]), + $ssh('ssh_keys.error.rejected', + '公钥请求未被接受,请检查输入或刷新页面后重试。', 'warning'), + $ssh('ssh_keys.error.mutation_unknown', + '请求可能已经生效,但无法确认结果。请先刷新公钥列表,不要立即重复提交。', + 'warning'), + $ssh('ssh_keys.error.bootstrap_missing', + '公钥页面初始数据缺失,请刷新后重试。', 'warning'), + $ssh('ssh_keys.error.bootstrap_invalid', + '公钥页面初始数据无效,请刷新后重试。', 'warning'), + $ssh('ssh_keys.error.bootstrap_incomplete', + '公钥页面初始数据不完整,请刷新后重试。', 'warning'), + $ssh('ssh_keys.error.list_invalid', + '公钥列表数据无效,请刷新后重试。', 'warning'), + $ssh('ssh_keys.error.saved_invalid', + '公钥已保存,但服务返回的列表数据无效,请刷新页面。', 'warning'), + $ssh('ssh_keys.error.save', '公钥保存失败,请稍后重试。', 'warning'), + $ssh('ssh_keys.error.delete', '公钥删除失败,请稍后重试。', 'warning'), + $ssh('ssh_keys.error.initialize', + '公钥页面初始化失败,请刷新后重试。', 'warning'), +]; diff --git a/web/resources/views/venix/cloud/pages/isos.tpl b/web/resources/views/venix/cloud/pages/isos.tpl index ef1bb3fd..710bc685 100644 --- a/web/resources/views/venix/cloud/pages/isos.tpl +++ b/web/resources/views/venix/cloud/pages/isos.tpl @@ -1,25 +1,25 @@
-
PERSONAL INSTALL MEDIA

ISO 镜像

从 HTTPS 直链导入并保存到个人 ISO 库;此功能仅在管理员开放期间可用。

返回实例
+
{user_copy key='isos.eyebrow'}

{user_copy key='isos.title'}

{user_copy key='isos.description'}

{user_copy key='isos.back'}
-
↓

远程下载 ISO

填写可直接下载的 HTTPS 地址,完成后可用于全部宿主机。

+
↓

{user_copy key='isos.import.title'}

{user_copy key='isos.import.description'}

- - - - - 仅支持无需登录、不会跳转的公网 HTTPS 直链,URL 路径的文件名必须以 .iso 结尾;每个用户最多保存 5 个,个人 ISO 库累计和单文件均不得超过 10 GiB。超出限额会停止下载并提示,离开页面不会取消后台任务。 -

{if !empty($cloud_iso_view.import_active)}已有 ISO 下载任务正在执行,完成前不能再次导入。{elseif empty($cloud_iso_view.can_import)}账户的套餐购买及 ISO 上传服务已被管理员停用。{/if}

+ + + + + {user_copy key='isos.form.hint'} +

{if !empty($cloud_iso_view.import_active)}{user_copy key='isos.availability.running'}{elseif empty($cloud_iso_view.can_import)}{user_copy key='isos.availability.disabled'}{/if}

- +
-
◉

我的 ISO

这里只显示当前账户的全局 ISO,其他用户无法查看或使用。

+
◉

{user_copy key='isos.list.title'}

{user_copy key='isos.list.description'}

-
- {foreach $cloud_iso_view.items|default:[] as $iso}
{$iso.name|escape:'html'}{$iso.size_display|escape:'html'}{$iso.fingerprint_display|escape:'html'}
{foreachelse}

还没有个人 ISO 镜像。

{/foreach} +
+ {foreach $cloud_iso_view.items|default:[] as $iso}
{if $iso.name|default:'' != ''}{$iso.name|escape:'html'}{else}{user_copy key='isos.item.unnamed'}{/if}{if $iso.sha256|default:'' != ''}{user_copy key='isos.item.summary_digest' size=$iso.size_display digest=$iso.sha256|truncate:12:''}{else}{$iso.size_display|escape:'html'}{/if}
{foreachelse}

{user_copy key='isos.empty'}

{/foreach}
diff --git a/web/resources/views/venix/cloud/pages/keys.tpl b/web/resources/views/venix/cloud/pages/keys.tpl index 01f20698..ba7ea79a 100644 --- a/web/resources/views/venix/cloud/pages/keys.tpl +++ b/web/resources/views/venix/cloud/pages/keys.tpl @@ -1,23 +1,23 @@
{if $cloud_ssh_keys_view == 'add'} -
ADD SSH KEY

添加 SSH 公钥

填写名称并粘贴 OpenSSH 公钥内容。

返回公钥列表
+
{user_copy key='ssh_keys.add.eyebrow'}

{user_copy key='ssh_keys.add.title'}

{user_copy key='ssh_keys.add.description'}

{user_copy key='ssh_keys.add.back'}
-
+

添加公钥

仅粘贴单行 OpenSSH 公钥;不要填写私钥或私钥口令。

+
+

{user_copy key='ssh_keys.add.panel.title'}

{user_copy key='ssh_keys.add.panel.description'}

- - + + - +
{else} -
ACCOUNT SSH KEYS

SSH 公钥

查看当前已经添加的 SSH 公钥;创建云镜像实例时可以直接选择。

+ 添加公钥
+
{user_copy key='ssh_keys.list.eyebrow'}

{user_copy key='ssh_keys.list.title'}

{user_copy key='ssh_keys.list.description'}

{user_copy key='ssh_keys.list.add'}
-
⌑

当前已添加的 SSH 公钥

公钥不会向其他用户显示;删除后,不影响已经创建的实例。

+
⌑

{user_copy key='ssh_keys.list.panel.title'}

{user_copy key='ssh_keys.list.panel.description'}

-
+
{if empty($cloud_ssh_keys)} -
还没有 SSH 公钥

添加公钥后,部署或重装实例时可以直接选择。

添加第一个公钥
+
{user_copy key='ssh_keys.empty.title'}

{user_copy key='ssh_keys.empty.body'}

{user_copy key='ssh_keys.empty.action'}
{else} {foreach $cloud_ssh_keys as $key}
@@ -26,7 +26,7 @@ {$key.fingerprint|escape:"html"}
- +
{/foreach} @@ -34,6 +34,6 @@
{/if} - +
diff --git a/web/tests/CloudPageBootstrapBehaviorTest.mjs b/web/tests/CloudPageBootstrapBehaviorTest.mjs index dc070bd9..106ea131 100644 --- a/web/tests/CloudPageBootstrapBehaviorTest.mjs +++ b/web/tests/CloudPageBootstrapBehaviorTest.mjs @@ -87,6 +87,7 @@ const session = runtime.slice(runtime.indexOf('async function initializeSession( applyCloudUser() {}, api() { throw Error('Unexpected initial ISO request'); }, byId: () => ({ addEventListener() {} }), bindPageCleanup() {}, renderIsos() { rendered = true; }, taskUrl: receipt => receipt.status_url, + t: key => key, setImportStatus() {}, updateImportAvailability() {}, watchImport(receipt) { observed = receipt.task_id; }, importIso() {}, window: { addEventListener() {} }, location: { assign() {} }, showError(id, message) { throw Error(message); }, @@ -113,6 +114,7 @@ const session = runtime.slice(runtime.indexOf('async function initializeSession( default_offer_id: 1, templates: [], ssh_keys: [] }; const context = vm.createContext({ state: { regions: [], lines: [], offers: [], templates: [], selectedKeys: {} }, byId, bootstrapItems: (value, key) => value[key] || [], showError() {}, + t: key => key, renderRegionPicker() {}, renderLinePicker() {}, renderOfferPicker() {}, renderTemplateCatalog() {}, renderKeyCards() {}, setDeploymentStepEnabled() {}, updateCreateAvailability() {}, formatUsd: value => `$${Number(value).toFixed(2)} USD`, }); diff --git a/web/tests/CloudSshKeyPageSsrContractTest.php b/web/tests/CloudSshKeyPageSsrContractTest.php index 7754c0d4..ac724774 100644 --- a/web/tests/CloudSshKeyPageSsrContractTest.php +++ b/web/tests/CloudSshKeyPageSsrContractTest.php @@ -67,7 +67,7 @@ $assert(str_contains($template, 'id="ssh-keys-bootstrap" type="application/json" && str_contains($template, '{$key.name|escape:"html"}') && str_contains($template, '{$key.fingerprint|escape:"html"}') && str_contains($template, 'id="ssh-key-list-view"') - && str_contains($template, '当前已添加的 SSH 公钥') + && str_contains($template, "{user_copy key='ssh_keys.list.panel.title'}") && str_contains($template, 'id="ssh-key-add-button"') && str_contains($template, '/user/cloud/ssh-keys?view=add') && str_contains($template, 'id="ssh-key-add-view"') @@ -97,6 +97,11 @@ $assert(str_contains($module, '/api/v1/ssh-keys') && !str_contains($module, 'importKeyFile') && !str_contains($module, 'ssh-key-file'), 'SSH-key JavaScript must retain explicit create and delete mutations.'); +$assert(str_contains($module, 'globalThis.VenixUserCopy') + && str_contains($module, "t('ssh_keys.confirm.delete.body', { name: key.name })") + && !preg_match('/payload\?\.(?:detail|message|msg|error)/', $module) + && !preg_match('/showError\([^\n]+error\?*\.message/', $module), + 'SSH-key feedback must use stable copy keys and never expose raw backend messages.'); $assert(str_contains($keyApi, "['id' => (int) \$key->id, 'name' => \$key->name, 'fingerprint' => \$key->fingerprint]") && !str_contains($keyApi, "'public_key' => \$key->public_key"), diff --git a/web/tests/CloudTaskObserverBehaviorTest.mjs b/web/tests/CloudTaskObserverBehaviorTest.mjs index c1082365..6ea7605e 100644 --- a/web/tests/CloudTaskObserverBehaviorTest.mjs +++ b/web/tests/CloudTaskObserverBehaviorTest.mjs @@ -553,20 +553,28 @@ const protocolFailure = task => { assert.doesNotMatch(runtimeSource, /task\.status === 'succeeded'/); const isoImagesSource = await readFile(isoImagesUrl, 'utf8'); - assert.match(isoImagesSource, /recoveryTaskFailureNotice\(task\)/); + assert.doesNotMatch(isoImagesSource, /recoveryTaskFailureNotice\(task\)/); + assert.doesNotMatch(isoImagesSource, /task\?\.error/); + assert.match(isoImagesSource, /task\?\.recovery\?\.pending === true/); + assert.match(isoImagesSource, /isos\.task\.failure\.resolved_partial/); + assert.match(isoImagesSource, /isos\.task\.failure\.resolved_applied/); + assert.match(isoImagesSource, /isos\.task\.failure\.resolved_not_applied/); + assert.match(isoImagesSource, /isos\.task\.failure\.effect_unknown/); + assert.match(isoImagesSource, /isos\.task\.failure\.locked/); assert.match(isoImagesSource, /method: 'DELETE', expectedStatus: 202, requireTaskReceipt: true/); assert.match(isoImagesSource, /const refreshed = await loadIsos\(\{ observeActive: false \}\)/); assert.match(isoImagesSource, /const canDelete = record\.can_delete === true/); assert.doesNotMatch(isoImagesSource, /const canDelete = String\(record\.state/); assert.match(isoImagesSource, /cleanupReason === 'quota_exceeded_after_import'/); - assert.match(isoImagesSource, /该 ISO 已下载到宿主机,但导入后超出个人库配额;可删除以释放空间/); - assert.match(isoImagesSource, /清理已下载 ISO/); - assert.match(isoImagesSource, /确定删除其宿主机副本并释放空间/); + assert.match(isoImagesSource, /isos\.item\.cleanup\.quota/); + assert.match(isoImagesSource, /isos\.confirm\.cleanup_downloaded\.title/); + assert.match(isoImagesSource, /isos\.confirm\.cleanup_downloaded\.body/); assert.match(isoImagesSource, /cleanupReason === 'partial_import'/); assert.match(isoImagesSource, /cleanupReason === 'partial_delete'/); - assert.match(isoImagesSource, /部分宿主机已完成导入、部分未导入;可清理已存在的剩余副本/); - assert.match(isoImagesSource, /部分宿主机已删除、部分仍保留副本;可继续清理剩余副本/); - assert.match(isoImagesSource, /已删除的宿主机不会重复执行/); + assert.match(isoImagesSource, /isos\.item\.cleanup\.partial_import/); + assert.match(isoImagesSource, /isos\.item\.cleanup\.partial_delete/); + assert.match(isoImagesSource, /isos\.confirm\.cleanup_partial_import\.body/); + assert.match(isoImagesSource, /isos\.confirm\.cleanup_partial_delete\.body/); assert.match(isoImagesSource, /taskSucceededWithoutRecovery\(task\)/); assert.doesNotMatch(isoImagesSource, /task\.status === 'succeeded'/); diff --git a/web/tests/UserCopyMediaKeysBehaviorTest.mjs b/web/tests/UserCopyMediaKeysBehaviorTest.mjs new file mode 100644 index 00000000..94e6f56b --- /dev/null +++ b/web/tests/UserCopyMediaKeysBehaviorTest.mjs @@ -0,0 +1,81 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import vm from 'node:vm'; + +const copyText = (key, parameters = {}) => `${key}:${JSON.stringify(parameters)}`; + +{ + const source = await readFile(new URL('../public/cloud/iso-images.js', import.meta.url), 'utf8'); + const safeError = source.slice(source.indexOf('function isoMutationMayHaveApplied('), + source.indexOf('function setImportStatus(')); + const context = vm.createContext({ t: copyText }); + vm.runInContext(`${safeError}\nglobalThis.safeIsoErrorForTest = safeIsoError;`, context); + const display = context.safeIsoErrorForTest; + assert.match(display(new Error('private transport detail'), 'isos.error.import', true), + /^isos\.error\.mutation_unknown:/); + assert.match(display({ status: 500 }, 'isos.error.delete', true), + /^isos\.error\.mutation_unknown:/); + assert.match(display({ status: 422 }, 'isos.error.import', true), + /^isos\.error\.invalid_input:/); + assert.match(display({ status: 500 }, 'isos.error.load'), + /^isos\.error\.request:\{"status":500\}$/); + assert.match(display({ status: 409, mutationMayHaveApplied: true }, + 'isos.error.delete', true), /^isos\.error\.mutation_unknown:/); +} + +{ + const source = await readFile(new URL('../public/cloud/ssh-keys.js', import.meta.url), 'utf8'); + const transport = source.slice(source.indexOf('class UiCopyError'), + source.indexOf('function normalizeKey(')); + const context = vm.createContext({ + Headers, + location: { protocol: 'https:', hostname: 'panel.example.test', assign() {} }, + state: { csrfToken: 'fixture' }, + byId() { return null; }, + t: copyText, + fetch: async () => { throw new Error('private network failure'); }, + }); + vm.runInContext(`${transport}\nglobalThis.apiForTest = api; globalThis.errorTextForTest = errorText;`, + context); + + await assert.rejects(context.apiForTest('/api/v1/ssh-keys', { + method: 'POST', body: { name: 'fixture', public_key: 'fixture' }, + }), error => error.copyKey === 'ssh_keys.error.mutation_unknown' + && error.mutationMayHaveApplied === true); + + context.fetch = async () => ({ status: 201, ok: true, async json() { + throw new Error('invalid response'); + } }); + await assert.rejects(context.apiForTest('/api/v1/ssh-keys', { + method: 'POST', body: { name: 'fixture', public_key: 'fixture' }, + }), error => error.copyKey === 'ssh_keys.error.mutation_unknown' + && error.mutationMayHaveApplied === true); + + context.fetch = async () => ({ + status: 422, ok: false, + async json() { return { message: 'private backend validation detail' }; }, + }); + await assert.rejects(context.apiForTest('/api/v1/ssh-keys', { + method: 'POST', body: { name: 'fixture', public_key: 'fixture' }, + }), error => error.copyKey === 'ssh_keys.error.invalid_input' + && !String(error.message).includes('private backend')); + + context.fetch = async () => ({ + status: 500, ok: false, + async json() { return { detail: 'private backend exception' }; }, + }); + await assert.rejects(context.apiForTest('/api/v1/ssh-keys'), + error => error.copyKey === 'ssh_keys.error.request' + && error.parameters.status === 500 + && !String(error.message).includes('private backend')); + await assert.rejects(context.apiForTest('/api/v1/ssh-keys', { + method: 'POST', body: { name: 'fixture', public_key: 'fixture' }, + }), error => error.copyKey === 'ssh_keys.error.mutation_unknown' + && error.mutationMayHaveApplied === true + && !String(error.message).includes('private backend')); + + assert.match(context.errorTextForTest(new Error('private backend exception'), + 'ssh_keys.error.initialize'), /^ssh_keys\.error\.initialize:/); +} + +console.log('ISO and SSH-key safe feedback behavior tests passed.'); diff --git a/web/tests/UserCopyMediaKeysContractTest.php b/web/tests/UserCopyMediaKeysContractTest.php new file mode 100644 index 00000000..402571df --- /dev/null +++ b/web/tests/UserCopyMediaKeysContractTest.php @@ -0,0 +1,95 @@ + 'string', 'size' => 'string', +] && $entries['isos.confirm.delete.body']['parameters'] === ['name' => 'string'] + && $entries['ssh_keys.confirm.delete.body']['parameters'] === ['name' => 'string'] + && $entries['isos.error.request']['parameters'] === ['status' => 'integer'] + && $entries['ssh_keys.error.request']['parameters'] === ['status' => 'integer'], + 'Media/key parameter contracts drifted from their call sites.'); + +foreach ($entries as $entry) { + if (!in_array($entry['scope'], ['isos', 'ssh_keys'], true) + || !str_starts_with($entry['kind'], 'toast_')) { + continue; + } + $assert(in_array($entry['toast_tone'], ['success', 'warning', 'error', 'info'], true), + 'Media/key Toast copy is missing an explicit tone: ' . $entry['key']); +} + +$paths = [ + $root . '/resources/views/venix/cloud/pages/isos.tpl', + $root . '/resources/views/venix/cloud/pages/keys.tpl', + $root . '/public/cloud/iso-images.js', + $root . '/public/cloud/ssh-keys.js', +]; +$violations = UserCopyCoverageScanner::scanFiles($paths); +$assert($violations === [], 'Media/key pages retain direct user-visible copy: ' + . json_encode($violations, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); + +$referenced = []; +foreach ($paths as $path) { + $source = file_get_contents($path); + preg_match_all( + '/(?:user_copy\s+key=|\bt\()[\'\"]((?:isos|ssh_keys)\.[a-z0-9_.]+)[\'\"]/', + $source, + $matches + ); + array_push($referenced, ...$matches[1]); +} +foreach (array_unique($referenced) as $key) { + $assert(isset($entries[$key]), 'Media/key source references an undeclared key: ' . $key); +} + +$isoModule = file_get_contents($root . '/public/cloud/iso-images.js'); +$keyModule = file_get_contents($root . '/public/cloud/ssh-keys.js'); +$assert(str_contains($isoModule, 'globalThis.VenixUserCopy') + && str_contains($keyModule, 'globalThis.VenixUserCopy'), + 'Media/key modules must resolve feedback through the user-copy runtime.'); +$assert(!preg_match('/payload\?\.(?:detail|message|msg|error)/', $keyModule) + && !preg_match('/task\?\.error/', $isoModule) + && !str_contains($isoModule, 'recoveryTaskFailureNotice(task)') + && !preg_match('/showError\([^\n]+error\?*\.message/', $isoModule . "\n" . $keyModule), + 'Media/key feedback must not expose raw backend or task messages.'); +$assert(str_contains($isoModule, "t('isos.confirm.delete.body', { name: isoName })") + && str_contains($keyModule, "t('ssh_keys.confirm.delete.body', { name: key.name })") + && str_contains($isoModule, "t('isos.toast.import.ready.title')") + && str_contains($keyModule, "t('ssh_keys.toast.deleted.title')"), + 'Media/key confirmations and Toasts must use their parameterized copy contracts.'); +$assert(str_contains($isoModule, 'uncertainMutations: new Set()') + && str_contains($isoModule, "pageState.activeStatusUrl = 'unknown'") + && substr_count($keyModule, 'if (!keepLocked) setMutationBusy(false);') === 2, + 'Unknown media/key mutations must remain locally locked until a fresh page reconciliation.'); + +echo "ISO and SSH-key user-copy contract checks passed.\n";