You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/public/cloud/ssh-keys.js

217 lines
7.7 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import { toast } from './toast.js?v=2026100102';
// The saved-key list and the user/CSRF bootstrap are rendered into the
// first HTML response. This module owns only the add/delete interactions and
// 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 state = { csrfToken: '', keys: [], mutationBusy: false };
function showError(id, message = '') {
const target = byId(id);
if (!target) return;
target.textContent = message;
target.hidden = !message;
}
function requireSecureTransport() {
if (location.protocol !== 'https:'
&& !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) {
throw new Error('请通过 HTTPS 管理 SSH 公钥。');
}
}
async function api(path, options = {}) {
const method = String(options.method || 'GET').toUpperCase();
const headers = new Headers({ Accept: 'application/json', ...options.headers });
if (!['GET', 'HEAD'].includes(method)) {
requireSecureTransport();
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),
});
let payload = null;
if (response.status !== 204) {
try { payload = await response.json(); }
catch { throw new Error('服务返回了非 JSON 数据,请检查 PHP 及反代配置。'); }
}
if (response.status === 401) {
location.assign('/auth/login');
throw new Error('登录已过期。');
}
if (!response.ok || payload?.ret === 0) {
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})`));
}
return payload;
}
function normalizeKey(value) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
const id = String(value.id ?? '');
const name = String(value.name ?? '').trim();
if (!/^[1-9]\d*$/.test(id) || !name) return null;
return { id, name, fingerprint: String(value.fingerprint ?? '').trim() };
}
function readBootstrap() {
const source = byId('ssh-keys-bootstrap');
if (!source) throw new Error('公钥页面初始数据缺失,请刷新后重试。');
let payload;
try { payload = JSON.parse(source.textContent || '{}'); }
catch { throw new Error('公钥页面初始数据无效,请刷新后重试。'); }
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('公钥页面初始数据不完整,请刷新后重试。');
}
const keys = payload.ssh_keys.map(normalizeKey);
if (keys.some(key => key === null)) {
throw new Error('公钥列表数据无效,请刷新后重试。');
}
state.csrfToken = String(user.csrf_token);
state.keys = keys;
}
function makeElement(tag, className = '', content) {
const element = document.createElement(tag);
if (className) element.className = className;
if (content !== undefined) element.textContent = String(content);
return element;
}
function renderKeys() {
const container = byId('ssh-keys-list');
if (!container) return;
container.replaceChildren();
if (!state.keys.length) {
container.append(makeElement('p', 'muted', '还没有公钥。'));
return;
}
for (const key of state.keys) {
const row = makeElement('div', 'ssh-key-row');
row.dataset.sshKeyId = key.id;
const details = makeElement('div', 'ssh-key-details');
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', '删除');
button.type = 'button';
button.dataset.sshKeyDelete = key.id;
actions.append(button);
row.append(details, actions);
container.append(row);
}
}
function setMutationBusy(busy) {
state.mutationBusy = busy;
const save = byId('ssh-key-save-button');
if (save) save.disabled = busy;
byId('ssh-keys-list')?.setAttribute('aria-busy', String(busy));
document.querySelectorAll('[data-ssh-key-delete]').forEach(button => {
button.disabled = busy;
});
}
async function addKey(event) {
event.preventDefault();
if (state.mutationBusy) return;
setMutationBusy(true);
showError('ssh-key-form-error');
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('公钥已保存,但服务返回的列表数据无效,请刷新页面。');
state.keys = [...state.keys.filter(item => item.id !== key.id), key];
byId('ssh-key-form').reset();
renderKeys();
toast('公钥已保存。', 'success');
} catch (error) {
showError('ssh-key-form-error', error?.message || '公钥保存失败,请稍后重试。');
} finally {
setMutationBusy(false);
}
}
async function deleteKey(button) {
if (state.mutationBusy) return;
const id = String(button.dataset.sshKeyDelete || '');
const key = state.keys.find(item => item.id === id);
if (!key) return;
const confirmed = await requestUserConfirmation({
title: '删除 SSH 公钥',
message: `确定删除“${key.name}”?已经创建的实例不会受到影响。`,
confirmText: '删除公钥',
tone: 'danger',
});
if (!confirmed) return;
setMutationBusy(true);
showError('ssh-keys-list-error');
try {
await api(`/api/v1/ssh-keys/${encodeURIComponent(id)}`, { method: 'DELETE' });
state.keys = state.keys.filter(item => item.id !== id);
renderKeys();
toast('公钥已删除。', 'success');
} catch (error) {
showError('ssh-keys-list-error', error?.message || '公钥删除失败,请稍后重试。');
} finally {
setMutationBusy(false);
}
}
async function importKeyFile(event) {
showError('ssh-key-form-error');
const file = event.target.files?.[0];
if (!file) return;
if (file.size > 16384) {
showError('ssh-key-form-error', '公钥文件超过 16 KiB 限制。');
return;
}
try {
const content = await file.text();
if (/PRIVATE KEY/.test(content)) {
showError('ssh-key-form-error', '不能导入私钥,只能导入 .pub 公钥。');
return;
}
byId('ssh-key-public-key').value = content.trim();
} catch {
showError('ssh-key-form-error', '无法读取公钥文件,请重新选择。');
}
}
export function initialize() {
try {
readBootstrap();
byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout'));
byId('ssh-key-form')?.addEventListener('submit', addKey);
byId('ssh-key-file')?.addEventListener('change', importKeyFile);
byId('ssh-keys-list')?.addEventListener('click', event => {
const button = event.target instanceof Element
? event.target.closest('[data-ssh-key-delete]') : null;
if (button) void deleteKey(button);
});
} catch (error) {
showError('cloud-page-error', error?.message
|| '公钥页面初始化失败,请刷新后重试。');
byId('ssh-key-save-button')?.setAttribute('disabled', '');
document.querySelectorAll('[data-ssh-key-delete]').forEach(button => {
button.disabled = true;
});
}
}