Files
pansy/cmd/pansy/main.go
T
steveandClaude Opus 4.8 0e41ccd95a
Build image / build-and-push (push) Successful in 8s
Gadfly review (reusable) / review (pull_request) Successful in 7m7s
Adversarial Review (Gadfly) / review (pull_request) Successful in 7m7s
Add local auth: users, sessions, register/login/logout/me (#4)
Implements pansy's local (email + password) authentication and the
session layer that OIDC (#5) will also reuse.

- store: users.go (create/get-by-id/get-by-email/count) and sessions.go
  (create/get/touch/delete/delete-expired), scanning the existing 0001
  schema.
- service: the business-logic seam. auth.go (Register/Login/session
  lifecycle/Providers) + password.go (argon2id, 64 MiB/1/4, PHC-encoded,
  constant-time verify) + service.go (Service, clock injection, token
  hashing). First user is admin; closed registration still allows the
  bootstrap user; unknown-email and wrong-password are indistinguishable
  (same error, same argon2 work via a dummy hash).
- api: POST /auth/register|login|logout, GET /auth/me|providers, plus a
  requireAuth middleware that resolves the HttpOnly session cookie
  (SameSite=Lax, Secure under https) to the actor. Handlers stay thin.
- main: wires the service and a periodic expired-session sweep; sessions
  are also dropped lazily on access. Sliding 30-day expiry.
- tests: service (register/login/expiry/renewal/cleanup, password) and
  api (cookie flow, middleware, validation, providers).

Verified end-to-end via curl: register -> me -> restart -> session
persists -> logout -> 401.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
2026-07-18 16:38:03 -04:00

119 lines
3.3 KiB
Go

// Command pansy is the single static binary: it loads configuration, opens and
// migrates the SQLite database, builds the HTTP server (JSON API + embedded SPA),
// and serves until interrupted.
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"gitea.stevedudenhoeffer.com/steve/pansy/internal/api"
"gitea.stevedudenhoeffer.com/steve/pansy/internal/config"
"gitea.stevedudenhoeffer.com/steve/pansy/internal/service"
"gitea.stevedudenhoeffer.com/steve/pansy/internal/store"
"gitea.stevedudenhoeffer.com/steve/pansy/internal/webdist"
)
// sessionSweepInterval is how often expired sessions are purged in the
// background (they are also dropped lazily on access).
const sessionSweepInterval = 6 * time.Hour
func main() {
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo})))
if err := run(); err != nil {
slog.Error("pansy: fatal", "error", err)
os.Exit(1)
}
}
func run() error {
cfg := config.Load()
db, err := store.Open(cfg.DBPath)
if err != nil {
return fmt.Errorf("open database: %w", err)
}
defer db.Close()
// Migrations run against a short-lived context so a hung DB can't block boot
// forever; the schema is tiny so this is generous.
migCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := db.Migrate(migCtx); err != nil {
return fmt.Errorf("migrate database: %w", err)
}
slog.Info("pansy: database ready", "path", cfg.DBPath)
svc := service.New(db, cfg)
r := api.New(cfg, svc)
api.RegisterSPA(r, webdist.Dist())
srv := &http.Server{
Addr: fmt.Sprintf(":%d", cfg.Port),
Handler: r,
ReadTimeout: 15 * time.Second,
ReadHeaderTimeout: 5 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
}
// Serve in the background; the main goroutine waits for a signal, then drains.
serveErr := make(chan error, 1)
go func() {
slog.Info("pansy: listening", "addr", srv.Addr)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
serveErr <- err
}
}()
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
go sweepSessions(ctx, svc)
select {
case err := <-serveErr:
return fmt.Errorf("http server: %w", err)
case <-ctx.Done():
slog.Info("pansy: shutting down")
stop() // restore default signal handling so a second Ctrl-C force-quits
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
return fmt.Errorf("graceful shutdown: %w", err)
}
}
return nil
}
// sweepSessions periodically purges expired sessions until ctx is cancelled. It
// runs one sweep immediately so a long-lived process doesn't wait a full
// interval after startup. Failures are logged, never fatal.
func sweepSessions(ctx context.Context, svc *service.Service) {
ticker := time.NewTicker(sessionSweepInterval)
defer ticker.Stop()
for {
if n, err := svc.CleanupExpiredSessions(ctx); err != nil {
if ctx.Err() == nil {
slog.Warn("pansy: session sweep failed", "error", err)
}
} else if n > 0 {
slog.Info("pansy: purged expired sessions", "count", n)
}
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}