feat(i18n): migrate ISO and SSH key pages

go
codex 2 weeks ago
parent 1e3a0fcbe5
commit e3bba49d7b

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

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

@ -0,0 +1,266 @@
<?php
$entry = require dirname(__DIR__) . '/entry.php';
$iso = static function (
string $key,
string $source,
string $kind = 'label',
array $parameters = [],
?string $toastTone = null
) use ($entry): array {
return $entry(
$key,
'isos',
'cloud.isos',
$source,
$kind,
$parameters,
'required',
false,
$toastTone
);
};
$ssh = static function (
string $key,
string $source,
string $kind = 'label',
array $parameters = [],
?string $toastTone = null
) use ($entry): array {
return $entry(
$key,
'ssh_keys',
'cloud.keys',
$source,
$kind,
$parameters,
'required',
false,
$toastTone
);
};
return [
$iso('isos.eyebrow', '个人安装介质'),
$iso('isos.title', 'ISO 镜像', 'title'),
$iso('isos.description',
'从 HTTPS 直链导入并保存到个人 ISO 库;此功能仅在管理员开放期间可用。',
'description'),
$iso('isos.back', '返回实例', 'navigation'),
$iso('isos.import.title', '远程下载 ISO', 'title'),
$iso('isos.import.description',
'填写可直接下载的 HTTPS 地址,完成后可用于全部宿主机。',
'description'),
$iso('isos.form.name.label', '镜像名称'),
$iso('isos.form.name.placeholder', '例如 Debian 13 安装镜像', 'placeholder'),
$iso('isos.form.url.label', 'HTTPS ISO 直链'),
$iso('isos.form.url.placeholder', 'https://example.com/system.iso', 'placeholder'),
$iso('isos.form.hint',
'仅支持无需登录、不会跳转的公网 HTTPS 直链,URL 路径的文件名必须以 .iso 结尾;每个用户最多保存 5 个,个人 ISO 库累计和单文件均不得超过 10 GiB。超出限额会停止下载并提示,离开页面不会取消后台任务。',
'help'),
$iso('isos.availability.running',
'已有 ISO 下载任务正在执行,完成前不能再次导入。', 'warning'),
$iso('isos.availability.disabled',
'账户的套餐购买及 ISO 上传服务已被管理员停用。', 'warning'),
$iso('isos.import.submit', '开始远程下载', 'button'),
$iso('isos.import.status.starting', '正在建立远程下载任务…', 'status'),
$iso('isos.import.status.importing', '正在远程下载并校验 ISO…', 'status'),
$iso('isos.import.status.accepted',
'任务已接收,正在后台下载;可在任务中心查看结果。', 'status'),
$iso('isos.import.status.ready', 'ISO 已导入全局个人库。', 'status'),
$iso('isos.import.status.observer_stopped',
'任务自动观察已停止,已按服务端最新状态更新导入入口;请在任务中心刷新最终结果。',
'warning'),
$iso('isos.list.title', '我的 ISO', 'title'),
$iso('isos.list.description',
'这里只显示当前账户的全局 ISO,其他用户无法查看或使用。',
'description'),
$iso('isos.list.aria', '个人 ISO 镜像列表', 'aria_label'),
$iso('isos.empty', '还没有个人 ISO 镜像。', 'empty_state'),
$iso('isos.item.unnamed', '未命名 ISO'),
$iso('isos.item.summary_digest',
'{size} · SHA-256 {digest}…', 'description', [
'size' => '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'),
];

@ -1,25 +1,25 @@
<div id="user-isos-workspace">
<div class="page-heading"><div><span class="eyebrow">PERSONAL INSTALL MEDIA</span><h1>ISO 镜像</h1><p>从 HTTPS 直链导入并保存到个人 ISO 库;此功能仅在管理员开放期间可用。</p></div><a class="button button-outline" href="/user/cloud/instances">返回实例</a></div>
<div class="page-heading"><div><span class="eyebrow">{user_copy key='isos.eyebrow'}</span><h1>{user_copy key='isos.title'}</h1><p>{user_copy key='isos.description'}</p></div><a class="button button-outline" href="/user/cloud/instances">{user_copy key='isos.back'}</a></div>
<div class="user-isos-grid">
<section class="host-card" aria-labelledby="user-iso-import-title">
<div class="host-card-heading"><span class="host-card-number">↓</span><div><h2 id="user-iso-import-title">远程下载 ISO</h2><p>填写可直接下载的 HTTPS 地址,完成后可用于全部宿主机。</p></div></div>
<div class="host-card-heading"><span class="host-card-number">↓</span><div><h2 id="user-iso-import-title">{user_copy key='isos.import.title'}</h2><p>{user_copy key='isos.import.description'}</p></div></div>
<form id="user-iso-form" class="form-stack">
<label for="user-iso-name">镜像名称</label>
<input id="user-iso-name" type="text" maxlength="64" required autocomplete="off" placeholder="例如 Debian 13 安装镜像" />
<label for="user-iso-url">HTTPS ISO 直链</label>
<input id="user-iso-url" type="url" maxlength="2048" required inputmode="url" autocomplete="off" spellcheck="false" placeholder="https://example.com/system.iso" />
<small class="user-iso-hint">仅支持无需登录、不会跳转的公网 HTTPS 直链,URL 路径的文件名必须以 .iso 结尾;每个用户最多保存 5 个,个人 ISO 库累计和单文件均不得超过 10 GiB。超出限额会停止下载并提示,离开页面不会取消后台任务。</small>
<p id="user-iso-availability" class="host-test-status warning" role="status"{if !empty($cloud_iso_view.can_import) && empty($cloud_iso_view.import_active)} hidden{/if}>{if !empty($cloud_iso_view.import_active)}已有 ISO 下载任务正在执行,完成前不能再次导入。{elseif empty($cloud_iso_view.can_import)}账户的套餐购买及 ISO 上传服务已被管理员停用。{/if}</p>
<label for="user-iso-name">{user_copy key='isos.form.name.label'}</label>
<input id="user-iso-name" type="text" maxlength="64" required autocomplete="off" placeholder="{user_copy key='isos.form.name.placeholder'}" />
<label for="user-iso-url">{user_copy key='isos.form.url.label'}</label>
<input id="user-iso-url" type="url" maxlength="2048" required inputmode="url" autocomplete="off" spellcheck="false" placeholder="{user_copy key='isos.form.url.placeholder'}" />
<small class="user-iso-hint">{user_copy key='isos.form.hint'}</small>
<p id="user-iso-availability" class="host-test-status warning" role="status"{if !empty($cloud_iso_view.can_import) && empty($cloud_iso_view.import_active)} hidden{/if}>{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}</p>
<p id="user-iso-form-error" class="form-error" role="alert" hidden></p>
<button id="user-iso-submit" class="button button-primary" type="submit" disabled>开始远程下载</button>
<button id="user-iso-submit" class="button button-primary" type="submit" disabled>{user_copy key='isos.import.submit'}</button>
</form>
<p id="user-iso-import-status" class="host-test-status" role="status" hidden></p>
</section>
<section class="host-card" aria-labelledby="user-iso-list-title">
<div class="host-card-heading"><span class="host-card-number">◉</span><div><h2 id="user-iso-list-title">我的 ISO</h2><p>这里只显示当前账户的全局 ISO,其他用户无法查看或使用。</p></div></div>
<div class="host-card-heading"><span class="host-card-number">◉</span><div><h2 id="user-iso-list-title">{user_copy key='isos.list.title'}</h2><p>{user_copy key='isos.list.description'}</p></div></div>
<p id="user-iso-list-error" class="form-error" role="alert" hidden></p>
<div id="user-iso-list" class="user-iso-list" aria-live="polite">
{foreach $cloud_iso_view.items|default:[] as $iso}<article class="user-iso-row"><div class="user-iso-details"><strong>{$iso.name|escape:'html'}</strong><small>{$iso.size_display|escape:'html'}{$iso.fingerprint_display|escape:'html'}</small></div><button class="row-button user-iso-delete" type="button" disabled>{if $iso.can_delete|default:false}删除{else}不可删除{/if}</button></article>{foreachelse}<p class="muted">还没有个人 ISO 镜像。</p>{/foreach}
<div id="user-iso-list" class="user-iso-list" aria-label="{user_copy key='isos.list.aria'}" aria-live="polite">
{foreach $cloud_iso_view.items|default:[] as $iso}<article class="user-iso-row"><div class="user-iso-details"><strong>{if $iso.name|default:'' != ''}{$iso.name|escape:'html'}{else}{user_copy key='isos.item.unnamed'}{/if}</strong><small>{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}</small></div><button class="row-button user-iso-delete" type="button" disabled>{if $iso.can_delete|default:false}{user_copy key='isos.action.delete'}{else}{user_copy key='isos.action.unavailable'}{/if}</button></article>{foreachelse}<p class="muted">{user_copy key='isos.empty'}</p>{/foreach}
</div>
</section>
</div>

@ -1,23 +1,23 @@
<div id="ssh-keys-workspace">
{if $cloud_ssh_keys_view == 'add'}
<div class="page-heading"><div><span class="eyebrow">ADD SSH KEY</span><h1>添加 SSH 公钥</h1><p>填写名称并粘贴 OpenSSH 公钥内容。</p></div><a id="ssh-keys-list-button" class="button button-outline" href="/user/cloud/ssh-keys">返回公钥列表</a></div>
<div class="page-heading"><div><span class="eyebrow">{user_copy key='ssh_keys.add.eyebrow'}</span><h1>{user_copy key='ssh_keys.add.title'}</h1><p>{user_copy key='ssh_keys.add.description'}</p></div><a id="ssh-keys-list-button" class="button button-outline" href="/user/cloud/ssh-keys">{user_copy key='ssh_keys.add.back'}</a></div>
<section id="ssh-key-add-view" class="host-card ssh-key-add-panel" aria-labelledby="ssh-key-add-title">
<div class="host-card-heading"><span class="host-card-number">+</span><div><h2 id="ssh-key-add-title">添加公钥</h2><p>仅粘贴单行 OpenSSH 公钥;不要填写私钥或私钥口令。</p></div></div>
<div class="host-card-heading"><span class="host-card-number">+</span><div><h2 id="ssh-key-add-title">{user_copy key='ssh_keys.add.panel.title'}</h2><p>{user_copy key='ssh_keys.add.panel.description'}</p></div></div>
<form id="ssh-key-form" class="form-stack">
<label for="ssh-key-name">公钥名称</label><input id="ssh-key-name" type="text" maxlength="80" required autocomplete="off" placeholder="例如 我的电脑" />
<label for="ssh-key-public-key">OpenSSH 公钥</label><textarea id="ssh-key-public-key" maxlength="16384" rows="5" required spellcheck="false" autocomplete="off" autocapitalize="off" placeholder="ssh-ed25519 AAAA…"></textarea>
<label for="ssh-key-name">{user_copy key='ssh_keys.form.name.label'}</label><input id="ssh-key-name" type="text" maxlength="80" required autocomplete="off" placeholder="{user_copy key='ssh_keys.form.name.placeholder'}" />
<label for="ssh-key-public-key">{user_copy key='ssh_keys.form.key.label'}</label><textarea id="ssh-key-public-key" maxlength="16384" rows="5" required spellcheck="false" autocomplete="off" autocapitalize="off" placeholder="{user_copy key='ssh_keys.form.key.placeholder'}"></textarea>
<p id="ssh-key-form-error" class="form-error" role="alert" hidden></p>
<button id="ssh-key-save-button" class="button button-primary" type="submit">保存公钥</button>
<button id="ssh-key-save-button" class="button button-primary" type="submit">{user_copy key='ssh_keys.form.save'}</button>
</form>
</section>
{else}
<div class="page-heading"><div><span class="eyebrow">ACCOUNT SSH KEYS</span><h1>SSH 公钥</h1><p>查看当前已经添加的 SSH 公钥;创建云镜像实例时可以直接选择。</p></div><a id="ssh-key-add-button" class="button button-primary" href="/user/cloud/ssh-keys?view=add">+ 添加公钥</a></div>
<div class="page-heading"><div><span class="eyebrow">{user_copy key='ssh_keys.list.eyebrow'}</span><h1>{user_copy key='ssh_keys.list.title'}</h1><p>{user_copy key='ssh_keys.list.description'}</p></div><a id="ssh-key-add-button" class="button button-primary" href="/user/cloud/ssh-keys?view=add">{user_copy key='ssh_keys.list.add'}</a></div>
<section id="ssh-key-list-view" class="host-card ssh-keys-panel" aria-labelledby="ssh-key-list-title">
<div class="host-card-heading"><span class="host-card-number">⌑</span><div><h2 id="ssh-key-list-title">当前已添加的 SSH 公钥</h2><p>公钥不会向其他用户显示;删除后,不影响已经创建的实例。</p></div></div>
<div class="host-card-heading"><span class="host-card-number">⌑</span><div><h2 id="ssh-key-list-title">{user_copy key='ssh_keys.list.panel.title'}</h2><p>{user_copy key='ssh_keys.list.panel.description'}</p></div></div>
<p id="ssh-keys-list-error" class="form-error" role="alert" hidden></p>
<div id="ssh-keys-list" class="ssh-keys-list" aria-live="polite">
<div id="ssh-keys-list" class="ssh-keys-list" aria-label="{user_copy key='ssh_keys.list.aria'}" aria-live="polite">
{if empty($cloud_ssh_keys)}
<div class="ssh-keys-empty"><strong>还没有 SSH 公钥</strong><p>添加公钥后,部署或重装实例时可以直接选择。</p><a class="button button-outline" href="/user/cloud/ssh-keys?view=add">添加第一个公钥</a></div>
<div class="ssh-keys-empty"><strong>{user_copy key='ssh_keys.empty.title'}</strong><p>{user_copy key='ssh_keys.empty.body'}</p><a class="button button-outline" href="/user/cloud/ssh-keys?view=add">{user_copy key='ssh_keys.empty.action'}</a></div>
{else}
{foreach $cloud_ssh_keys as $key}
<div class="ssh-key-row" data-ssh-key-id="{$key.id|escape:"html"}">
@ -26,7 +26,7 @@
<small>{$key.fingerprint|escape:"html"}</small>
</div>
<div class="ssh-key-actions">
<button class="row-button ssh-key-delete" type="button" data-ssh-key-delete="{$key.id|escape:"html"}">删除</button>
<button class="row-button ssh-key-delete" type="button" data-ssh-key-delete="{$key.id|escape:"html"}">{user_copy key='ssh_keys.action.delete'}</button>
</div>
</div>
{/foreach}
@ -34,6 +34,6 @@
</div>
</section>
{/if}
<noscript><p class="resource-warning">已保存的公钥可以正常查看;新增或删除公钥需要启用 JavaScript。</p></noscript>
<noscript><p class="resource-warning">{user_copy key='ssh_keys.noscript'}</p></noscript>
<script id="ssh-keys-bootstrap" type="application/json">{$cloud_ssh_keys_bootstrap_json nofilter}</script>
</div>

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

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

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

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

@ -0,0 +1,95 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\UserCopy\UserCopyCoverageScanner;
use App\Services\UserCopy\UserCopyManifest;
$root = dirname(__DIR__);
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$manifest = UserCopyManifest::load();
$entries = array_column($manifest['entries'], null, 'key');
$assert(($manifest['pages']['cloud.isos']['scopes'] ?? null) === ['common', 'isos']
&& ($manifest['pages']['cloud.keys']['scopes'] ?? null) === ['common', 'ssh_keys'],
'ISO and SSH-key pages must publish only their declared copy scopes.');
$required = [
'isos.list.aria', 'isos.empty', 'isos.confirm.delete.body',
'isos.confirm.cleanup_downloaded.body', 'isos.task.failure.recovering',
'isos.task.failure.effect_unknown', 'isos.task.receipt.invalid',
'isos.toast.import.ready.body', 'isos.error.mutation_unknown',
'ssh_keys.list.aria', 'ssh_keys.empty.title',
'ssh_keys.confirm.delete.body', 'ssh_keys.toast.deleted.body',
'ssh_keys.error.mutation_unknown', 'ssh_keys.error.initialize',
];
foreach ($required as $key) {
$assert(isset($entries[$key]), 'Required media/key copy is missing: ' . $key);
}
$assert($entries['isos.item.summary_digest']['parameters'] === [
'digest' => '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";
Loading…
Cancel
Save