Trim comments to the non-obvious why
Test and deploy / test (push) Successful in 28s
Test and deploy / deploy (push) Successful in 31s

Drop narration, history and restated-code comments across the repo,
keep short ones for security boundaries, upstream quirks and ordering
constraints, and record the convention in CLAUDE.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-24 20:49:03 +00:00
co-authored by Claude Opus 5.5
parent effddd2794
commit 4530cb8dc4
222 changed files with 1173 additions and 5423 deletions
+19 -89
View File
@@ -20,18 +20,9 @@ import (
"adam-french.co.uk/backend/services"
)
// Command backend is the Go API for adam-french.co.uk.
//
// main is the single place everything is wired together: it reads every
// setting from the environment, builds the services, packs them into one
// handlers.Store, and registers the routes. There are three route groups —
// open, `protected` (valid access token) and `admin` (token with admin=true)
// — plus the GraphQL endpoint, which is authorised by the @admin / @signedIn
// directives in its schema instead of by middleware. See backend/README.md
// for the wider picture.
// Command backend is the site's Go API. GraphQL is guarded by schema
// directives, not middleware; see backend/README.md.
func main() {
// Logs go to both stdout (so `docker compose logs` works) and a file in a
// mounted volume (so they survive the container).
logsDir := "/backend/logs"
logFile, err := os.OpenFile(logsDir+"/go.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
@@ -44,16 +35,11 @@ func main() {
}
r := gin.New()
// Custom traffic formatter (services/traffic_log.go) instead of gin's
// default: quiets heartbeat subrequests, surfaces external visitors and
// server errors. Same writer pair as above.
r.Use(gin.LoggerWithFormatter(services.TrafficLogFormatter))
r.Use(gin.Recovery())
// Only the Docker network Caddy sits on may set X-Forwarded-For. Without
// this pin any client could spoof its IP and defeat the per-IP login rate
// limiter, which keys on ctx.ClientIP(). The CIDR must match the network
// defined in docker-compose.yml.
// Only the Docker network may set X-Forwarded-For, or clients could spoof
// their IP past the login rate limiter. Must match docker-compose.yml.
err = r.SetTrustedProxies([]string{"172.28.0.0/16"})
if err != nil {
panic(err)
@@ -69,36 +55,21 @@ func main() {
if err != nil {
log.Fatal(err)
}
// Dev only; the seeder creates an admin with a known password.
if os.Getenv("SEED_DB") == "true" {
services.SeedDatabase(db)
}
// DOMAIN does double duty: the WebSocket origin allow-list and the auth
// cookie domain.
// Used for both the WebSocket origin check and the cookie domain.
domainName := os.Getenv("DOMAIN")
// The chat hub is a package-level singleton rather than a value on the
// Store, so it is initialised rather than constructed.
services.InitWebSocket(db, domainName)
// SPOTIFY
// No SPOTIFY_AUTH_STATE: the OAuth `state` is now a one-shot nonce minted
// per authorisation request, so there is nothing to configure.
spotifyRedirectURL := os.Getenv("SPOTIFY_REDIRECT_URI")
spotifyClientID := os.Getenv("SPOTIFY_CLIENT_ID")
spotifyClientSecret := os.Getenv("SPOTIFY_CLIENT_SECRET")
spotifyConfig := services.SpotifyConfig{RedirectURL: spotifyRedirectURL, ClientID: spotifyClientID, ClientSecret: spotifyClientSecret}
spotifyAuth, spotifyClient := services.InitSpotifyAuth(&spotifyConfig)
// No Claude client here: the site's one Claude call, the rowing photo
// reader, is made by the Python service, which is the only container of
// the site's own that reads CLAUDE_API_KEY. The backend reaches it at
// pythonURL, below. (The job tracker, a separate container, makes its own.)
authSecret := os.Getenv("BACKEND_SECRET")
backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
// Long-lived by design: this is a personal site with a single admin, and
// there is no server-side revocation, so a leaked token stays valid for
// its whole lifetime.
accessTokenLifetime := 7 * 24 * time.Hour
refreshTokenLifetime := 365 * 24 * time.Hour
authConfig := services.AuthConfig{Secret: []byte(authSecret), Domain: domainName, RefreshTokenLifetime: refreshTokenLifetime, AccessTokenLifetime: accessTokenLifetime, Endpoint: backendEndpoint}
@@ -114,10 +85,7 @@ func main() {
steamAPIKey := os.Getenv("STEAM_API_KEY")
steamID := os.Getenv("STEAM_ID")
// PYTHON SERVICE
// Called directly over the Docker network, not through Caddy, for its
// /internal/ Claude route (services/python_call.go). The defaults
// mirror docker-compose.yml, where both variables are optional.
// Called over the Docker network, not through Caddy.
pythonHost := os.Getenv("PYTHON_HOST")
if pythonHost == "" {
pythonHost = "python"
@@ -128,11 +96,7 @@ func main() {
}
pythonURL := fmt.Sprintf("http://%s:%s", pythonHost, pythonPort)
// UPLOADS
// Public uploads go to the Garage bucket (and to the shared `uploads`
// volume when Garage refuses a write, or when S3_ENDPOINT is unset);
// private ones to the volume. See services/uploads.go. Region and bucket
// default to what garage/garage.toml and garage/bootstrap.sh set up.
// Defaults match garage/garage.toml and garage/bootstrap.sh.
s3Region := os.Getenv("S3_REGION")
if s3Region == "" {
s3Region = "garage"
@@ -144,24 +108,18 @@ func main() {
s3Config := services.S3Config{Endpoint: os.Getenv("S3_ENDPOINT"), Region: s3Region, Bucket: s3Bucket, AccessKeyID: os.Getenv("S3_ACCESS_KEY_ID"), SecretAccessKey: os.Getenv("S3_SECRET_ACCESS_KEY")}
uploads := services.NewUploads(s3Config, "/backend/uploads/", "/backend/uploads/private/")
// 5 login attempts per IP per minute, applied by both the REST handler
// and the GraphQL login mutation. Caddy rate-limits the login route too.
// Shared by REST and GraphQL login, on top of Caddy's limit.
loginLimiter := services.NewRateLimiter(5, time.Minute)
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL, Uploads: uploads}
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
// the Gin context, so the order in the admin group matters.
//
// Paths below have no /api prefix: Caddy strips it before proxying.
protected := r.Group("/", store.AuthMiddlewear)
admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware)
// Caddy strips /api before proxying.
protected := r.Group("/", store.AuthMiddleware)
admin := r.Group("/", store.AuthMiddleware, store.AdminMiddleware)
// ROWING
r.GET("/rowing", store.GetRowing)
admin.POST("/rowing", store.CreateRowing)
// AUTH
r.POST("/auth/login", store.Login)
r.POST("/auth/refresh", store.RefreshToken)
r.GET("/auth/check", store.CheckToken)
@@ -169,47 +127,29 @@ func main() {
r.GET("/auth/validate-admin", store.ValidateAdmin)
r.GET("/auth/validate/:permission", store.ValidatePermission)
// SPOTIFY
// The callback must be open — Spotify redirects a logged-out browser to
// it — and is protected by the state nonce instead. Starting the flow is
// admin-only, since that is what mints the nonce.
// The callback is open (Spotify redirects a logged-out browser) and is
// protected by the state nonce that only the admin-only start mints.
r.GET("/spotify/callback", store.CompleteSpotifyAuth)
admin.GET("/spotify/auth", store.StartSpotifyAuth)
r.GET("/spotify/listening", store.ListeningTo)
r.GET("/spotify/recent", store.RecentlyPlayed)
// r.POST("/spotify", store.SendSong)
// RADIO
admin.POST("/radio/upload", store.UploadRadioSong)
admin.GET("/radio/songs", store.ListRadioSongs)
admin.DELETE("/radio/songs/:filename", store.DeleteRadioSong)
admin.PATCH("/radio/songs/:filename/disable", store.DisableRadioSong)
admin.PATCH("/radio/songs/:filename/enable", store.EnableRadioSong)
// MESSAGES
// /ws is deliberately outside the protected group: chat is public, and
// the handler checks the cookies itself to decide admin privileges.
// Public: the handler reads the cookies itself for admin privileges.
r.GET("/ws", store.ConnectWebSocket)
protected.POST("/uploads", store.Upload)
admin.GET("/uploads", store.ListUploads)
// NOTES
admin.GET("/notes/*path", store.GetNoteFile)
// GRAPHQL
// GraphQL is assembled by hand rather than with handler.NewDefaultServer
// so the transports and extensions below are explicit.
//
// Note the whole API is one POST route with no middleware guard.
// Authorisation is declared in the schema instead: a field marked @admin
// or @signedIn is refused by the matching function in graph.Directives()
// before its resolver runs. A field with neither is PUBLIC, so a new
// mutation needs one — graph/directives_test.go fails until it has one or
// is added to the list of deliberately public fields there.
//
// Directives must stay wired here: gqlgen fails closed on a nil directive
// (the field errors with "directive admin is not implemented"), so
// dropping this line breaks every guarded field rather than opening it.
// One unguarded POST route: authorisation is the schema's @admin and
// @signedIn directives, so a field with neither is public. gqlgen fails
// closed if Directives is dropped.
gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{
Resolvers: &graph.Resolver{Store: &store},
Directives: graph.Directives(),
@@ -218,20 +158,13 @@ func main() {
gqlSrv.AddTransport(transport.Options{})
gqlSrv.AddTransport(transport.POST{})
gqlSrv.AddTransport(transport.MultipartForm{})
// Caches parsed query documents so repeated queries skip parsing.
gqlSrv.SetQueryCache(lru.New[*ast.QueryDocument](1000))
// Rejects queries above a computed complexity, the standard defence
// against a deeply nested query being used to exhaust the server.
gqlSrv.Use(extension.FixedComplexityLimit(200))
// Introspection and the playground are both off unless DEV_MODE *and*
// their own flag are set, so production does not publish its schema.
// Production never publishes its schema.
devMode := os.Getenv("DEV_MODE") == "true"
if devMode && os.Getenv("GQL_INTROSPECTION") == "true" {
gqlSrv.Use(extension.Introspection{})
}
// AuthContextMiddleware copies the Gin context and any verified claims
// into the request context, which is what resolvers read. The closure is
// needed because gqlgen speaks net/http, not gin.
r.POST("/graphql", graph.AuthContextMiddleware(auth, db), func(c *gin.Context) {
gqlSrv.ServeHTTP(c.Writer, c.Request)
})
@@ -241,15 +174,12 @@ func main() {
})
}
// HELLO WORLD
r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{"message": "Hello World"})
})
port := os.Getenv("BACKEND_PORT")
// Blocks until the server stops. Any return is a failure — a port clash,
// most often — so it must exit non-zero, or Docker sees a clean shutdown
// and reports the container as having succeeded.
// Exit non-zero so Docker doesn't report a port clash as success.
if err := r.Run(fmt.Sprintf(":%s", port)); err != nil {
log.Fatalf("http server stopped: %v", err)
}