feat: unified config (#533)

* chore: add yaml config ref

* feat: add initial implementation of a traefik like cli

* refactor: remove dependency on traefik

* chore: update example env

* refactor: update build

* chore: remove unused code

* fix: fix translations not loading

* feat: add experimental config file support

* chore: mod tidy

* fix: review comments

* refactor: move tinyauth to separate package

* chore: add quotes to all env variables

* chore: resolve go mod and sum conflicts

* chore: go mod tidy

* fix: review comments
This commit is contained in:
Stavros
2025-12-22 22:13:40 +02:00
committed by GitHub
parent f3d2e14535
commit 03ed18343e
46 changed files with 1074 additions and 1259 deletions

98
cmd/tinyauth/create.go Normal file
View File

@@ -0,0 +1,98 @@
package main
import (
"errors"
"fmt"
"os"
"strings"
"time"
"github.com/charmbracelet/huh"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/traefik/paerser/cli"
"golang.org/x/crypto/bcrypt"
)
type CreateUserConfig struct {
Interactive bool `description:"Create a user interactively."`
Docker bool `description:"Format output for docker."`
Username string `description:"Username."`
Password string `description:"Password."`
}
func NewCreateUserConfig() *CreateUserConfig {
return &CreateUserConfig{
Interactive: false,
Docker: false,
Username: "",
Password: "",
}
}
func createUserCmd() *cli.Command {
tCfg := NewCreateUserConfig()
loaders := []cli.ResourceLoader{
&cli.FlagLoader{},
}
return &cli.Command{
Name: "create",
Description: "Create a user",
Configuration: tCfg,
Resources: loaders,
Run: func(_ []string) error {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}).With().Caller().Logger().Level(zerolog.InfoLevel)
if tCfg.Interactive {
form := huh.NewForm(
huh.NewGroup(
huh.NewInput().Title("Username").Value(&tCfg.Username).Validate((func(s string) error {
if s == "" {
return errors.New("username cannot be empty")
}
return nil
})),
huh.NewInput().Title("Password").Value(&tCfg.Password).Validate((func(s string) error {
if s == "" {
return errors.New("password cannot be empty")
}
return nil
})),
huh.NewSelect[bool]().Title("Format the output for Docker?").Options(huh.NewOption("Yes", true), huh.NewOption("No", false)).Value(&tCfg.Docker),
),
)
var baseTheme *huh.Theme = huh.ThemeBase()
err := form.WithTheme(baseTheme).Run()
if err != nil {
return fmt.Errorf("failed to run interactive prompt: %w", err)
}
}
if tCfg.Username == "" || tCfg.Password == "" {
return errors.New("username and password cannot be empty")
}
log.Info().Str("username", tCfg.Username).Msg("Creating user")
passwd, err := bcrypt.GenerateFromPassword([]byte(tCfg.Password), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("failed to hash password: %w", err)
}
// If docker format is enabled, escape the dollar sign
passwdStr := string(passwd)
if tCfg.Docker {
passwdStr = strings.ReplaceAll(passwdStr, "$", "$$")
}
log.Info().Str("user", fmt.Sprintf("%s:%s", tCfg.Username, passwdStr)).Msg("User created")
return nil
},
}
}

119
cmd/tinyauth/generate.go Normal file
View File

