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

247 lines
8.9 KiB
JavaScript

const assetVersion = new URL(import.meta.url).searchParams.get('v');
function versionedModuleUrl(path) {
const url = new URL(path, import.meta.url);
url.search = '';
if (assetVersion) url.searchParams.set('v', assetVersion);
return url.href;
}
const { toast } = await import(versionedModuleUrl('./toast.js'));
// 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 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;
target.textContent = message;
target.hidden = !message;
}
function requireSecureTransport() {
if (location.protocol !== 'https:'
&& !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) {
throw new UiCopyError('ssh_keys.error.secure_transport');
}
}
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 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 UiCopyError(mutating
? 'ssh_keys.error.mutation_unknown' : 'ssh_keys.error.non_json', {}, mutating);
}
}
if (response.status === 401) {
location.assign('/auth/login');
throw new UiCopyError('ssh_keys.error.login_expired');
}
if (!response.ok || payload?.ret === 0) {
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;
}
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 UiCopyError('ssh_keys.error.bootstrap_missing');
let payload;
try { payload = JSON.parse(source.textContent || '{}'); }
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 UiCopyError('ssh_keys.error.bootstrap_incomplete');
}
const keys = payload.ssh_keys.map(normalizeKey);
if (keys.some(key => key === null)) {
throw new UiCopyError('ssh_keys.error.list_invalid');
}
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) {
const empty = makeElement('div', 'ssh-keys-empty');
const action = makeElement('a', 'button button-outline', t('ssh_keys.empty.action'));
action.href = '/user/cloud/ssh-keys?view=add';
empty.append(makeElement('strong', '', t('ssh_keys.empty.title')),
makeElement('p', '', t('ssh_keys.empty.body')), action);
container.append(empty);
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',
t('ssh_keys.action.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');
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 UiCopyError('ssh_keys.error.saved_invalid');
location.assign('/user/cloud/ssh-keys');
} catch (error) {
keepLocked = error?.mutationMayHaveApplied === true;
showError('ssh-key-form-error', errorText(error, 'ssh_keys.error.save'));
} finally {
if (!keepLocked) 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: 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(t('ssh_keys.toast.deleted.body'), 'success',
t('ssh_keys.toast.deleted.title'));
} catch (error) {
keepLocked = error?.mutationMayHaveApplied === true;
showError('ssh-keys-list-error', errorText(error, 'ssh_keys.error.delete'));
} finally {
if (!keepLocked) setMutationBusy(false);
}
}
export function initialize() {
try {
readBootstrap();
byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout'));
byId('ssh-key-form')?.addEventListener('submit', addKey);
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', errorText(error, 'ssh_keys.error.initialize'));
byId('ssh-key-save-button')?.setAttribute('disabled', '');
document.querySelectorAll('[data-ssh-key-delete]').forEach(button => {
button.disabled = true;
});
}
}