Files
homegate/ui/dist/settings.js
DizelBadCoder a83d897b70
All checks were successful
Test and publish Homegate / checks (push) Successful in 29s
Test and publish Homegate / publish (push) Successful in 12m46s
Add first-run web setup and Compose without environment or secrets
2026-10-14 03:26:50 +03:00

71 lines
7.3 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 renderManagedSettings() {
const c = data.config, links = data.connections, first = data.setup_required;
const passwordField = (name, title) => `<label class="field full">${title}<input name="${name}" type="password" autocomplete="new-password" placeholder="${links[name + '_set'] ? 'Сохранён. Оставьте пустым, чтобы не менять' : 'Пароль существующего сервиса'}" ${name === 'npm_password' && !links.npm_password_set ? 'required' : ''}></label>`;
return heading(first ? 'Подключим вашу домашнюю сеть' : 'Настройки и подключения',
first ? 'Заполните адреса здесь — Homegate сохранит настройки и начнёт работать.' : 'Все параметры сохраняются здесь и применяются автоматически.') + `
<div class="settings-grid"><form id="settings-form" class="panel">
<section class="form-section"><h2>Ваша сеть</h2><p>Сервисы будут открываться через Nginx Proxy Manager.</p>
<div class="form-grid">
<label class="field">IP Nginx Proxy Manager<input name="proxy_ip" value="${esc(c.proxy_ip)}" placeholder="192.168.0.11" required><small>Адрес, на который должны указывать домены сервисов.</small></label>
<label class="field">Обновление, секунд<input name="interval_seconds" type="number" min="30" max="3600" value="${c.interval_seconds || 60}" required></label>
<label class="field full">Домашние подсети<textarea name="allowed_networks" rows="2" placeholder="192.168.0.0/24" required>${esc(c.allowed_networks.join('\n'))}</textarea><small>Укажите вашу LAN. Можно несколько подсетей, по одной в строке.</small></label>
<label class="field full">Доменные зоны<textarea name="domain_zones" rows="2" required>${esc((c.domain_zones || ['home','home.arpa']).join('\n'))}</textarea><small>Например: home, home.arpa, lab.internal.</small></label>
</div>
</section>
<section class="form-section"><h2>Nginx Proxy Manager</h2><p>Homegate создаёт прокси и загружает сертификаты через API.</p>
<div class="form-grid">
<label class="field full">Адрес панели NPM<input name="npm_url" type="url" value="${esc(links.npm_url)}" placeholder="http://192.168.0.11:81" required><small>Без /api в конце.</small></label>
<label class="field full">Логин NPM<input name="npm_identity" value="${esc(links.npm_identity)}" placeholder="admin@example.com" autocomplete="username" required></label>
${passwordField('npm_password', 'Пароль NPM')}
</div>
</section>
<section class="form-section"><h2>DNS</h2><div class="form-grid">
<label class="field full">Создание DNS-записей<select name="dns_mode"><option value="pihole6" ${c.dns_mode !== 'manual' ? 'selected' : ''}>Автоматически — Pi-hole 6</option><option value="manual" ${c.dns_mode === 'manual' ? 'selected' : ''}>Вручную — другой DNS</option></select></label>
<div id="pihole-fields" class="field full" ${c.dns_mode === 'manual' ? 'hidden' : ''}>
<label class="field">Адрес Pi-hole<input name="pihole_url" type="url" value="${esc(links.pihole_url)}" placeholder="http://192.168.0.2" ${c.dns_mode !== 'manual' ? 'required' : ''}><small>Без /admin и /api в конце.</small></label>
${passwordField('pihole_password', 'Пароль Pi-hole')}
</div>
</div></section>
<section class="form-section"><details><summary>Дополнительные настройки</summary><div class="form-grid">
<label class="field full">URL SSH-конфига<input name="ssh_public_url" type="url" value="${esc(links.ssh_public_url)}" placeholder="${esc(sshUrl())}"><small>Оставьте пустым для адреса этого сервера на порту 8099.</small></label>
<label class="field full">Корневой сертификат API, PEM<textarea name="api_ca_pem" rows="4" placeholder="-----BEGIN CERTIFICATE-----">${esc(links.api_ca_pem)}</textarea><small>Нужен только если HTTPS API NPM или Pi-hole использует собственный CA.</small></label>
</div></details><div id="settings-error" class="form-error" hidden></div></section>
<div class="form-footer"><button class="btn primary" type="submit">${icon('check',14)} ${first ? 'Сохранить и начать' : 'Сохранить и применить'}</button></div>
</form><div class="stack"><section class="panel panel-pad"><div class="panel-heading">${first ? 'Всё настраивается здесь' : 'Подключения'}</div>
<p class="panel-description">Адреса, домены и доступ к вашим сервисам сохраняются на сервере. После перезапуска ничего вводить заново не нужно.</p>
<div class="integration"><span class="integration-icon">${icon('route',19)}</span><div><strong>Nginx Proxy Manager</strong><small>Прокси и HTTPS для ваших VM</small></div></div>
<div class="integration"><span class="integration-icon">${icon('globe',19)}</span><div><strong>Pi-hole</strong><small>Локальные DNS-записи</small></div></div>
<p class="note">Пароли в форме — от уже работающих NPM и Pi-hole. Панель Homegate открывается без логина.</p>
</section>${!first ? statusStrip() : ''}</div></div>`;
}
function bindManagedSettings(form) {
form.elements.dns_mode.addEventListener('change', () => {
const manual = form.elements.dns_mode.value === 'manual';
document.querySelector('#pihole-fields').hidden = manual;
form.elements.pihole_url.required = !manual;
});
}
async function saveManagedSettings(event) {
event.preventDefault();
const form = event.target, fields = new FormData(form), config = clone(data.config);
const list = name => fields.get(name).split(/\n|,/).map(value => value.trim()).filter(Boolean);
Object.assign(config, {proxy_ip: fields.get('proxy_ip').trim(), allowed_networks: list('allowed_networks'),
domain_zones: list('domain_zones'), dns_mode: fields.get('dns_mode'), interval_seconds: Number(fields.get('interval_seconds'))});
const connections = Object.fromEntries(['npm_url','npm_identity','npm_password','pihole_url','pihole_password','ssh_public_url','api_ca_pem'].map(key => [key, fields.get(key)]));
const first = data.setup_required, button = form.querySelector('[type=submit]');
button.disabled = true;
try {
data = await api('/api/settings', {config, connections, revision: data.revision});
settingsDirty = false;
if(first) location.hash = 'services';
render();
toast(first ? 'Готово. Добавьте первый сервис.' : 'Настройки сохранены. Подключения обновляются.');
} catch(error) {
document.querySelector('#settings-error').hidden = false;
document.querySelector('#settings-error').textContent = friendlyError(error);
button.disabled = false;
}
}