Add NPM certificate selection and read-only VDS certificate renewal sync
All checks were successful
Test and publish Homegate / checks (push) Successful in 28s
Test and publish Homegate / publish (push) Successful in 12m47s

This commit is contained in:
2026-10-15 05:12:03 +03:00
parent b305cc1ba8
commit eeffcfb616
18 changed files with 838 additions and 49 deletions

78
ui/dist/certificates.js vendored Normal file
View File

@@ -0,0 +1,78 @@
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="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>`;
}
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 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', enabled = mode.value !== 'homegate';
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 нужно обновлять у его издателя.',
remote_npm: 'NPM на VDS продлевает сертификат самостоятельно. Homegate проверяет его каждый цикл и копирует обновление домой. На VDS выполняется только чтение. Если интернет недоступен, используется последняя копия до окончания её срока. При выборе существующего Custom обновляется именно он.'
}[mode.value];
}
async function load() {
if(mode.value === 'homegate') 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' : 'Custom — у издателя сертификата';
return 'Автоматически в Homegate';
}