Files
archie/internal/app/archie/config.go
T
sam 073959b4f9 feat(memory): scope chat notes and preserve deletions on restore (#2069)
Keep personal notes private by default and require review before publishing shared notes. Restore backups and replay forgotten notes in one transaction, and retain the installed release when an unattended rollback could bring back forgotten notes.
2026-11-21 13:20:31 +11:00

189 lines
6.0 KiB
Go

package archie
import (
"errors"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"filippo.io/age"
"github.com/BurntSushi/toml"
"github.com/samcharles93/archie-core/internal/platform/deletions"
)
// Config is the bootstrap configuration: only what the binary needs before it
// can reach its database. Everything else is a setting in the control plane.
type Config struct {
Listen string `toml:"listen"`
Database DatabaseConfig `toml:"database"`
// AdminTokenSHA256 is the hex SHA-256 of the bootstrap admin token that
// guards /api/ until identities exist. The token itself is never stored.
AdminTokenSHA256 string `toml:"admin_token_sha256"`
// AgeIdentity ("AGE-SECRET-KEY-1...") seals and opens the credentials
// Archie keeps. Losing it loses them, unless a backup recipient's key
// survives.
AgeIdentity string `toml:"age_identity"`
// AgeBackupRecipients ("age1...") can also open every sealed credential.
AgeBackupRecipients []string `toml:"age_backup_recipients"`
// StateDir is where the binary keeps state outside the database, including
// the record of deletions a restore has to apply again. It defaults to
// ${XDG_DATA_HOME:-~/.local/share}/archie, where the other archie binaries
// keep their state unless an instance name is set. A leading ~ is the home
// directory, and a relative path is refused: the restore that reads this
// directory runs as another process.
StateDir string `toml:"state_dir"`
}
// DatabaseConfig holds the two connection URLs. The owner runs migrations at
// boot and nothing else; the runtime URL never holds DDL rights.
type DatabaseConfig struct {
URL string `toml:"url"`
OwnerURL string `toml:"owner_url"`
}
var adminHash = regexp.MustCompile(`^[0-9a-f]{64}$`)
var adminLine = regexp.MustCompile(`(?m)^\s*admin_token_sha256\s*=.*$`)
// WriteAdminHash replaces the admin token hash in the config at path, keeping
// every other line. The hash is the only value written: the old token and the
// old hash are never read back or logged.
func WriteAdminHash(path, hash string) error {
if !adminHash.MatchString(hash) {
return errors.New("an admin token hash is a hex SHA-256")
}
raw, err := os.ReadFile(path) //nolint:gosec // the path is the config the binary was started with.
if err != nil {
return fmt.Errorf("read config %s: %w", path, err)
}
line := `admin_token_sha256 = "` + hash + `"`
next := string(raw)
if adminLine.MatchString(next) {
next = adminLine.ReplaceAllString(next, line)
} else {
next = strings.TrimRight(next, "\n") + "\n" + line + "\n"
}
if !strings.HasSuffix(next, "\n") {
next += "\n"
}
return writeConfig(path, []byte(next))
}
// writeConfig replaces path atomically, so a crash leaves either the old file
// or the new one.
func writeConfig(path string, data []byte) error {
dir := filepath.Dir(path)
file, err := os.CreateTemp(dir, ".config-*")
if err != nil {
return fmt.Errorf("write config %s: %w", path, err)
}
name := file.Name()
defer func() { _ = os.Remove(name) }()
if err := file.Chmod(0o600); err != nil {
_ = file.Close()
return fmt.Errorf("write config %s: %w", path, err)
}
if _, err := file.Write(data); err != nil {
_ = file.Close()
return fmt.Errorf("write config %s: %w", path, err)
}
if err := file.Sync(); err != nil {
_ = file.Close()
return fmt.Errorf("write config %s: %w", path, err)
}
if err := file.Close(); err != nil {
return fmt.Errorf("write config %s: %w", path, err)
}
if err := os.Rename(name, path); err != nil {
return fmt.Errorf("write config %s: %w", path, err)
}
return nil
}
// DatabaseHost is the host a database URL names, without credentials or the
// database name. It is what the dashboard shows.
func DatabaseHost(raw string) string {
u, err := url.Parse(raw)
if err != nil {
return ""
}
return u.Host
}
// DefaultConfigPath is ${XDG_CONFIG_HOME:-~/.config}/archie/config.toml.
func DefaultConfigPath() string {
dir, err := os.UserConfigDir()
if err != nil {
return filepath.Join("archie", "config.toml")
}
return filepath.Join(dir, "archie", "config.toml")
}
// DefaultStateDir is ${XDG_DATA_HOME:-~/.local/share}/archie, or the instance's
// directory when ARCHIE_INSTANCE names one, resolved the way every archie binary
// resolves it.
func DefaultStateDir() string {
dir, err := deletions.Dir("")
if err != nil {
return filepath.Join("archie", "state")
}
return dir
}
// NewAgeIdentity writes a new age identity to w, for a config's age_identity.
func NewAgeIdentity(w io.Writer) error {
id, err := age.GenerateX25519Identity()
if err != nil {
return fmt.Errorf("generate age identity: %w", err)
}
_, err = fmt.Fprintln(w, id.String())
return err
}
// LoadConfig reads and validates the bootstrap config at path.
func LoadConfig(path string) (Config, error) {
cfg := Config{Listen: "127.0.0.1:8080", StateDir: DefaultStateDir()}
if _, err := toml.DecodeFile(path, &cfg); err != nil {
return Config{}, fmt.Errorf("read config %s: %w", path, err)
}
dir, err := deletions.Dir(cfg.StateDir)
if err != nil {
return Config{}, fmt.Errorf("config %s: %w", path, err)
}
cfg.StateDir = dir
if err := cfg.validate(); err != nil {
return Config{}, fmt.Errorf("config %s: %w", path, err)
}
return cfg, nil
}
func (c Config) validate() error {
var errs []error
if c.Listen == "" {
errs = append(errs, errors.New("listen is empty"))
}
if c.Database.URL == "" {
errs = append(errs, errors.New("database.url is required"))
}
// The owner URL has no fallback to the runtime URL: a runtime connection
// that can run DDL defeats the role split.
if c.Database.OwnerURL == "" {
errs = append(errs, errors.New("database.owner_url is required"))
}
if c.AgeIdentity == "" {
errs = append(errs, errors.New("age_identity is required"))
}
if !adminHash.MatchString(c.AdminTokenSHA256) {
errs = append(errs, errors.New("admin_token_sha256 must be a hex SHA-256"))
}
if c.Database.URL != "" && c.Database.URL == c.Database.OwnerURL {
errs = append(errs, errors.New("database.url and database.owner_url must name different roles"))
}
return errors.Join(errs...)
}