Files
selfpost/internal/web/setup.go
T
mix d49351c022 chore/docs: move to GitHub as the single home; drop archived-spec references
Codeberg is being retired as the project's public site, so every reference now
points at GitHub. That includes the Go module path (codeberg.org/mix/selfpost →
github.com/mixeme/selfpost): leaving an import path on a host that is going
away would break `go get` and `go install`, so this is not only a docs change.
Touches go.mod, test/e2e/go.mod, all imports, Makefile MODULE, the -ldflags
version stamp in build/Dockerfile and docs/development.md, the licence headers
in the SVG/HTML assets, and README (no more primary/mirror pair).

Comments no longer cite the archived specification. "spec 7.6.1", "spec 5.1"
and friends pointed into docs/archive/specification-v1.0.md, which is marked as
not a source of truth; each is now a reference to the live document that owns
the subject — architecture.md (with section), product.md, security.md or the
README. The review only asked for the 7.x refs (code-review.md § 4), but 4/5/6/
8/9 had the same defect, so they went too. Comments only, no behaviour change.

Also closes the remaining review items: architecture.md gained a Code layers
section with the layer diagram (A2), and TestParseDelivery gained the exotic
mail.log cases (§ 3).

Fixes a bug that last test found: the delivery-line pattern matched status=
greedily, taking the *last* occurrence on the line. Postfix appends the remote
server's reply verbatim, so a rejection whose reply quoted "status=sent" was
filed as a delivered message in the send log. It now takes the first status=
after the recipient, which is the real field.

R7 (CONTRIBUTING.md) moved to roadmap 2.x — one developer, no external PR flow,
so the file would have no audience yet. R1 (compose image tag) and the git tag
stay in roadmap § v1.x as the release-commit steps.

gofmt/go vet clean on both modules; go test ./... green except the three known
Windows-only failures (file perms, backslash paths, renaming an open file).
Not exercised on the dev server — no Docker locally.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 22:14:13 +03:00

137 lines
4.0 KiB
Go

package web
import (
"crypto/subtle"
"fmt"
"os"
"sync"
"time"
"github.com/mixeme/selfpost/internal/store"
)
// setupTokenTTL is the lifetime of a setup token (security.md). After it
// elapses the token is regenerated and re-announced on the next /setup hit.
const setupTokenTTL = 10 * time.Minute
// setupManager owns the one-time administrator setup token. The token itself is
// ephemeral (regenerated on restart or expiry) and lives only in memory; the
// persistent "setup complete" fact is the presence of the admin row in the
// store, so once that exists the token is gone for good (security.md).
type setupManager struct {
store *store.Store
hostname string
tokenPath string
mu sync.Mutex
token string
expiresAt time.Time
}
func newSetupManager(st *store.Store, hostname, tokenPath string) *setupManager {
return &setupManager{store: st, hostname: hostname, tokenPath: tokenPath}
}
// bootstrap runs once at startup. If setup is already complete it clears any
// stale token file; otherwise it mints and announces the first token.
func (m *setupManager) bootstrap() error {
done, err := m.store.AdminExists()
if err != nil {
return err
}
if done {
m.clearTokenFile()
return nil
}
m.mu.Lock()
defer m.mu.Unlock()
m.regenerateLocked()
return nil
}
// activeToken returns the current valid setup token, regenerating and
// re-announcing it if none exists or it has expired. It returns ("", false)
// once setup is complete — callers must treat that as "route gone" (404).
func (m *setupManager) activeToken() (string, bool) {
done, err := m.store.AdminExists()
if err != nil {
logf("panel: setup: admin check failed: %v", err)
return "", false
}
if done {
return "", false
}
m.mu.Lock()
defer m.mu.Unlock()
if m.token == "" || time.Now().After(m.expiresAt) {
m.regenerateLocked()
}
return m.token, true
}
// validate reports whether provided matches the active token, using a
// constant-time comparison to avoid leaking a correct prefix via timing
// (security.md). A mismatch does NOT regenerate or invalidate the token: failed
// attempts must not let an attacker DoS a legitimate setup (security.md).
func (m *setupManager) validate(provided string) bool {
token, ok := m.activeToken()
if !ok {
return false
}
return subtle.ConstantTimeCompare([]byte(provided), []byte(token)) == 1
}
// complete marks setup as finished: the admin row now exists, so drop the
// in-memory token and remove the on-disk copy.
func (m *setupManager) complete() {
m.mu.Lock()
m.token = ""
m.expiresAt = time.Time{}
m.mu.Unlock()
m.clearTokenFile()
}
// regenerateLocked mints a fresh token, announces it and mirrors it to disk.
// Caller holds m.mu.
func (m *setupManager) regenerateLocked() {
m.token = randomToken(16) // 128 bits of entropy (security.md)
m.expiresAt = time.Now().Add(setupTokenTTL)
m.announce(m.token)
}
// announce prints the setup link to the container log and writes it to the
// token file so it can be read either way (security.md).
func (m *setupManager) announce(token string) {
url := m.setupURL(token)
logf("panel: ==================================================================")
logf("panel: SelfPost first-run setup — open this one-time link within %s:", setupTokenTTL)
logf("panel: %s", url)
logf("panel: (also written to %s)", m.tokenPath)
logf("panel: ==================================================================")
if m.tokenPath == "" {
return
}
// 0600: the token is a bearer secret for creating the admin.
if err := os.WriteFile(m.tokenPath, []byte(url+"\n"), 0o600); err != nil {
logf("panel: setup: could not write token file %s: %v", m.tokenPath, err)
}
}
func (m *setupManager) setupURL(token string) string {
host := m.hostname
if host == "" {
host = "localhost"
}
return fmt.Sprintf("https://%s/setup/%s", host, token)
}
func (m *setupManager) clearTokenFile() {
if m.tokenPath == "" {
return
}
if err := os.Remove(m.tokenPath); err != nil && !os.IsNotExist(err) {
logf("panel: setup: could not remove token file %s: %v", m.tokenPath, err)
}
}