- feat(config): TOML config with env overrides, strict parsing and validation - feat(storage): SQLite (modernc) and PostgreSQL (pgx) backends through bun, embedded per-driver SQL migrations with a transactional runner - feat(schema): catalog tables (artists, albums, tracks, audio_files with per-root paths), users and listening events with idempotency keys - feat(auth): Argon2id password hashing, HS256 JWT tokens, first-user-only registration and login - feat(api): gin REST API under /api/v1 (health, register, login, listens) with a consistent error envelope, body limit and request logging - feat(sondad): zap logger, graceful shutdown, composition root in main - chore: example config, .gitignore for secrets, DB files, IDE and agent files
171 lines
4.5 KiB
Go
171 lines
4.5 KiB
Go
// Package config loads and validates the sondad configuration.
|
|
//
|
|
// Precedence: built-in defaults, then the TOML file, then environment variables.
|
|
package config
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/pelletier/go-toml/v2"
|
|
)
|
|
|
|
const minJWTSecretLen = 32
|
|
|
|
// Config is the full sondad configuration.
|
|
type Config struct {
|
|
Server Server `toml:"server"`
|
|
Library Library `toml:"library"`
|
|
Database Database `toml:"database"`
|
|
Log Log `toml:"log"`
|
|
Auth Auth `toml:"auth"`
|
|
Providers Providers `toml:"providers"`
|
|
}
|
|
|
|
// Server holds HTTP listener settings.
|
|
type Server struct {
|
|
Listen string `toml:"listen"`
|
|
}
|
|
|
|
// Library holds the music directories. They are treated as read-only.
|
|
type Library struct {
|
|
Roots []string `toml:"roots"`
|
|
}
|
|
|
|
// Database selects and configures the storage backend.
|
|
//
|
|
// Driver is "sqlite" (uses Path) or "postgres" (uses DSN).
|
|
type Database struct {
|
|
Driver string `toml:"driver"`
|
|
Path string `toml:"path"`
|
|
DSN string `toml:"dsn"`
|
|
}
|
|
|
|
// Log holds logging settings. Env is "dev" or "production".
|
|
type Log struct {
|
|
Env string `toml:"env"`
|
|
}
|
|
|
|
// Auth holds token settings. JWTSecret must be long and random,
|
|
// for example: openssl rand -hex 32.
|
|
type Auth struct {
|
|
JWTSecret string `toml:"jwt_secret"`
|
|
TokenTTLHours int `toml:"token_ttl_hours"`
|
|
}
|
|
|
|
// TokenTTL returns the access token lifetime.
|
|
func (a Auth) TokenTTL() time.Duration {
|
|
return time.Duration(a.TokenTTLHours) * time.Hour
|
|
}
|
|
|
|
// Providers holds external provider settings.
|
|
type Providers struct {
|
|
LastFM LastFM `toml:"lastfm"`
|
|
}
|
|
|
|
// LastFM holds the Last.fm API settings.
|
|
type LastFM struct {
|
|
APIKey string `toml:"api_key"`
|
|
}
|
|
|
|
// Default returns the configuration used when nothing else is set.
|
|
func Default() Config {
|
|
return Config{
|
|
Server: Server{Listen: "127.0.0.1:8080"},
|
|
Database: Database{Driver: "sqlite", Path: "sonda.db"},
|
|
Log: Log{Env: "production"},
|
|
Auth: Auth{TokenTTLHours: 168}, // one week
|
|
}
|
|
}
|
|
|
|
// Load builds a Config from defaults, the TOML file at path, and environment
|
|
// variables. An empty path skips the file. Unknown keys in the file are errors.
|
|
func Load(path string) (Config, error) {
|
|
cfg := Default()
|
|
|
|
if path != "" {
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return Config{}, fmt.Errorf("read config: %w", err)
|
|
}
|
|
dec := toml.NewDecoder(bytes.NewReader(data))
|
|
dec.DisallowUnknownFields()
|
|
if err := dec.Decode(&cfg); err != nil {
|
|
return Config{}, fmt.Errorf("parse config %s: %w", path, err)
|
|
}
|
|
}
|
|
|
|
applyEnv(&cfg)
|
|
return cfg, nil
|
|
}
|
|
|
|
func applyEnv(cfg *Config) {
|
|
if v := os.Getenv("SONDA_ENV"); v != "" {
|
|
cfg.Log.Env = v
|
|
}
|
|
if v := os.Getenv("SONDA_LISTEN"); v != "" {
|
|
cfg.Server.Listen = v
|
|
}
|
|
if v := os.Getenv("SONDA_DB_DRIVER"); v != "" {
|
|
cfg.Database.Driver = v
|
|
}
|
|
if v := os.Getenv("SONDA_DB_PATH"); v != "" {
|
|
cfg.Database.Path = v
|
|
}
|
|
if v := os.Getenv("SONDA_DB_DSN"); v != "" {
|
|
cfg.Database.DSN = v
|
|
}
|
|
if v := os.Getenv("SONDA_JWT_SECRET"); v != "" {
|
|
cfg.Auth.JWTSecret = v
|
|
}
|
|
if v := os.Getenv("SONDA_LASTFM_API_KEY"); v != "" {
|
|
cfg.Providers.LastFM.APIKey = v
|
|
}
|
|
}
|
|
|
|
// Validate checks that the configuration is usable.
|
|
func (c Config) Validate() error {
|
|
var errs []error
|
|
|
|
if c.Server.Listen == "" {
|
|
errs = append(errs, errors.New("server.listen is required"))
|
|
}
|
|
switch c.Database.Driver {
|
|
case "sqlite":
|
|
if c.Database.Path == "" {
|
|
errs = append(errs, errors.New("database.path is required for the sqlite driver"))
|
|
}
|
|
case "postgres":
|
|
if c.Database.DSN == "" {
|
|
errs = append(errs, errors.New("database.dsn is required for the postgres driver"))
|
|
}
|
|
default:
|
|
errs = append(errs, fmt.Errorf("database.driver must be \"sqlite\" or \"postgres\", got %q", c.Database.Driver))
|
|
}
|
|
if c.Log.Env != "dev" && c.Log.Env != "production" {
|
|
errs = append(errs, fmt.Errorf("log.env must be \"dev\" or \"production\", got %q", c.Log.Env))
|
|
}
|
|
if len(c.Auth.JWTSecret) < minJWTSecretLen {
|
|
errs = append(errs, fmt.Errorf("auth.jwt_secret must be at least %d characters (try: openssl rand -hex 32)", minJWTSecretLen))
|
|
}
|
|
if c.Auth.TokenTTLHours <= 0 {
|
|
errs = append(errs, errors.New("auth.token_ttl_hours must be greater than 0"))
|
|
}
|
|
if len(c.Library.Roots) == 0 {
|
|
errs = append(errs, errors.New("library.roots needs at least one directory"))
|
|
}
|
|
for _, root := range c.Library.Roots {
|
|
info, err := os.Stat(root)
|
|
switch {
|
|
case err != nil:
|
|
errs = append(errs, fmt.Errorf("library.roots: %w", err))
|
|
case !info.IsDir():
|
|
errs = append(errs, fmt.Errorf("library.roots: %s is not a directory", root))
|
|
}
|
|
}
|
|
|
|
return errors.Join(errs...)
|
|
}
|