@@ -0,0 +1,119 @@
package main
import (
"errors"
"fmt"
"os"
"strings"
"time"
"tinyauth/internal/utils"
"github.com/charmbracelet/huh"
"github.com/mdp/qrterminal/v3"
"github.com/pquerna/otp/totp"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/traefik/paerser/cli"
)
type GenerateTotpConfig struct {
Interactive bool `description:"Generate a TOTP secret interactively."`
User string `description:"Your current user (username:hash)."`
}
func NewGenerateTotpConfig() *GenerateTotpConfig {
return &GenerateTotpConfig{
Interactive: false,
User: "",
}
}
func generateTotpCmd() *cli.Command {
tCfg := NewGenerateTotpConfig()
loaders := []cli.ResourceLoader{
&cli.FlagLoader{},
}
return &cli.Command{
Name: "generate",
Description: "Generate a TOTP secret",
Configuration: tCfg,
Resources: loaders,
Run: func(_ []string) error {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}).With().Caller().Logger().Level(zerolog.InfoLevel)
if tCfg.Interactive {
form := huh.NewForm(
huh.NewGroup(
huh.NewInput().Title("Current user (username:hash)").Value(&tCfg.User).Validate((func(s string) error {
if s == "" {
return errors.New("user cannot be empty")
}
return nil
})),
),
)
var baseTheme *huh.Theme = huh.ThemeBase()
err := form.WithTheme(baseTheme).Run()
if err != nil {
return fmt.Errorf("failed to run interactive prompt: %w", err)
}
}
user, err := utils.ParseUser(tCfg.User)
if err != nil {
return fmt.Errorf("failed to parse user: %w", err)
}
docker := false
if strings.Contains(tCfg.User, "$$") {
docker = true
}
if user.TotpSecret != "" {
return fmt.Errorf("user already has a TOTP secret")
}
key, err := totp.Generate(totp.GenerateOpts{
Issuer: "Tinyauth",
AccountName: user.Username,
})
if err != nil {
return fmt.Errorf("failed to generate TOTP secret: %w", err)
}
secret := key.Secret()
log.Info().Str("secret", secret).Msg("Generated TOTP secret")
log.Info().Msg("Generated QR code")
config := qrterminal.Config{
Level: qrterminal.L,
Writer: os.Stdout,
BlackChar: qrterminal.BLACK,
WhiteChar: qrterminal.WHITE,
QuietZone: 2,
}
qrterminal.GenerateWithConfig(key.URL(), config)
user.TotpSecret = secret
// If using docker escape re-escape it
if docker {
user.Password = strings.ReplaceAll(user.Password, "$", "$$")
}
log.Info().Str("user", fmt.Sprintf("%s:%s:%s", user.Username, user.Password, user.TotpSecret)).Msg("Add the totp secret to your authenticator app then use the verify command to ensure everything is working correctly.")
return nil
},
}
}

View File

@@ -0,0 +1,85 @@
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/traefik/paerser/cli"
)
type healthzResponse struct {
Status string `json:"status"`
Message string `json:"message"`
}
func healthcheckCmd() *cli.Command {
return &cli.Command{
Name: "healthcheck",
Description: "Perform a health check",
Configuration: nil,
Resources: nil,
AllowArg: true,
Run: func(args []string) error {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}).With().Caller().Logger().Level(zerolog.InfoLevel)
appUrl := os.Getenv("TINYAUTH_APPURL")
if len(args) > 0 {
appUrl = args[0]
}
if appUrl == "" {
return errors.New("TINYAUTH_APPURL is not set and no argument was provided")
}
log.Info().Str("app_url", appUrl).Msg("Performing health check")
client := http.Client{
Timeout: 30 * time.Second,
}
req, err := http.NewRequest("GET", appUrl+"/api/healthz", nil)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to perform request: %w", err)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("service is not healthy, got: %s", resp.Status)
}
defer resp.Body.Close()
var healthResp healthzResponse
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response: %w", err)
}
err = json.Unmarshal(body, &healthResp)
if err != nil {
return fmt.Errorf("failed to decode response: %w", err)
}
log.Info().Interface("response", healthResp).Msg("Tinyauth is healthy")
return nil
},
}
}

124
cmd/tinyauth/tinyauth.go Normal file
View File

@@ -0,0 +1,124 @@
package main
import (
"fmt"
"os"
"strings"
"time"
"tinyauth/internal/bootstrap"
"tinyauth/internal/config"
"tinyauth/internal/utils/loaders"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/traefik/paerser/cli"
)
func NewTinyauthCmdConfiguration() *config.Config {
return &config.Config{
LogLevel: "info",
ResourcesDir: "./resources",
DatabasePath: "./tinyauth.db",
Server: config.ServerConfig{
Port: 3000,
Address: "0.0.0.0",
},
Auth: config.AuthConfig{
SessionExpiry: 3600,
LoginTimeout: 300,
LoginMaxRetries: 3,
},
UI: config.UIConfig{
Title: "Tinyauth",
ForgotPasswordMessage: "You can change your password by changing the configuration.",
BackgroundImage: "/background.jpg",
},
Experimental: config.ExperimentalConfig{
ConfigFile: "",
},
}
}
func main() {
tConfig := NewTinyauthCmdConfiguration()
loaders := []cli.ResourceLoader{
&loaders.FileLoader{},
&loaders.FlagLoader{},
&loaders.EnvLoader{},
}
cmdTinyauth := &cli.Command{
Name: "tinyauth",
Description: "The simplest way to protect your apps with a login screen.",
Configuration: tConfig,
Resources: loaders,
Run: func(_ []string) error {
return runCmd(*tConfig)
},
}
err := cmdTinyauth.AddCommand(versionCmd())
if err != nil {
log.Fatal().Err(err).Msg("Failed to add version command")
}
err = cmdTinyauth.AddCommand(verifyUserCmd())
if err != nil {
log.Fatal().Err(err).Msg("Failed to add verify command")
}
err = cmdTinyauth.AddCommand(healthcheckCmd())
if err != nil {
log.Fatal().Err(err).Msg("Failed to add healthcheck command")
}
err = cmdTinyauth.AddCommand(generateTotpCmd())
if err != nil {
log.Fatal().Err(err).Msg("Failed to add generate command")
}
err = cmdTinyauth.AddCommand(createUserCmd())
if err != nil {
log.Fatal().Err(err).Msg("Failed to add create command")
}
err = cli.Execute(cmdTinyauth)
if err != nil {
log.Fatal().Err(err).Msg("Failed to execute command")
}
}
func runCmd(cfg config.Config) error {
logLevel, err := zerolog.ParseLevel(strings.ToLower(cfg.LogLevel))
if err != nil {
log.Error().Err(err).Msg("Invalid or missing log level, defaulting to info")
} else {
zerolog.SetGlobalLevel(logLevel)
}
log.Logger = log.With().Caller().Logger()
if !cfg.LogJSON {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339})
}
log.Info().Str("version", config.Version).Msg("Starting tinyauth")
app := bootstrap.NewBootstrapApp(cfg)
err = app.Setup()
if err != nil {
return fmt.Errorf("failed to bootstrap app: %w", err)
}
return nil
}

