Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .claude/rules/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@
- Panic recovery prevents a single request from crashing the process.
- Structured logs must never contain secrets or raw personal/financial data.
- Auth: short-lived HS256 JWT access tokens (`JWT_SIGNING_SECRET`, at least 32
characters) + two roles (operator, admin); `RequireRole` exists but is not
yet mounted on any route.
characters) + two roles (operator, admin); admin-only routes (e.g.
`PATCH /rules/{id}`) are enforced server-side with `auth.RequireRole`
next to the route they protect.

## Reporting

Expand Down
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ CORS_ALLOWED_ORIGINS=http://localhost:5173,http://localhost:8081
JWT_SIGNING_SECRET=dev_only_example_secret_change_me_32+chars
JWT_ACCESS_TOKEN_TTL=15m

# How often the realtime relay polls the transactional outbox.
OUTBOX_POLL_INTERVAL=500ms

# Demo account passwords for `go run ./cmd/api seed-users` (operator@example.com,
# admin@example.com). SAFE example dev values only.
DEMO_OPERATOR_PASSWORD=operator_dev_password
Expand Down
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ product, and must never be represented as one.
- **Real-time:** PostgreSQL transactional **outbox** + an in-process WebSocket
hub. Do **not** add Kafka, Redis, NATS, or RabbitMQ.
- **Auth:** short-lived (15m default) HS256 JWT access tokens via `POST
/login`; two roles (operator, admin). `RequireRole` exists but is not yet
mounted on any route.
/login`; two roles (operator, admin). Admin-only routes (rule changes) are
enforced server-side with `auth.RequireRole`.

## Contract-first

Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ near-real-time monitoring and alerting platform:
migrations, structured JSON logging, validated configuration, graceful shutdown.
- **Frontend** — React + TypeScript + Vite, Tailwind + shadcn-compatible
components, TanStack Query, Recharts.
- **Real-time (planned)** — PostgreSQL transactional outbox + an in-process
WebSocket hub. No Kafka/Redis/NATS/RabbitMQ.
- **Real-time** — PostgreSQL transactional outbox relayed to an in-process
WebSocket hub at `/ws`. No Kafka/Redis/NATS/RabbitMQ.
- **Contracts** — OpenAPI for REST, AsyncAPI for events, as the source of truth.

This repository is the **bootstrap**: structure, skeletons, contracts, docs,
local environment, and CI. Business features (transactions, alerts, rule
evaluation, live streaming) arrive in later issues.
evaluation) arrive in later issues.

## Repository layout

Expand Down
27 changes: 25 additions & 2 deletions apps/api/cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ import (
"github.com/vianbas/finwatch/apps/api/internal/config"
"github.com/vianbas/finwatch/apps/api/internal/platform/httpserver"
"github.com/vianbas/finwatch/apps/api/internal/platform/postgres"
"github.com/vianbas/finwatch/apps/api/internal/rules"
"github.com/vianbas/finwatch/apps/api/internal/realtime"
realtimehttp "github.com/vianbas/finwatch/apps/api/internal/realtime/httpapi"
realtimestore "github.com/vianbas/finwatch/apps/api/internal/realtime/store"
rulehttp "github.com/vianbas/finwatch/apps/api/internal/rules/httpapi"
rulestore "github.com/vianbas/finwatch/apps/api/internal/rules/store"
"github.com/vianbas/finwatch/apps/api/internal/transactions"
txhttp "github.com/vianbas/finwatch/apps/api/internal/transactions/httpapi"
Expand Down Expand Up @@ -73,7 +76,7 @@ func main() {
type appServices struct {
transactions *transactions.Service
alerts *alerts.Service
rules rules.Repository
rules *rulestore.Store
}

// buildServices wires the feature modules over a connection pool, registering
Expand Down Expand Up @@ -254,16 +257,24 @@ func run() error {
authSvc := auth.NewService(authstore.New(pool), issuer)
authHandler := authhttp.NewHandler(authSvc, logger)

// Realtime: the relay moves committed outbox events into the hub, which
// fans them out to /ws clients.
hub := realtime.NewHub(logger)
relay := realtime.NewRelay(realtimestore.New(pool), hub, cfg.OutboxPollInterval, logger)

router := httpserver.NewRouter(httpserver.RouterDeps{
Logger: logger,
Health: httpserver.NewHealthHandler(pool),
PublicModules: []httpserver.RouteRegistrar{
httpserver.RegistrarFunc(authHandler.RegisterPublicRoutes),
// /ws authenticates its own handshake (token in a subprotocol).
realtimehttp.NewHandler(hub, verifier, cfg.CORSAllowedOrigins, logger),
},
Modules: []httpserver.RouteRegistrar{
httpserver.RegistrarFunc(authHandler.RegisterProtectedRoutes),
txhttp.NewHandler(svcs.transactions, logger),
alerthttp.NewHandler(svcs.alerts, logger),
rulehttp.NewHandler(svcs.rules, logger),
},
RequireAuth: auth.RequireAuth(verifier),
CORSAllowedOrigins: cfg.CORSAllowedOrigins,
Expand All @@ -282,6 +293,12 @@ func run() error {
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer stop()

relayDone := make(chan struct{})
go func() {
defer close(relayDone)
relay.Run(ctx)
}()

serverErr := make(chan error, 1)
go func() {
logger.Info("http server listening", slog.String("addr", srv.Addr))
Expand All @@ -304,6 +321,12 @@ func run() error {
slog.Duration("timeout", cfg.ShutdownTimeout))
}

// Stop relaying, then tell WebSocket clients to reconnect elsewhere:
// Shutdown does not track upgraded (hijacked) connections.
stop()
<-relayDone
hub.Close()

shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
Expand Down
1 change: 1 addition & 0 deletions apps/api/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/vianbas/finwatch/apps/api
go 1.26.0

require (
github.com/coder/websocket v1.8.15
github.com/go-chi/chi/v5 v5.3.0
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/jackc/pgx/v5 v5.10.0
Expand Down
2 changes: 2 additions & 0 deletions apps/api/go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand Down
9 changes: 9 additions & 0 deletions apps/api/internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ type Config struct {
JWTSigningSecret string
// JWTAccessTokenTTL bounds how long an issued access token remains valid.
JWTAccessTokenTTL time.Duration

// OutboxPollInterval is how often the realtime relay polls for unpublished
// outbox events.
OutboxPollInterval time.Duration
}

// Addr returns the host:port the HTTP server should bind to.
Expand Down Expand Up @@ -102,6 +106,10 @@ func Load(getenv func(string) string) (*Config, error) {
return nil, err
}

if cfg.OutboxPollInterval, err = durationEnv(getenv, "OUTBOX_POLL_INTERVAL", 500*time.Millisecond); err != nil {
return nil, err
}

if err := cfg.Validate(); err != nil {
return nil, err
}
Expand Down Expand Up @@ -141,6 +149,7 @@ func (c Config) Validate() error {
"HTTP_IDLE_TIMEOUT": c.IdleTimeout,
"HTTP_SHUTDOWN_TIMEOUT": c.ShutdownTimeout,
"JWT_ACCESS_TOKEN_TTL": c.JWTAccessTokenTTL,
"OUTBOX_POLL_INTERVAL": c.OutboxPollInterval,
} {
if d <= 0 {
return fmt.Errorf("config: %s must be a positive duration", name)
Expand Down
22 changes: 22 additions & 0 deletions apps/api/internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,26 @@ func TestLoad_JWTDefaultsAndOverrides(t *testing.T) {
}
}

func TestLoad_OutboxPollIntervalDefaultAndOverride(t *testing.T) {
cfg, err := Load(envFunc(validEnv()))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if cfg.OutboxPollInterval != 500*time.Millisecond {
t.Errorf("OutboxPollInterval = %v, want 500ms", cfg.OutboxPollInterval)
}

env := validEnv()
env["OUTBOX_POLL_INTERVAL"] = "2s"
cfg, err = Load(envFunc(env))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if cfg.OutboxPollInterval != 2*time.Second {
t.Errorf("OutboxPollInterval = %v, want 2s", cfg.OutboxPollInterval)
}
}

func TestLoad_ValidationErrors(t *testing.T) {
tests := []struct {
name string
Expand All @@ -95,6 +115,8 @@ func TestLoad_ValidationErrors(t *testing.T) {
{"short jwt signing secret", func(m map[string]string) { m["JWT_SIGNING_SECRET"] = "too-short" }},
{"non-duration jwt ttl", func(m map[string]string) { m["JWT_ACCESS_TOKEN_TTL"] = "soon" }},
{"zero jwt ttl", func(m map[string]string) { m["JWT_ACCESS_TOKEN_TTL"] = "0s" }},
{"non-duration outbox poll interval", func(m map[string]string) { m["OUTBOX_POLL_INTERVAL"] = "often" }},
{"negative outbox poll interval", func(m map[string]string) { m["OUTBOX_POLL_INTERVAL"] = "-1s" }},
{"published example secret in staging", func(m map[string]string) {
m["APP_ENV"] = "staging"
m["JWT_SIGNING_SECRET"] = "dev_only_example_secret_change_me_32+chars"
Expand Down
4 changes: 2 additions & 2 deletions apps/api/internal/platform/httpserver/cors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ func TestCORS_PreflightFromAllowedOrigin(t *testing.T) {
if got := h.Get("Access-Control-Allow-Origin"); got != "http://localhost:5173" {
t.Errorf("Access-Control-Allow-Origin = %q, want %q", got, "http://localhost:5173")
}
if got := h.Get("Access-Control-Allow-Methods"); got != "GET, POST" {
t.Errorf("Access-Control-Allow-Methods = %q, want %q", got, "GET, POST")
if got := h.Get("Access-Control-Allow-Methods"); got != "GET, POST, PATCH" {
t.Errorf("Access-Control-Allow-Methods = %q, want %q", got, "GET, POST, PATCH")
}
if got := h.Get("Access-Control-Allow-Headers"); got != "Authorization, Content-Type" {
t.Errorf("Access-Control-Allow-Headers = %q, want %q", got, "Authorization, Content-Type")
Expand Down
9 changes: 8 additions & 1 deletion apps/api/internal/platform/httpserver/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,13 @@ func (s *statusRecorder) WriteHeader(code int) {
s.ResponseWriter.WriteHeader(code)
}

// Unwrap exposes the underlying writer to http.ResponseController, so
// handlers behind AccessLog can still hijack (WebSocket upgrades) and set
// connection deadlines.
func (s *statusRecorder) Unwrap() http.ResponseWriter {
return s.ResponseWriter
}

// CORS returns a middleware that answers cross-origin requests from an
// explicit allow-list of origins, using exact string comparison (no
// wildcards, no suffix matching). It exists to let the web app (served from a
Expand Down Expand Up @@ -125,7 +132,7 @@ func CORS(allowedOrigins []string) func(http.Handler) http.Handler {
if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
h := w.Header()
h.Set("Access-Control-Allow-Origin", origin)
h.Set("Access-Control-Allow-Methods", "GET, POST")
h.Set("Access-Control-Allow-Methods", "GET, POST, PATCH")
h.Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
h.Set("Access-Control-Max-Age", "600")
w.WriteHeader(http.StatusNoContent)
Expand Down
65 changes: 65 additions & 0 deletions apps/api/internal/platform/postgres/db/outbox.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

65 changes: 65 additions & 0 deletions apps/api/internal/platform/postgres/db/rules.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading