Files
homegate/ui/dist/certificates.js
DizelBadCoder 5661de72b7
All checks were successful
Test and publish Homegate / checks (push) Successful in 29s
Test and publish Homegate / publish (push) Successful in 12m43s
Add UI DNS challenge issuance and automatic home NPM renewal
2026-10-15 05:42:15 +03:00

96 lines
7.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

function certificateFields(route) {
const mode = route.certificate_mode || 'homegate';
return `<h3 class="modal-subtitle">HTTPS-сертификат</h3><div class="form-grid">
<label class="field full">Источник<select name="certificate_mode">
<option value="homegate" ${mode === 'homegate' ? 'selected' : ''}>Homegate — локальный CA</option>
<option value="npm" ${mode === 'npm' ? 'selected' : ''}>Существующий сертификат домашнего NPM</option>
<option value="dns_challenge">Let’s Encrypt — DNS challenge</option>
<option value="remote_npm" ${mode === 'remote_npm' ? 'selected' : ''}>Копия из NPM на VDS — автообновление</option>
</select></label>
<div class="field full" id="npm-certificate-fields" ${mode === 'homegate' ? 'hidden' : ''}>
<label class="field">Сертификат домашнего NPM<select name="npm_certificate_id"></select></label>
<label class="field" id="remote-certificate-field" ${mode !== 'remote_npm' ? 'hidden' : ''}>Сертификат на VDS<select name="remote_certificate_id"></select></label>
<button type="button" class="btn" id="reload-certificates">${icon('refresh',14)} Обновить список</button>
<small id="certificate-list-status" role="status"></small>
</div><p class="note field full" id="certificate-help"></p>
</div>${dnsChallengeFields(route.hostname || '')}`;
}
function bindCertificateFields(form, route) {
let local = [], remote = [], generation = 0;
const mode = form.elements.certificate_mode, target = form.elements.npm_certificate_id;
const source = form.elements.remote_certificate_id, status = form.querySelector('#certificate-list-status');
let selectedTarget = String(route.npm_certificate_id || ''), selectedSource = String(route.remote_certificate_id || '');
const dns = bindDNSChallenge(form, cert => {
if(mode.value !== 'dns_challenge') return;
const hostname = form.elements.hostname.value.trim().toLowerCase();
if(hostname && !cert.domains.some(d => d === hostname || (d.startsWith('*.') && hostname.endsWith(d.slice(1)) && hostname.split('.').length === d.split('.').length))) {
form.querySelector('#dns-challenge-status').textContent = `Сертификат #${cert.id} готов, но не покрывает ${hostname}. Укажите соответствующий домен сервиса или выпустите сертификат для него.`;
return;
}
local = [...local.filter(c => c.id !== cert.id), cert];
selectedTarget = String(cert.id); mode.value = 'npm';
update();
status.textContent = 'Сертификат готов. Сохраните сервис — Homegate создаст DNS и прокси. Автопродление уже включено в NPM.';
});
const option = (value, label) => `<option value="${esc(value)}">${esc(label)}</option>`;
const label = c => `#${c.id} · ${c.name || c.domains.join(', ')} · ${c.domains.join(', ')} · до ${date(c.expires)}${c.provider === 'letsencrypt' ? ' · Let’s Encrypt' : ''}`;
function populate(select, certs, selected, placeholder) {
select.innerHTML = option('', placeholder) + certs.map(c => option(String(c.id), label(c))).join('');
if(selected && !certs.some(c => String(c.id) === selected)) select.insertAdjacentHTML('beforeend', option(selected, `#${selected} — сохранённый выбор, нет в списке`));
select.value = selected;
}
function update() {
const copying = mode.value === 'remote_npm', issuing = mode.value === 'dns_challenge';
const enabled = ['npm','remote_npm'].includes(mode.value);
if(issuing) dns.load(); else dns.hide();
document.querySelector('button[type="submit"][form="modal-form"]').disabled = issuing;
form.querySelector('#npm-certificate-fields').hidden = !enabled;
form.querySelector('#remote-certificate-field').hidden = !copying;
target.disabled = !enabled; target.required = mode.value === 'npm';
source.disabled = !copying; source.required = copying;
populate(target, local.filter(c => !copying || c.provider === 'other'), selectedTarget,
copying ? 'Создать новую копию в домашнем NPM' : 'Выберите сертификат');
populate(source, remote, selectedSource, 'Выберите сертификат Let’s Encrypt');
form.querySelector('#certificate-help').textContent = {
homegate: 'Homegate выпускает и продлевает сертификат. На устройствах нужен доверенный корневой CA.',
npm: 'Homegate привяжет этот сертификат к прокси и создаст локальный DNS. Сертификат не заменяется. Let’s Encrypt автоматически продлевает домашний NPM; Custom нужно обновлять у его издателя.',
dns_challenge: 'Сначала выпустите сертификат кнопкой ниже, затем сохраните сервис. Подключение к VDS для этого режима не требуется.',
remote_npm: 'NPM на VDS продлевает сертификат самостоятельно. Homegate проверяет его каждый цикл и копирует обновление домой. На VDS выполняется только чтение. Если интернет недоступен, используется последняя копия до окончания её срока. При выборе существующего Custom обновляется именно он.'
}[mode.value];
}
async function load() {
if(!['npm','remote_npm'].includes(mode.value)) return;
const request = ++generation, copying = mode.value === 'remote_npm';
status.textContent = 'Загрузка сертификатов…';
const results = await Promise.allSettled([api('/api/npm-certificates'), ...(copying ? [api('/api/remote-certificates')] : [])]);
if(request !== generation || !form.isConnected) return;
const errors = [];
if(results[0].status === 'fulfilled') local = results[0].value.certificates; else errors.push(results[0].reason.message);
if(copying) {
if(results[1].status === 'fulfilled') remote = results[1].value.certificates; else errors.push(results[1].reason.message);
}
update();
status.textContent = errors.length ? errors.join(' · ') : (copying ? 'Списки обновлены. Настройки VDS не изменены.' : 'Список обновлён.');
}
target.addEventListener('change', () => selectedTarget = target.value);
source.addEventListener('change', () => selectedSource = source.value);
mode.addEventListener('change', () => { generation++; selectedTarget = ''; update(); load(); });
form.querySelector('#reload-certificates').addEventListener('click', load);
update(); load();
}
function readCertificateFields(fields, item) {
item.certificate_mode = fields.get('certificate_mode');
delete item.npm_certificate_id;
delete item.remote_certificate_id;
if(item.certificate_mode !== 'homegate' && fields.get('npm_certificate_id')) item.npm_certificate_id = Number(fields.get('npm_certificate_id'));
if(item.certificate_mode === 'remote_npm') item.remote_certificate_id = Number(fields.get('remote_certificate_id'));
}
function certificateRenewal(cert) {
if(cert.mode === 'remote_npm') return cert.sync_error ? `Ошибка копирования: ${esc(cert.sync_error)}` : `Копия с VDS${cert.synced_at ? ' · проверена ' + esc(new Date(cert.synced_at * 1000).toLocaleString('ru-RU')) : ''}`;
if(cert.mode === 'npm') return cert.provider === 'letsencrypt' ? `Автоматически в домашнем NPM${cert.dns_challenge ? ' · DNS challenge' : ''}` : 'Custom — у издателя сертификата';
return 'Автоматически в Homegate';
}