120
cmd/tinyauth/verify.go Normal file
View File

@@ -0,0 +1,120 @@
package main
import (
"errors"
"fmt"
"os"
"time"
"tinyauth/internal/utils"
"github.com/charmbracelet/huh"
"github.com/pquerna/otp/totp"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/traefik/paerser/cli"
"golang.org/x/crypto/bcrypt"
)
type VerifyUserConfig struct {
Interactive bool `description:"Validate a user interactively."`
Username string `description:"Username."`
Password string `description:"Password."`
Totp string `description:"TOTP code."`
User string `description:"Hash (username:hash:totp)."`
}
func NewVerifyUserConfig() *VerifyUserConfig {
return &VerifyUserConfig{
Interactive: false,
Username: "",
Password: "",
Totp: "",
User: "",
}
}
func verifyUserCmd() *cli.Command {
tCfg := NewVerifyUserConfig()
loaders := []cli.ResourceLoader{
&cli.FlagLoader{},
}
return &cli.Command{
Name: "verify",
Description: "Verify a user is set up correctly.",
Configuration: tCfg,
Resources: loaders,
Run: func(_ []string) error {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}).With().Caller().Logger().Level(zerolog.InfoLevel)
if tCfg.Interactive {
form := huh.NewForm(
huh.NewGroup(
huh.NewInput().Title("User (username:hash:totp)").Value(&tCfg.User).Validate((func(s string) error {
if s == "" {
return errors.New("user cannot be empty")
}
return nil
})),
huh.NewInput().Title("Username").Value(&tCfg.Username).Validate((func(s string) error {
if s == "" {
return errors.New("username cannot be empty")
}
return nil
})),
huh.NewInput().Title("Password").Value(&tCfg.Password).Validate((func(s string) error {
if s == "" {
return errors.New("password cannot be empty")
}
return nil
})),
huh.NewInput().Title("TOTP Code (optional)").Value(&tCfg.Totp),
),
)
var baseTheme *huh.Theme = huh.ThemeBase()
err := form.WithTheme(baseTheme).Run()
if err != nil {
return fmt.Errorf("failed to run interactive prompt: %w", err)
}
}
user, err := utils.ParseUser(tCfg.User)
if err != nil {
return fmt.Errorf("failed to parse user: %w", err)
}
if user.Username != tCfg.Username {
return fmt.Errorf("username is incorrect")
}
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(tCfg.Password))
if err != nil {
return fmt.Errorf("password is incorrect: %w", err)
}
if user.TotpSecret == "" {
if tCfg.Totp != "" {
log.Warn().Msg("User does not have TOTP secret")
}
log.Info().Msg("User verified")
return nil
}
ok := totp.Validate(tCfg.Totp, user.TotpSecret)
if !ok {
return fmt.Errorf("TOTP code incorrect")
}
log.Info().Msg("User verified")
return nil
},
}
}

23
cmd/tinyauth/version.go Normal file
View File

@@ -0,0 +1,23 @@
package main
import (
"fmt"
"tinyauth/internal/config"
"github.com/traefik/paerser/cli"
)
func versionCmd() *cli.Command {
return &cli.Command{
Name: "version",
Description: "Print the version number of Tinyauth.",
Configuration: nil,
Resources: nil,
Run: func(_ []string) error {
fmt.Printf("Version: %s\n", config.Version)
fmt.Printf("Commit Hash: %s\n", config.CommitHash)
fmt.Printf("Build Timestamp: %s\n", config.BuildTimestamp)
return nil
},
}
}