panel: shared nav, account settings, backup page, connection settings

Phase 12 (UI/UX). The navigation bar now renders once from layout.html
instead of being copied into each content template, so it is present on
every authenticated page — including the domain page and its delete
confirmation, which had no links at all — and the current page is
highlighted via .Active rather than quietly dropping out of the list.

New /account page changes the administrator's username and/or password:
the current password is required and the attempt is throttled on the same
limiter as the login form, so this route cannot be used to brute-force
past that limit. A password change invalidates every other session while
keeping the one performing it; a rename carries that session over.

Backup and domain import move from a card in the middle of the domain
list to their own /backup page, one card each; the handlers themselves
are unchanged, only the page the import form renders its errors on.

The domain page gains a "Sending server settings" card (server, port,
encryption) so a client can be configured without reading the docs; 587
is listed only when SUBMISSION_ENABLE is true for this deployment, which
is a deploy-time flag the panel cannot verify at runtime.

Client-side (static/panel.js, no libraries): Copy buttons on the values
that get carried elsewhere (DKIM record, new application credentials,
server name), and the Addresses field is hidden while the address mode is
wildcard, where the server ignores it.

Verified in a container on the dev server: setup, login, every page's
nav and active item, domain and application creation, all account-form
paths including cross-session invalidation, import errors, full backup
download. gofmt/vet/test/docker build green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-01 21:34:59 +03:00
parent 1f29bef87a
commit 147072dbb9
28 changed files with 720 additions and 282 deletions
+168
View File
@@ -0,0 +1,168 @@
package web
import (
"errors"
"net/http"
"strings"
"codeberg.org/mix/selfpost/internal/store"
"golang.org/x/crypto/bcrypt"
)
// handleAccount serves the administrator's own account settings: the username
// and password chosen during setup are the only panel credentials (spec 7.6.1),
// and until now they could be changed only by recreating the state. Changing
// them here never touches application SASL logins, which are a separate
// identity system (spec 5.1).
func (s *Server) handleAccount(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
s.renderAccount(w, r, http.StatusOK, "", currentUser(r))
case http.MethodPost:
s.submitAccount(w, r)
default:
w.Header().Set("Allow", "GET, POST")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
// renderAccount draws the settings form. formUsername repopulates the username
// field after a rejected submission; the password fields are never repopulated.
func (s *Server) renderAccount(w http.ResponseWriter, r *http.Request, status int, formErr, formUsername string) {
s.render(w, status, "account", map[string]any{
"Title": "SelfPost — account",
"User": currentUser(r),
"Active": "account",
"FormUsername": formUsername,
"Error": formErr,
"Flash": accountFlash(r),
})
}
// accountFlash maps a fixed redirect flag to a fixed message, so status text
// after a redirect is never attacker-influenced.
func accountFlash(r *http.Request) string {
switch r.URL.Query().Get("updated") {
case "username":
return "Username changed."
case "password":
return "Password changed. Any other signed-in sessions were signed out."
case "both":
return "Username and password changed. Any other signed-in sessions were signed out."
default:
return ""
}
}
// submitAccount applies a username and/or password change. The current password
// is always required, so a stolen session alone cannot lock the administrator
// out of their own panel, and the attempt is throttled on the same limiter as
// the login form so this route cannot be used to brute-force the password past
// that limit (spec 7.6.5).
func (s *Server) submitAccount(w http.ResponseWriter, r *http.Request) {
if !s.loginLimiter.Allow(clientIP(r, s.trustedProxies)) {
s.renderAccount(w, r, http.StatusTooManyRequests,
"Too many attempts. Please wait and try again.", currentUser(r))
return
}
if err := r.ParseForm(); err != nil {
s.renderAccount(w, r, http.StatusBadRequest, "Invalid form submission.", currentUser(r))
return
}
username := strings.TrimSpace(r.PostFormValue("username"))
current := r.PostFormValue("current_password")
password := r.PostFormValue("new_password")
confirm := r.PostFormValue("new_password_confirm")
admin, err := s.store.GetAdmin()
if err != nil {
logf("panel: account: get admin failed: %v", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
if username == "" {
username = admin.Username
}
if err := bcrypt.CompareHashAndPassword([]byte(admin.PasswordHash), []byte(current)); err != nil {
s.renderAccount(w, r, http.StatusUnauthorized, "Current password is incorrect.", username)
return
}
renaming := username != admin.Username
if renaming {
if err := validateUsername(username); err != nil {
s.renderAccount(w, r, http.StatusBadRequest, err.Error(), username)
return
}
}
// An empty pair of new-password fields means "leave the password alone", so
// the username can be changed on its own.
repassword := password != "" || confirm != ""
if repassword {
if password != confirm {
s.renderAccount(w, r, http.StatusBadRequest, "New passwords do not match.", username)
return
}
if err := validateAdminPassword(password); err != nil {
s.renderAccount(w, r, http.StatusBadRequest, err.Error(), username)
return
}
}
if !renaming && !repassword {
s.renderAccount(w, r, http.StatusBadRequest,
"Nothing to change: enter a new username, a new password, or both.", username)
return
}
hash := admin.PasswordHash
if repassword {
newHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
logf("panel: account: hashing password failed: %v", err)
s.renderAccount(w, r, http.StatusInternalServerError,
"Internal error. Please try again.", username)
return
}
hash = string(newHash)
}
if err := s.store.UpdateAdmin(username, hash); err != nil {
logf("panel: account: update admin failed: %v", err)
msg := "Could not save the changes. Please check the logs and try again."
if errors.Is(err, store.ErrNoAdmin) {
msg = "There is no administrator account to update."
}
s.renderAccount(w, r, http.StatusInternalServerError, msg, username)
return
}
// Keep this session usable under the new name, and — when the password
// changed — drop every other session so a cookie captured under the old
// password stops working.
if c, err := r.Cookie(sessionCookie); err == nil {
if renaming {
s.sessions.Rename(c.Value, username)
}
if repassword {
s.sessions.DestroyOthers(c.Value)
}
}
logf("panel: administrator account updated (username changed: %t, password changed: %t)", renaming, repassword)
http.Redirect(w, r, "/account?updated="+updatedFlag(renaming, repassword), http.StatusSeeOther)
}
// updatedFlag names what changed, for the fixed post-redirect flash message.
func updatedFlag(renamed, repassword bool) string {
switch {
case renamed && repassword:
return "both"
case renamed:
return "username"
default:
return "password"
}
}
+24 -18
View File
@@ -95,24 +95,30 @@ func (s *Server) renderDomainDetail(w http.ResponseWriter, r *http.Request, stat
}
s.render(w, status, "domain_detail", map[string]any{
"Title": "SelfPost — " + d.Name,
"User": currentUser(r),
"Domain": d,
"Record": record,
"Apps": appViews,
"Error": view.FormErr,
"FormLogin": view.FormLogin,
"FormMode": view.FormMode,
"FormAddrs": view.FormAddrs,
"NewCred": view.NewCred,
"Flash": detailFlash(r),
"Wildcard": store.AddressModeWildcard,
"List": store.AddressModeList,
"RateLimitErr": view.RateLimitErr,
"DomainHasRL": domainRLok && domainRL.Active(),
"DomainRLIPs": strings.Join(domainRL.AllowedIPs, "\n"),
"DomainRLMax": intOrBlank(domainRL.MaxMessages),
"DomainRLWin": windowOrDefault(domainRL.WindowSeconds),
"Title": "SelfPost — " + d.Name,
"User": currentUser(r),
"Active": "domains",
"Domain": d,
"Record": record,
// Client connection settings (the same for every domain on this
// instance): the hostname clients connect to, and whether the optional
// submission listener is enabled in this deployment.
"Hostname": s.cfg.Hostname,
"SubmissionEnabled": s.cfg.SubmissionEnabled,
"Apps": appViews,
"Error": view.FormErr,
"FormLogin": view.FormLogin,
"FormMode": view.FormMode,
"FormAddrs": view.FormAddrs,
"NewCred": view.NewCred,
"Flash": detailFlash(r),
"Wildcard": store.AddressModeWildcard,
"List": store.AddressModeList,
"RateLimitErr": view.RateLimitErr,
"DomainHasRL": domainRLok && domainRL.Active(),
"DomainRLIPs": strings.Join(domainRL.AllowedIPs, "\n"),
"DomainRLMax": intOrBlank(domainRL.MaxMessages),
"DomainRLWin": windowOrDefault(domainRL.WindowSeconds),
})
}
+25 -7
View File
@@ -17,6 +17,24 @@ import (
// room while refusing anything large enough to be an abuse attempt.
const maxImportBytes = 1 << 20 // 1 MiB
// handleBackupPage renders the backup/migration screen: the full-server backup
// and the domain import are separate actions with different risk, so each gets
// its own card here rather than sharing a block on the domain list.
func (s *Server) handleBackupPage(w http.ResponseWriter, r *http.Request) {
s.renderBackupPage(w, r, http.StatusOK, "")
}
// renderBackupPage draws the page; importErr surfaces a failed domain import
// (spec 7.5.B) next to the form that produced it.
func (s *Server) renderBackupPage(w http.ResponseWriter, r *http.Request, status int, importErr string) {
s.render(w, status, "backup", map[string]any{
"Title": "SelfPost — backup",
"User": currentUser(r),
"Active": "backup",
"ImportErr": importErr,
})
}
// handleBackup streams a full-server backup as a download (spec 7.5.A). It is an
// authenticated admin action (this handler sits behind the auth middleware). The
// archive carries DKIM private keys, the admin password hash and SASL
@@ -75,17 +93,17 @@ func (s *Server) handleExportDomain(w http.ResponseWriter, r *http.Request) {
// domain on this instance (spec 7.5.B). The domain name is normalised and
// validated here (spec 7.6.2); the domain service validates the selector, each
// login and address, and the DKIM key before writing anything. On success it
// redirects to the new domain's page; on failure it re-renders the dashboard
// with a friendly message.
// redirects to the new domain's page; on failure it re-renders the backup page,
// where the import form lives, with a friendly message.
func (s *Server) handleImportDomain(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxImportBytes)
if err := r.ParseMultipartForm(maxImportBytes); err != nil {
s.renderDashboard(w, r, http.StatusBadRequest, "", "", "Could not read the uploaded file (too large or not a valid upload).")
s.renderBackupPage(w, r, http.StatusBadRequest, "Could not read the uploaded file (too large or not a valid upload).")
return
}
file, _, err := r.FormFile("file")
if err != nil {
s.renderDashboard(w, r, http.StatusBadRequest, "", "", "Choose a domain export file to import.")
s.renderBackupPage(w, r, http.StatusBadRequest, "Choose a domain export file to import.")
return
}
defer file.Close()
@@ -94,7 +112,7 @@ func (s *Server) handleImportDomain(w http.ResponseWriter, r *http.Request) {
dec := json.NewDecoder(file)
dec.DisallowUnknownFields()
if err := dec.Decode(&exp); err != nil {
s.renderDashboard(w, r, http.StatusBadRequest, "", "", "That file is not a valid SelfPost domain export.")
s.renderBackupPage(w, r, http.StatusBadRequest, "That file is not a valid SelfPost domain export.")
return
}
@@ -102,7 +120,7 @@ func (s *Server) handleImportDomain(w http.ResponseWriter, r *http.Request) {
// same gate the add-domain form uses (spec 7.6.2).
exp.Domain = normalizeDomain(exp.Domain)
if err := validateDomain(exp.Domain); err != nil {
s.renderDashboard(w, r, http.StatusBadRequest, "", "", "Invalid domain in export file: "+err.Error())
s.renderBackupPage(w, r, http.StatusBadRequest, "Invalid domain in export file: "+err.Error())
return
}
@@ -110,7 +128,7 @@ func (s *Server) handleImportDomain(w http.ResponseWriter, r *http.Request) {
if err != nil {
logf("panel: import domain %q: %v", exp.Domain, err)
status, msg := importErrorMessage(err)
s.renderDashboard(w, r, status, "", "", msg)
s.renderBackupPage(w, r, status, msg)
return
}
http.Redirect(w, r, fmt.Sprintf("/domains/%d?imported=1", d.ID), http.StatusSeeOther)
+16 -16
View File
@@ -13,14 +13,13 @@ import (
// domains with their DKIM/selector and application counts, plus the add-domain
// form (spec 7.2.2). Applications and the send log arrive in later phases.
func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request) {
s.renderDashboard(w, r, http.StatusOK, "", "", "")
s.renderDashboard(w, r, http.StatusOK, "", "")
}
// renderDashboard renders the domain list. formErr and formName repopulate the
// add-domain form after a rejected submission; importErr surfaces a failed
// domain import (spec 7.5.B); flash surfaces a one-shot status message keyed by
// a redirect query flag (never reflected user input).
func (s *Server) renderDashboard(w http.ResponseWriter, r *http.Request, status int, formErr, formName, importErr string) {
// add-domain form after a rejected submission; flash surfaces a one-shot status
// message keyed by a redirect query flag (never reflected user input).
func (s *Server) renderDashboard(w http.ResponseWriter, r *http.Request, status int, formErr, formName string) {
domains, err := s.domains.List()
if err != nil {
logf("panel: dashboard: list domains: %v", err)
@@ -28,13 +27,13 @@ func (s *Server) renderDashboard(w http.ResponseWriter, r *http.Request, status
return
}
s.render(w, status, "dashboard", map[string]any{
"Title": "SelfPost",
"User": currentUser(r),
"Domains": domains,
"Error": formErr,
"FormName": formName,
"ImportErr": importErr,
"Flash": dashboardFlash(r),
"Title": "SelfPost",
"User": currentUser(r),
"Active": "domains",
"Domains": domains,
"Error": formErr,
"FormName": formName,
"Flash": dashboardFlash(r),
})
}
@@ -56,25 +55,25 @@ func dashboardFlash(r *http.Request) string {
// publish is shown (spec 7.2.3).
func (s *Server) handleAddDomain(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
s.renderDashboard(w, r, http.StatusBadRequest, "Invalid form submission.", "", "")
s.renderDashboard(w, r, http.StatusBadRequest, "Invalid form submission.", "")
return
}
raw := r.PostFormValue("name")
name := normalizeDomain(raw)
if err := validateDomain(name); err != nil {
s.renderDashboard(w, r, http.StatusBadRequest, err.Error(), raw, "")
s.renderDashboard(w, r, http.StatusBadRequest, err.Error(), raw)
return
}
d, err := s.domains.Add(name)
if err != nil {
if errors.Is(err, store.ErrDomainExists) {
s.renderDashboard(w, r, http.StatusConflict, "That domain is already configured.", raw, "")
s.renderDashboard(w, r, http.StatusConflict, "That domain is already configured.", raw)
return
}
logf("panel: add domain %q: %v", name, err)
s.renderDashboard(w, r, http.StatusInternalServerError,
"Could not add the domain. Please check the logs and try again.", raw, "")
"Could not add the domain. Please check the logs and try again.", raw)
return
}
http.Redirect(w, r, fmt.Sprintf("/domains/%d", d.ID), http.StatusSeeOther)
@@ -90,6 +89,7 @@ func (s *Server) handleDeleteConfirm(w http.ResponseWriter, r *http.Request) {
s.render(w, http.StatusOK, "domain_delete", map[string]any{
"Title": "SelfPost — delete " + d.Name,
"User": currentUser(r),
"Active": "domains",
"Domain": d,
})
}
+7 -4
View File
@@ -30,6 +30,7 @@ func (s *Server) handleSendLog(w http.ResponseWriter, r *http.Request) {
}
data["Title"] = "SelfPost — send log"
data["User"] = currentUser(r)
data["Active"] = "sendlog"
s.render(w, http.StatusOK, "sendlog", data)
}
@@ -112,6 +113,7 @@ func (s *Server) handleQueue(w http.ResponseWriter, r *http.Request) {
s.render(w, http.StatusOK, "queue", map[string]any{
"Title": "SelfPost — mail queue",
"User": currentUser(r),
"Active": "queue",
"Output": out,
"Error": errText,
})
@@ -142,10 +144,11 @@ func readQueue() (string, string) {
func (s *Server) handleLogTail(w http.ResponseWriter, r *http.Request) {
lines, errText := s.readLogTail()
s.render(w, http.StatusOK, "logtail", map[string]any{
"Title": "SelfPost — mail log",
"User": currentUser(r),
"Lines": lines,
"Error": errText,
"Title": "SelfPost — mail log",
"User": currentUser(r),
"Active": "logtail",
"Lines": lines,
"Error": errText,
})
}
+26
View File
@@ -54,6 +54,32 @@ func (s *sessionStore) Lookup(token string) (string, bool) {
return sess.username, true
}
// Rename updates the username carried by a session, keeping its expiry. It is
// used when the administrator renames their own account so the current session
// keeps working under the new name.
func (s *sessionStore) Rename(token, username string) {
s.mu.Lock()
defer s.mu.Unlock()
if sess, ok := s.sessions[token]; ok {
sess.username = username
s.sessions[token] = sess
}
}
// DestroyOthers invalidates every session except keep. It is called when the
// administrator changes their password: a stolen cookie issued under the old
// password must stop working, while the admin performing the change stays
// signed in.
func (s *sessionStore) DestroyOthers(keep string) {
s.mu.Lock()
defer s.mu.Unlock()
for token := range s.sessions {
if token != keep {
delete(s.sessions, token)
}
}
}
// Destroy invalidates a session token (logout).
func (s *sessionStore) Destroy(token string) {
s.mu.Lock()
+36
View File
@@ -0,0 +1,36 @@
package web
import "testing"
func TestSessionRename(t *testing.T) {
s := newSessionStore()
token := s.Create("admin")
s.Rename(token, "operator")
name, ok := s.Lookup(token)
if !ok {
t.Fatal("session lost after rename")
}
if name != "operator" {
t.Fatalf("session username = %q, want %q", name, "operator")
}
}
// A password change must invalidate every other session (so a cookie captured
// under the old password stops working) while keeping the one performing the
// change signed in.
func TestSessionDestroyOthers(t *testing.T) {
s := newSessionStore()
keep := s.Create("admin")
other := s.Create("admin")
s.DestroyOthers(keep)
if _, ok := s.Lookup(keep); !ok {
t.Fatal("current session was destroyed")
}
if _, ok := s.Lookup(other); ok {
t.Fatal("other session survived")
}
}
+64
View File
@@ -0,0 +1,64 @@
// Panel progressive enhancement. Everything here is optional convenience: the
// pages are fully usable with JavaScript disabled or blocked, and nothing is
// sent to the server from this file.
(function () {
"use strict";
// --- Copy buttons on .code values ------------------------------------
// Values that get carried into another interface (a DNS panel, a mail
// client) sit in a .code-row wrapper next to a Copy button. The text is read
// from the .code element itself, so it can never drift from what is shown.
// navigator.clipboard needs a secure context (HTTPS or localhost); over plain
// HTTP in development it is simply absent, in which case the value stays
// selectable by hand.
document.addEventListener("click", function (ev) {
var button = ev.target.closest("button.copy");
if (!button) {
return;
}
var row = button.closest(".code-row");
var code = row && row.querySelector(".code");
if (!code || !navigator.clipboard) {
return;
}
navigator.clipboard.writeText(code.textContent).then(function () {
var original = button.textContent;
button.textContent = "Copied";
setTimeout(function () {
button.textContent = original;
}, 1500);
}, function () {
/* Clipboard refused (permissions, insecure context): leave the page be. */
});
});
// --- Address list shown only in list mode -----------------------------
// The "Addresses" field applies to list mode only; in wildcard mode the
// server ignores it, so hiding it removes a field that does nothing. The
// toggle runs on load too, because the edit form of an existing application
// may already be set to list mode.
function syncAddressField(select) {
var form = select.closest("form");
var field = form && form.querySelector("[data-addresses]");
if (!field) {
return;
}
// The mode values come from the server (store.AddressModeList), so the
// select carries the one that means "list" rather than this script
// hard-coding it.
field.hidden = select.value !== select.dataset.listMode;
}
function initAddressFields(root) {
root.querySelectorAll("select[data-list-mode]").forEach(function (select) {
syncAddressField(select);
select.addEventListener("change", function () {
syncAddressField(select);
});
});
}
document.addEventListener("DOMContentLoaded", function () {
initAddressFields(document);
});
})();
+10
View File
@@ -26,6 +26,8 @@ var pageFiles = map[string][]string{
"setup": {"templates/setup.html"},
"login": {"templates/login.html"},
"dashboard": {"templates/dashboard.html"},
"account": {"templates/account.html"},
"backup": {"templates/backup.html"},
"domain_detail": {"templates/domain_detail.html"},
"domain_delete": {"templates/domain_delete.html"},
"sendlog": {"templates/sendlog.html", "templates/sendlog_rows.html"},
@@ -72,6 +74,14 @@ func (s *Server) render(w http.ResponseWriter, status int, page string, data any
http.Error(w, "template not found", http.StatusInternalServerError)
return
}
// The layout's navigation compares .Active against each item, so the key
// must exist on every authenticated page. Defaulting it here keeps a page
// that forgets it from failing to render — it simply highlights nothing.
if m, ok := data.(map[string]any); ok {
if _, has := m["Active"]; !has {
m["Active"] = ""
}
}
var buf bytes.Buffer
if err := tmpl.ExecuteTemplate(&buf, "layout.html", data); err != nil {
logf("panel: render %s: %v", page, err)
+32
View File
@@ -0,0 +1,32 @@
{{define "content"}}
<h1>Account</h1>
{{if .Flash}}<div class="flash">{{.Flash}}</div>{{end}}
<div class="card narrow">
<h2>Panel credentials</h2>
<p class="muted">These are the credentials for this control panel only.
Applications keep their own logins and passwords, which are not affected.</p>
{{if .Error}}<p class="error">{{.Error}}</p>{{end}}
<form method="post" action="/account">
<label for="username">Username</label>
<input id="username" name="username" autocomplete="username"
autocapitalize="none" spellcheck="false" value="{{.FormUsername}}" required>
<label for="current_password">Current password</label>
<input id="current_password" name="current_password" type="password"
autocomplete="current-password" required>
<label for="new_password">New password</label>
<input id="new_password" name="new_password" type="password" autocomplete="new-password">
<label for="new_password_confirm">Confirm new password</label>
<input id="new_password_confirm" name="new_password_confirm" type="password" autocomplete="new-password">
<button type="submit">Save changes</button>
</form>
<p class="muted">Leave both new-password fields empty to change the username
only. Changing the password signs out every other session; this one stays
signed in.</p>
</div>
{{end}}
+32
View File
@@ -0,0 +1,32 @@
{{define "content"}}
<h1>Backup &amp; migration</h1>
<div class="card">
<h2>Full backup</h2>
<p class="muted">Download a full backup of all persistent state — the database,
every domain's DKIM key and the application credentials. Use it to move the
whole server to a new machine: restore it into a container of the
<strong>same SelfPost version</strong>, with the same data mount, before first
start. TLS certificates and the mail queue are not included.</p>
<p class="muted"><strong>The backup file is a secret</strong> (it contains
private keys and credentials). Store and transfer it securely and delete it
once the restore succeeds.</p>
<form class="inline" method="post" action="/backup">
<button type="submit">Download full backup</button>
</form>
</div>
<div class="card">
<h2>Import a domain</h2>
<p class="muted">Move a single domain here from another SelfPost instance using
a domain export file (from that domain's page). Its DKIM key and application
passwords come across, so the published DNS record needs no change. The export
file is a secret, like a full backup.</p>
{{if .ImportErr}}<p class="error">{{.ImportErr}}</p>{{end}}
<form method="post" action="/domains/import" enctype="multipart/form-data">
<label for="importfile">Domain export file</label>
<input id="importfile" name="file" type="file" accept=".json,application/json" required>
<button type="submit">Import domain</button>
</form>
</div>
{{end}}
-34
View File
@@ -2,16 +2,9 @@
<div class="topbar">
<h1>SelfPost</h1>
<div class="actions muted">
<span>{{.User}}</span>
<a href="/sendlog">Send log</a>
<a href="/queue">Queue</a>
<a href="/logtail">Log</a>
<form class="inline" method="post" action="/reload">
<button type="submit">Reload</button>
</form>
<form class="inline" method="post" action="/logout">
<button type="submit">Sign out</button>
</form>
</div>
</div>
@@ -53,31 +46,4 @@
<p class="muted">No domains yet. Add one above to get started.</p>
{{end}}
</div>
<div class="card">
<h2>Backup &amp; migration</h2>
<p class="muted">Download a full backup of all persistent state — the database,
every domain's DKIM key and the application credentials. Use it to move the
whole server to a new machine: restore it into a container of the
<strong>same SelfPost version</strong>, with the same data mount, before first
start. TLS certificates and the mail queue are not included.</p>
<p class="muted"><strong>The backup file is a secret</strong> (it contains
private keys and credentials). Store and transfer it securely and delete it
once the restore succeeds.</p>
<form class="inline" method="post" action="/backup">
<button type="submit">Download full backup</button>
</form>
<h2>Import a domain</h2>
<p class="muted">Move a single domain here from another SelfPost instance using
a domain export file (from that domain's page). Its DKIM key and application
passwords come across, so the published DNS record needs no change. The export
file is a secret, like a full backup.</p>
{{if .ImportErr}}<p class="error">{{.ImportErr}}</p>{{end}}
<form method="post" action="/domains/import" enctype="multipart/form-data">
<label for="importfile">Domain export file</label>
<input id="importfile" name="file" type="file" accept=".json,application/json" required>
<button type="submit">Import domain</button>
</form>
</div>
{{end}}
+1 -9
View File
@@ -1,13 +1,5 @@
{{define "content"}}
<div class="topbar">
<h1>Delete {{.Domain.Name}}</h1>
<div class="actions muted">
<span>{{.User}}</span>
<form class="inline" method="post" action="/logout">
<button type="submit">Sign out</button>
</form>
</div>
</div>
<h1>Delete {{.Domain.Name}}</h1>
<a class="back" href="/domains/{{.Domain.ID}}">&larr; Back to {{.Domain.Name}}</a>
+51 -20
View File
@@ -1,13 +1,5 @@
{{define "content"}}
<div class="topbar">
<h1>{{.Domain.Name}}</h1>
<div class="actions muted">
<span>{{.User}}</span>
<form class="inline" method="post" action="/logout">
<button type="submit">Sign out</button>
</form>
</div>
</div>
<h1>{{.Domain.Name}}</h1>
<a class="back" href="/">&larr; All domains</a>
@@ -20,9 +12,15 @@
<p class="muted">This password is shown <strong>once only</strong> and is not
stored. Copy it now — if it is lost, regenerate a new one.</p>
<label>Login</label>
<span class="code">{{.NewCred.Login}}</span>
<div class="code-row">
<span class="code">{{.NewCred.Login}}</span>
<button type="button" class="copy">Copy</button>
</div>
<label>Password</label>
<span class="code">{{.NewCred.Password}}</span>
<div class="code-row">
<span class="code">{{.NewCred.Password}}</span>
<button type="button" class="copy">Copy</button>
</div>
</div>
{{end}}
@@ -32,18 +30,47 @@
It is not a secret and can be viewed at any time.</p>
<label>Host / name</label>
<span class="code">{{.Record.Name}}</span>
<div class="code-row">
<span class="code">{{.Record.Name}}</span>
<button type="button" class="copy">Copy</button>
</div>
<label>Type</label>
<span class="code">TXT</span>
<label>Value</label>
<span class="code">{{.Record.Value}}</span>
<div class="code-row">
<span class="code">{{.Record.Value}}</span>
<button type="button" class="copy">Copy</button>
</div>
<p class="muted">Also configure SPF and DMARC for the domain (see the
documentation). Mail is signed with selector <strong>{{.Domain.DKIMSelector}}</strong>.</p>
</div>
<div class="card">
<h2>Sending server settings</h2>
<p class="muted">Point the mail client or script at these settings and
authenticate with an application login and password from the
<strong>Applications</strong> section below. They are the same for every
domain on this server.</p>
<label>Server</label>
<div class="code-row">
<span class="code">{{.Hostname}}</span>
<button type="button" class="copy">Copy</button>
</div>
<label>Port and encryption</label>
<span class="code">465 — SSL/TLS (implicit){{if .SubmissionEnabled}}
587 — STARTTLS (submission){{end}}</span>
<p class="muted">Authentication is required on every port. The username is the
application's login (see the table below) and the password is the one shown
once when that application was created or its password regenerated — if it was
lost, generate a new one.</p>
</div>
<div class="card">
<h2>Applications</h2>
<p class="muted">Each application is a SASL login/password an app or script
@@ -70,13 +97,15 @@
<summary>Edit mode</summary>
<form method="post" action="/applications/{{.ID}}/mode">
<label>Address mode</label>
<select name="mode">
<select name="mode" data-list-mode="{{$.List}}">
<option value="{{$.Wildcard}}" {{if eq .AddressMode $.Wildcard}}selected{{end}}>Any address of the domain</option>
<option value="{{$.List}}" {{if eq .AddressMode $.List}}selected{{end}}>Specific addresses (list)</option>
</select>
<label>Addresses (for list mode; one per line or comma-separated)</label>
<textarea name="addresses" rows="3" placeholder="alerts@{{$.Domain.Name}}">{{range $i, $a := .Addresses}}{{if $i}}
<div data-addresses>
<label>Addresses (one per line or comma-separated)</label>
<textarea name="addresses" rows="3" placeholder="alerts@{{$.Domain.Name}}">{{range $i, $a := .Addresses}}{{if $i}}
{{end}}{{$a}}{{end}}</textarea>
</div>
<button type="submit">Save mode</button>
</form>
</details>
@@ -161,14 +190,16 @@
value="{{.FormLogin}}" required>
<label for="mode">Address mode</label>
<select id="mode" name="mode">
<select id="mode" name="mode" data-list-mode="{{.List}}">
<option value="{{.Wildcard}}" {{if eq .FormMode .Wildcard}}selected{{end}}>Any address of the domain</option>
<option value="{{.List}}" {{if eq .FormMode .List}}selected{{end}}>Specific addresses (list)</option>
</select>
<label for="addresses">Addresses (for list mode; one per line or comma-separated)</label>
<textarea id="addresses" name="addresses" rows="3"
placeholder="alerts@{{.Domain.Name}}">{{.FormAddrs}}</textarea>
<div data-addresses>
<label for="addresses">Addresses (one per line or comma-separated)</label>
<textarea id="addresses" name="addresses" rows="3"
placeholder="alerts@{{.Domain.Name}}">{{.FormAddrs}}</textarea>
</div>
{{if .Error}}<p class="error">{{.Error}}</p>{{end}}
<button type="submit">Create application</button>
+53
View File
@@ -6,6 +6,7 @@
<title>{{.Title}}</title>
<link rel="icon" href="/static/favicon.png" type="image/png">
<script src="/static/htmx.min.js" defer></script>
<script src="/static/panel.js" defer></script>
<style>
:root { color-scheme: light dark; }
* { box-sizing: border-box; }
@@ -75,11 +76,63 @@
details form { margin-top: 0.6rem; }
.credential { border-color: #f5c518; background: #fffbeb; }
@media (prefers-color-scheme: dark) { .credential { background: #2a2408 !important; border-color: #6b5a10 !important; } }
/* Panel navigation: rendered once from this layout, so it is present on every
authenticated page without each content template having to include it. */
.nav {
display: flex; flex-wrap: wrap; justify-content: space-between; align-items: baseline;
gap: 0.4rem 1rem; margin-bottom: 1.2rem; padding-bottom: 0.6rem;
border-bottom: 1px solid #e2e5e9;
}
@media (prefers-color-scheme: dark) { .nav { border-color: #2b3138 !important; } }
.nav .links, .nav .session { display: flex; flex-wrap: wrap; gap: 0.2rem 0.9rem; align-items: baseline; }
.nav .links a, .nav .links [aria-current] { padding: 0.2rem 0.5rem; border-radius: 6px; }
.nav .links [aria-current] {
font-weight: 600; color: #1b1f24; background: #e6ebf5; box-shadow: inset 0 -2px 0 #2563eb;
}
@media (prefers-color-scheme: dark) {
.nav .links [aria-current] { color: #e6e8eb !important; background: #22303f !important; }
}
.code-row { display: flex; align-items: flex-start; gap: 0.5rem; }
.code-row .code { flex: 1; min-width: 0; }
button.copy {
flex: none; margin-top: 0.3rem; padding: 0.45rem 0.7rem; font-size: 0.8rem;
background: #eef1f5; color: #2563eb; border: 1px solid #cfd4da;
}
button.copy:hover { background: #e2e7ee; }
@media (prefers-color-scheme: dark) {
button.copy { background: #22262b !important; border-color: #2b3138 !important; }
button.copy:hover { background: #2b3138 !important; }
}
</style>
</head>
<body>
<main>
{{if .User}}{{template "nav" .}}{{end}}
{{template "content" .}}
</main>
</body>
</html>{{end}}
{{/* nav is the panel's navigation bar. It is rendered here, from the layout, so
every authenticated page has it without the page's own template having to
remember to include it; .Active names the current page so it is highlighted
instead of linking to itself. Unauthenticated pages (login, setup) carry no
.User and get no nav. */}}
{{define "nav"}}
<nav class="nav">
<div class="links">
{{if eq .Active "domains"}}<span aria-current="page">Domains</span>{{else}}<a href="/">Domains</a>{{end}}
{{if eq .Active "sendlog"}}<span aria-current="page">Send log</span>{{else}}<a href="/sendlog">Send log</a>{{end}}
{{if eq .Active "queue"}}<span aria-current="page">Queue</span>{{else}}<a href="/queue">Queue</a>{{end}}
{{if eq .Active "logtail"}}<span aria-current="page">Log</span>{{else}}<a href="/logtail">Log</a>{{end}}
{{if eq .Active "backup"}}<span aria-current="page">Backup</span>{{else}}<a href="/backup">Backup</a>{{end}}
</div>
<div class="session">
<span class="muted">{{.User}}</span>
{{if eq .Active "account"}}<span aria-current="page">Account</span>{{else}}<a href="/account">Account</a>{{end}}
<form class="inline" method="post" action="/logout">
<button type="submit">Sign out</button>
</form>
</div>
</nav>
{{end}}
+1 -14
View File
@@ -1,18 +1,5 @@
{{define "content"}}
<div class="topbar">
<h1>Mail log</h1>
<div class="actions muted">
<span>{{.User}}</span>
<a href="/">Domains</a>
<a href="/sendlog">Send log</a>
<a href="/queue">Queue</a>
<form class="inline" method="post" action="/logout">
<button type="submit">Sign out</button>
</form>
</div>
</div>
<a class="back" href="/">&larr; Domains</a>
<h1>Mail log</h1>
<div class="card">
<h2>mail.log tail</h2>
+1 -14
View File
@@ -1,18 +1,5 @@
{{define "content"}}
<div class="topbar">
<h1>Mail queue</h1>
<div class="actions muted">
<span>{{.User}}</span>
<a href="/">Domains</a>
<a href="/sendlog">Send log</a>
<a href="/logtail">Log</a>
<form class="inline" method="post" action="/logout">
<button type="submit">Sign out</button>
</form>
</div>
</div>
<a class="back" href="/">&larr; Domains</a>
<h1>Mail queue</h1>
<div class="card">
<h2>postqueue -p</h2>
+1 -14
View File
@@ -1,18 +1,5 @@
{{define "content"}}
<div class="topbar">
<h1>Send log</h1>
<div class="actions muted">
<span>{{.User}}</span>
<a href="/">Domains</a>
<a href="/queue">Queue</a>
<a href="/logtail">Log</a>
<form class="inline" method="post" action="/logout">
<button type="submit">Sign out</button>
</form>
</div>
</div>
<a class="back" href="/">&larr; Domains</a>
<h1>Send log</h1>
<div class="card">
<h2>Filter</h2>
+47
View File
@@ -0,0 +1,47 @@
package web
import (
"bytes"
"strings"
"testing"
)
// The navigation is rendered from the layout, not copied into each page, so
// every page template must resolve it. This is what makes "the nav is on every
// authenticated page" a structural property instead of a checklist item.
func TestEveryPageResolvesNav(t *testing.T) {
tmpl, err := loadTemplates()
if err != nil {
t.Fatalf("loadTemplates: %v", err)
}
for name, page := range tmpl.pages {
if page.Lookup("nav") == nil {
t.Errorf("page %q does not resolve the shared nav template", name)
}
}
}
func TestNavMarksActivePage(t *testing.T) {
tmpl, err := loadTemplates()
if err != nil {
t.Fatalf("loadTemplates: %v", err)
}
var buf bytes.Buffer
err = tmpl.pages["dashboard"].ExecuteTemplate(&buf, "nav", map[string]any{
"User": "admin",
"Active": "queue",
})
if err != nil {
t.Fatalf("execute nav: %v", err)
}
out := buf.String()
if !strings.Contains(out, `<span aria-current="page">Queue</span>`) {
t.Errorf("active page is not marked:\n%s", out)
}
if strings.Contains(out, `href="/queue"`) {
t.Errorf("active page still links to itself:\n%s", out)
}
if !strings.Contains(out, `href="/sendlog"`) {
t.Errorf("inactive pages are not linked:\n%s", out)
}
}
+11 -1
View File
@@ -28,6 +28,11 @@ type Config struct {
// to true (spec 7.6.6); it exists as a knob only so the panel can be tested
// over plain HTTP in development, never for production.
CookieSecure bool
// SubmissionEnabled mirrors SUBMISSION_ENABLE: whether this deployment also
// runs the 587/STARTTLS submission listener next to the primary 465 one
// (spec 5). The panel only reports it on the domain page's connection
// settings; it is a deploy-time flag, not something the panel can verify.
SubmissionEnabled bool
// MailLogPath is where Postfix's delivery log lives, read by the mail.log
// monitoring view (spec 7.2.13). It is the same path the log-tailer role
// follows in cmd/panel.
@@ -132,7 +137,12 @@ func (s *Server) Handler() http.Handler {
authed.HandleFunc("POST /applications/{aid}/delete", s.handleDeleteApplication)
authed.HandleFunc("POST /reload", s.handleReload)
// Full-server backup download (spec 7.5.A).
// Administrator's own panel credentials.
authed.HandleFunc("/account", s.handleAccount)
// Backup and migration: the page with both actions (spec 7.5.A-B), and the
// full-server backup download itself.
authed.HandleFunc("GET /backup", s.handleBackupPage)
authed.HandleFunc("POST /backup", s.handleBackup)
// Monitoring screens (spec 7.2.11-13): each page and its HTMX polling