Document codebase: comments, per-area READMEs, deployment guide
Readability pass across all four areas of the stack. Comments explain why rather than what, concentrated at the points where behaviour is non-obvious: concurrency, caching, auth, scraping and nginx templating. Backend: doc comments on every exported declaration across handlers, services, models and resolvers. Resolver commentary lives inside function bodies so gqlgen does not strip it on regeneration; schema files use # comments rather than description blocks so introspection output is unchanged. Extracted the duplicated auth-cookie blocks into helpers. Frontend: header comments on every component, store and view, including STATUS: notes marking which of the parallel/legacy views are still live. Documented the non-reactive animation-state pattern, the homeData hub and the WebSocket stale-socket guard. Removed a few dead imports and named the reconnect-backoff and poll-interval constants. Python: module and function docstrings covering the Travelodge scraping contract, the deadline threading, the two-executor concurrency and the NDJSON streaming protocol. Infra: header blocks on every compose file, nginx template, Dockerfile and entrypoint, covering the config selection, envsubst allow-lists, rate-limit semantics and volume persistence. Hoisted the duplicated envsubst variable list in nginx/entrypoint.sh. New: backend/README.md, python/README.md, DEPLOYMENT.md, .env.example, backend/graph/doc.go. Refreshed vue/README.md. Corrected CLAUDE.md, which stated a 24h access token where main.go sets 7 days. No behaviour change. go build/vet, vite build, py_compile and docker compose config all pass. Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
@@ -1,3 +1,32 @@
|
||||
# =============================================================================
|
||||
# Go backend image — multi-stage: build with the full toolchain, ship a slim
|
||||
# runtime containing one static binary.
|
||||
#
|
||||
# STAGE 1 (golang:1.26)
|
||||
# go.mod/go.sum are copied and downloaded BEFORE the rest of the source, so
|
||||
# the dependency layer is cached and only re-runs when the module files
|
||||
# change — a meaningful saving when building on a Raspberry Pi.
|
||||
#
|
||||
# The `--mount=type=cache` lines are BuildKit cache mounts: the module cache
|
||||
# and the Go build cache persist BETWEEN builds on the host without being
|
||||
# baked into any image layer. This is the single biggest reason a rebuild on
|
||||
# the Pi takes minutes rather than much longer. They require BuildKit, which
|
||||
# is the default in modern `docker compose build`.
|
||||
#
|
||||
# CGO_ENABLED=0 produces a fully static binary with no libc dependency, which
|
||||
# is what lets a golang-built binary run on a different, slimmer base image.
|
||||
#
|
||||
# STAGE 2 (debian:bookworm-slim)
|
||||
# Carries only the binary plus ca-certificates — needed because the backend
|
||||
# makes outbound HTTPS calls (Spotify, Claude, Steam, the Gitea feed) and
|
||||
# would fail certificate verification without a trust store.
|
||||
#
|
||||
# EXPOSE 8080 is documentation only; the port is never published to the host.
|
||||
# nginx reaches it over app-network as BACKEND_HOST:BACKEND_PORT.
|
||||
#
|
||||
# Base images are multi-arch, so this builds unchanged on arm64 (the Pi) and
|
||||
# amd64 (a dev laptop) with no platform pin.
|
||||
# =============================================================================
|
||||
FROM golang:1.26 AS builder
|
||||
|
||||
WORKDIR /backend
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
# Backend
|
||||
|
||||
The Go API for adam-french.co.uk. It is one process behind nginx, serving a
|
||||
GraphQL endpoint, a handful of REST endpoints, and the chat WebSocket, backed
|
||||
by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea, Anthropic).
|
||||
|
||||
Nginx strips the `/api` prefix before proxying, so a browser request to
|
||||
`/api/graphql` arrives here as `/graphql`. Every path below is as this service
|
||||
sees it.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
main.go wiring: env -> services -> Store -> routes
|
||||
models/models.go GORM entities, which are ALSO the GraphQL object types
|
||||
handlers/ REST endpoints + the shared Store dependency container
|
||||
store.go Store: DB, service handles, and the third-party caches
|
||||
handle_*.go one file per domain
|
||||
services/ stateful collaborators (DB, auth, chat hub, API clients)
|
||||
graph/ GraphQL layer
|
||||
schema/*.graphql source of truth for the schema
|
||||
*.resolvers.go resolver implementations, one per schema file
|
||||
*_helpers.go hand-written mapping helpers (never regenerated)
|
||||
context.go reading identity out of the resolver context
|
||||
middleware.go putting it in
|
||||
doc.go package overview — read this before touching resolvers
|
||||
generated.go GENERATED, do not edit
|
||||
model/models_gen.go GENERATED, do not edit
|
||||
```
|
||||
|
||||
## Request lifecycle
|
||||
|
||||
1. Nginx terminates TLS, applies its own rate limits, strips `/api`, and
|
||||
proxies to this service.
|
||||
2. Gin routes the request. `SetTrustedProxies` pins the Docker network CIDR so
|
||||
that `ClientIP()` — which the login rate limiter keys on — cannot be
|
||||
spoofed via `X-Forwarded-For`.
|
||||
3. **REST**: the route's middleware chain runs. `AuthMiddlewear` requires a
|
||||
valid access token and stashes the claims in the Gin context;
|
||||
`AdminMiddleware` then requires `admin: true` in those claims. A handler
|
||||
reached through the `admin` group can assume both.
|
||||
4. **GraphQL**: there is no guarding middleware. `AuthContextMiddleware` only
|
||||
*annotates* the request context with the Gin context and, if a valid access
|
||||
token is present, the JWT claims — and then lets everything through. Each
|
||||
resolver authorises itself with `IsAdminFromCtx` / `UserIDFromCtx`.
|
||||
**A resolver that forgets to check is public.**
|
||||
5. Handlers and resolvers both reach the database and the caches through the
|
||||
single `handlers.Store` built in `main`.
|
||||
|
||||
## Auth
|
||||
|
||||
- `POST /auth/login` (or the `login` mutation) checks a bcrypt hash and sets
|
||||
two cookies, both `HttpOnly` + `Secure` + `SameSite=Lax`:
|
||||
- `access_token` (7 days) carries `id`, `username`, `admin`, so ordinary
|
||||
requests authorise without a database hit;
|
||||
- `refresh_token` (365 days) carries only `id`.
|
||||
- `POST /auth/refresh` (or the `refreshToken` mutation) exchanges the refresh
|
||||
token for a new pair, re-reading the user — and therefore the admin flag —
|
||||
from the database.
|
||||
- `GET /auth/validate-admin` answers with a bare status code (200 / 403 / 401)
|
||||
and will transparently refresh, so returning admins are recognised without a
|
||||
visible re-login.
|
||||
- Tokens are stateless. **Logout only clears the browser's cookies**; nothing
|
||||
is revoked server-side, and a token that has already been issued stays valid
|
||||
until it expires. The same is true of demoting an admin: it takes effect on
|
||||
their next refresh, not immediately.
|
||||
|
||||
The two implementations (REST in `handlers/handle_auth.go`, GraphQL in
|
||||
`graph/auth.resolvers.go`) are parallel by design, since the front end uses
|
||||
both. They share `services.Auth` and the rate limiter, but each has its own
|
||||
cookie-writing helper — change one and you must change the other.
|
||||
|
||||
## GraphQL vs REST
|
||||
|
||||
GraphQL is the default and covers essentially all the site's data. REST exists
|
||||
for the things GraphQL cannot do:
|
||||
|
||||
| REST endpoint | why it is not GraphQL |
|
||||
| --- | --- |
|
||||
| `/auth/*` | cookie handling and the status-code-only admin probe |
|
||||
| `/spotify/callback`, `/email/callback` | OAuth providers redirect a *browser* here |
|
||||
| `/messages/upload`, `/radio/upload`, `/rowing` (POST) | multipart file uploads |
|
||||
| `/notes/*path` | streams a file download, not JSON |
|
||||
| `/ws` | WebSocket upgrade |
|
||||
| `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working |
|
||||
|
||||
## Services
|
||||
|
||||
Everything is constructed in `main` from environment variables and handed to
|
||||
`handlers.Store`. Nothing here fails start-up: a missing Spotify token, an
|
||||
unconfigured mailbox or an absent Steam key all just leave that feature
|
||||
dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
|
||||
|
||||
- **database.go** — Postgres via GORM. There are no migration files:
|
||||
`AutoMigrate` is the whole schema story, so it adds tables/columns but never
|
||||
drops or renames, and a new model must be listed there to get a table.
|
||||
- **auth.go** — HS256 JWT minting and verification.
|
||||
- **ratelimit.go** — in-memory per-IP sliding window (5 logins/minute).
|
||||
Process-local and never evicts keys.
|
||||
- **websocket.go** — the chat hub. A package-level singleton: one connection
|
||||
set, one mutex, one DB handle. Public, with admin connections additionally
|
||||
able to see/send private messages and delete.
|
||||
- **spotify.go**, **steam.go**, **gitea.go** — third-party reads. Results are
|
||||
cached on `Store` with TTLs of 1 min (Spotify recent, Gitea) and 5 min
|
||||
(Steam).
|
||||
- **email_sync.go** / **email_imap.go** — the job-application pipeline: fetch
|
||||
recent mail (Microsoft Graph *or* a hand-rolled IMAP client), keyword-filter
|
||||
it, ask Claude to extract structured data, create or advance a
|
||||
`JobApplication`. Runs on a timer and can be triggered by an admin.
|
||||
- **claude.go** — the shared Anthropic client, used by the email pipeline and
|
||||
by the rowing photo reader.
|
||||
- **notes.go** — path-traversal-safe file lookup for the notes directory.
|
||||
- **seed.go** — dev-only test data. Creates an admin with the password
|
||||
`password`, so it must never run in production (`SEED_DB=true` is set only
|
||||
in `docker-compose.dev.yml`).
|
||||
|
||||
## Regenerating gqlgen
|
||||
|
||||
The `.graphql` files are the source of truth.
|
||||
|
||||
```
|
||||
cd backend && go run github.com/99designs/gqlgen generate
|
||||
```
|
||||
|
||||
This rewrites `graph/generated.go` and `graph/model/models_gen.go` and adds
|
||||
stubs for new fields to the matching `*.resolvers.go`. Existing resolver bodies
|
||||
are preserved, but hand-written code in a regenerated file can be relocated to
|
||||
the end of it — which is why shared helpers live in `*_helpers.go` instead.
|
||||
|
||||
`gqlgen.yml` maps most GraphQL object types directly onto the GORM structs in
|
||||
`models/`, so `graph/model/` holds only input and payload types. Adding a type
|
||||
to the schema without a corresponding entry in `gqlgen.yml` gets you a fresh
|
||||
generated struct rather than the model you expected.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **Soft delete everywhere.** Every model except `ProcessedEmail` has a
|
||||
`gorm.DeletedAt`, so `Delete` sets a timestamp and later queries filter the
|
||||
row out. Rows are never actually removed, and a `uniqueIndex` still collides
|
||||
with deleted rows — a soft-deleted username cannot be reused.
|
||||
- **`Preload` is not lazy.** `Post.Author` is nil unless the query preloads it;
|
||||
there is no error to tell you why the field came back null.
|
||||
- **IDs.** Models use `uint`, GraphQL uses `Int`. That is why nearly every type
|
||||
has a hand-written `ID` resolver doing `int(obj.ID)`.
|
||||
- **`Message.AuthorID` is not a user id.** It is a per-process counter handed
|
||||
out by the chat hub on connect, meaningless across restarts.
|
||||
- **The chat table is capped.** Every insert soft-deletes all but the newest
|
||||
50 messages.
|
||||
- **Store's caches are unsynchronised** and shared by all requests. The races
|
||||
are benign (at worst a duplicate upstream fetch), but do not add a field
|
||||
there that would be unsafe to tear.
|
||||
- **Claude output is parsed as JSON** after stripping a possible markdown code
|
||||
fence, in both `handle_rowing.go` and `email_sync.go`.
|
||||
- **The email pipeline never retries.** A failed email is recorded with action
|
||||
`"error"` so the next sync skips it.
|
||||
- **Authenticating email after start-up does not start the scheduler**, which
|
||||
only checks readiness once — restart, or trigger syncs by hand.
|
||||
- **Introspection and the playground are off** unless `DEV_MODE=true` *and*
|
||||
`GQL_INTROSPECTION` / `GQL_PLAYGROUND` are set.
|
||||
- **No graceful shutdown.** `r.Run` blocks forever and its error is ignored;
|
||||
the container is simply killed.
|
||||
|
||||
## Environment
|
||||
|
||||
| var | purpose |
|
||||
| --- | --- |
|
||||
| `POSTGRES_USER` / `_PASSWORD` / `_DB` / `_HOST` / `_PORT` | database connection |
|
||||
| `BACKEND_PORT` | listen port |
|
||||
| `BACKEND_SECRET` | JWT signing secret |
|
||||
| `BACKEND_ENDPOINT` | this service's public base URL |
|
||||
| `DOMAIN` | auth cookie domain and WebSocket origin allow-list |
|
||||
| `DEV_MODE` | release vs debug Gin; gates the two GraphQL dev flags |
|
||||
| `SEED_DB` | seed dev test data (never in production) |
|
||||
| `GQL_INTROSPECTION` / `GQL_PLAYGROUND` | dev-only GraphQL extras |
|
||||
| `SPOTIFY_CLIENT_ID` / `_SECRET` / `_REDIRECT_URI` / `SPOTIFY_AUTH_STATE` | Spotify OAuth |
|
||||
| `CLAUDE_API_KEY` | Anthropic API |
|
||||
| `GITEA_HOST` / `GITEA_PORT` | Gitea activity feed |
|
||||
| `STEAM_API_KEY` / `STEAM_ID` | Steam presence |
|
||||
| `EMAIL_SYNC_ENABLED` / `EMAIL_BACKEND` / `EMAIL_SYNC_INTERVAL` | email pipeline (`graph` or `imap`) |
|
||||
| `MSGRAPH_CLIENT_ID` / `_SECRET` / `_TENANT_ID` / `_REDIRECT_URI` | Microsoft Graph backend |
|
||||
| `IMAP_HOST` / `_PORT` / `_EMAIL` / `_PASSWORD` | IMAP backend |
|
||||
|
||||
Paths baked into the code, all inside mounted volumes so they survive a
|
||||
container restart: `/backend/logs`, `/backend/notes`, `/backend/uploads`,
|
||||
`/backend/fallback_music`, `/backend/token/` (Spotify and Microsoft Graph
|
||||
OAuth tokens).
|
||||
@@ -20,6 +20,7 @@ func (r *activityResolver) ID(ctx context.Context, obj *models.Activity) (int, e
|
||||
|
||||
// CreateActivity is the resolver for the createActivity field.
|
||||
func (r *mutationResolver) CreateActivity(ctx context.Context, input model.CreateActivityInput) (*models.Activity, error) {
|
||||
// No middleware guards GraphQL, so each mutation checks for itself.
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
@@ -38,6 +39,9 @@ func (r *queryResolver) Activities(ctx context.Context) ([]*models.Activity, err
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&activities).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &activities[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Activity, len(activities))
|
||||
for i := range activities {
|
||||
result[i] = &activities[i]
|
||||
|
||||
@@ -17,6 +17,12 @@ import (
|
||||
|
||||
// Login is the resolver for the login field.
|
||||
func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*model.AuthPayload, error) {
|
||||
// The Gin context is needed for two things GraphQL cannot express: the
|
||||
// client IP for rate limiting, and setting response cookies. It is
|
||||
// smuggled in by AuthContextMiddleware.
|
||||
//
|
||||
// This mutation mirrors handlers.Store.Login; the two share the limiter
|
||||
// and services.Auth, so the same 5/min budget covers both entry points.
|
||||
gc := GinContextFromCtx(ctx)
|
||||
if gc == nil {
|
||||
return nil, fmt.Errorf("could not get gin context")
|
||||
@@ -26,6 +32,8 @@ func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*
|
||||
return nil, fmt.Errorf("too many login attempts, please try again later")
|
||||
}
|
||||
|
||||
// Identical message for unknown user and wrong password, so the API
|
||||
// cannot be used to enumerate usernames.
|
||||
var user models.User
|
||||
if err := r.Store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
|
||||
return nil, fmt.Errorf("invalid credentials")
|
||||
@@ -40,24 +48,10 @@ func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*
|
||||
return nil, fmt.Errorf("failed to generate tokens")
|
||||
}
|
||||
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(r.Store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
gc.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(r.Store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
setAuthCookies(gc, r.Store.Auth.Config, tokens)
|
||||
|
||||
// The payload carries no token: the tokens only ever travel as HttpOnly
|
||||
// cookies, so client JavaScript never sees them.
|
||||
return &model.AuthPayload{User: &user}, nil
|
||||
}
|
||||
|
||||
@@ -68,6 +62,9 @@ func (r *mutationResolver) Logout(ctx context.Context) (bool, error) {
|
||||
return false, fmt.Errorf("could not get gin context")
|
||||
}
|
||||
|
||||
// Max-age -1 tells the browser to drop the cookies. Nothing is
|
||||
// invalidated server-side, so a token captured beforehand still works
|
||||
// until it expires.
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie("access_token", "", -1, "/", r.Store.Auth.Config.Domain, true, true)
|
||||
gc.SetCookie("refresh_token", "", -1, "/", r.Store.Auth.Config.Domain, true, true)
|
||||
@@ -97,6 +94,9 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
|
||||
return nil, fmt.Errorf("invalid token claims")
|
||||
}
|
||||
|
||||
// Setting the primary key and calling First with no condition makes GORM
|
||||
// look the row up by that key. Admin status is re-read from the database
|
||||
// here, which is what lets a revoked admin flag take effect on refresh.
|
||||
var user models.User
|
||||
user.ID = uint(userIDF)
|
||||
if err := r.Store.DB.First(&user).Error; err != nil {
|
||||
@@ -108,23 +108,7 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
|
||||
return nil, fmt.Errorf("failed to generate tokens")
|
||||
}
|
||||
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(r.Store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
gc.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(r.Store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
setAuthCookies(gc, r.Store.Auth.Config, tokens)
|
||||
|
||||
return &model.AuthPayload{User: &user}, nil
|
||||
}
|
||||
@@ -136,6 +120,8 @@ func (r *queryResolver) Me(ctx context.Context) (*models.User, error) {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
// Read fresh from the database rather than returned from the token
|
||||
// claims, so `me` reflects the current username and admin flag.
|
||||
var user models.User
|
||||
user.ID = userID
|
||||
if err := r.Store.DB.First(&user).Error; err != nil {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package graph
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// setAuthCookies writes the access/refresh cookie pair on a GraphQL response.
|
||||
//
|
||||
// This mirrors handlers.Store.setAuthCookies — the two cannot be shared
|
||||
// because importing graph from handlers would be a cycle, so any change to
|
||||
// cookie attributes has to be made in both places or login via REST and login
|
||||
// via GraphQL will disagree.
|
||||
//
|
||||
// gin's SetCookie takes Secure and HttpOnly as its two trailing booleans, both
|
||||
// true here: the cookies never travel over plain HTTP and are invisible to
|
||||
// JavaScript. SameSite=Lax survives a top-level navigation back from an OAuth
|
||||
// provider while still blocking cross-site POSTs. Each max-age mirrors the
|
||||
// lifetime baked into the token itself.
|
||||
//
|
||||
// It lives in its own file rather than in auth.resolvers.go because gqlgen may
|
||||
// relocate hand-written code in the files it regenerates.
|
||||
func setAuthCookies(gc *gin.Context, config *services.AuthConfig, tokens *services.Tokens) {
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
config.Domain,
|
||||
true, true,
|
||||
)
|
||||
gc.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
config.Domain,
|
||||
true, true,
|
||||
)
|
||||
}
|
||||
@@ -35,6 +35,9 @@ func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models.
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Loaded first so the deleted record can be returned to the client, and
|
||||
// so a missing id is a clean "not found" rather than a silent no-op.
|
||||
// Delete is a soft delete: deleted_at is set and the row stays.
|
||||
var bookmark models.Bookmark
|
||||
if err := r.Store.DB.First(&bookmark, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -51,6 +54,9 @@ func (r *queryResolver) Bookmarks(ctx context.Context) ([]*models.Bookmark, erro
|
||||
if err := r.Store.DB.Order("category ASC, created_at ASC").Find(&bookmarks).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &bookmarks[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Bookmark, len(bookmarks))
|
||||
for i := range bookmarks {
|
||||
result[i] = &bookmarks[i]
|
||||
|
||||
@@ -7,6 +7,17 @@ import (
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// This file is the bridge between Gin's request handling and gqlgen's
|
||||
// resolvers. gqlgen resolvers receive only a context.Context, so
|
||||
// AuthContextMiddleware (middleware.go) smuggles the verified JWT claims and
|
||||
// the *gin.Context itself into that context, and these accessors read them
|
||||
// back out.
|
||||
|
||||
// contextKey is a private named type so that these keys can never collide
|
||||
// with a key set by another package — the reason the standard library warns
|
||||
// against using bare strings as context keys. Note the string value
|
||||
// "userClaims" happens to match the key handlers.AuthMiddlewear uses in the
|
||||
// *Gin* context, but the two are unrelated and do not see each other.
|
||||
type contextKey string
|
||||
|
||||
const (
|
||||
@@ -14,6 +25,9 @@ const (
|
||||
ginContextKey contextKey = "ginContext"
|
||||
)
|
||||
|
||||
// UserClaimsFromCtx returns the verified JWT claims, or nil when the request
|
||||
// is anonymous. nil means "not authenticated": a missing or invalid token is
|
||||
// not an error here, because many queries are public.
|
||||
func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
||||
claims, ok := ctx.Value(userClaimsKey).(*jwt.MapClaims)
|
||||
if !ok {
|
||||
@@ -22,6 +36,8 @@ func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
||||
return claims
|
||||
}
|
||||
|
||||
// UserIDFromCtx returns the authenticated user's id. The claim arrives as a
|
||||
// float64 because claims are decoded by encoding/json, hence the conversion.
|
||||
func UserIDFromCtx(ctx context.Context) (uint, bool) {
|
||||
claims := UserClaimsFromCtx(ctx)
|
||||
if claims == nil {
|
||||
@@ -34,6 +50,11 @@ func UserIDFromCtx(ctx context.Context) (uint, bool) {
|
||||
return uint(idF), true
|
||||
}
|
||||
|
||||
// IsAdminFromCtx reports whether the request carries an admin token. This is
|
||||
// the authorisation check for nearly every mutation — there is no middleware
|
||||
// in front of the GraphQL endpoint, so a resolver that forgets to call this
|
||||
// is public. Admin comes from the token, not the database, so a revoked admin
|
||||
// flag only bites once the access token expires.
|
||||
func IsAdminFromCtx(ctx context.Context) bool {
|
||||
claims := UserClaimsFromCtx(ctx)
|
||||
if claims == nil {
|
||||
@@ -43,6 +64,10 @@ func IsAdminFromCtx(ctx context.Context) bool {
|
||||
return ok && admin
|
||||
}
|
||||
|
||||
// GinContextFromCtx returns the underlying *gin.Context, which resolvers need
|
||||
// for things that live outside GraphQL's model: setting auth cookies and
|
||||
// reading the client IP. Returns nil if the middleware was not installed,
|
||||
// which the auth resolvers surface as an error rather than panicking.
|
||||
func GinContextFromCtx(ctx context.Context) *gin.Context {
|
||||
gc, ok := ctx.Value(ginContextKey).(*gin.Context)
|
||||
if !ok {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// Package graph is the GraphQL layer: the single POST /graphql endpoint that
|
||||
// serves most of the site's data.
|
||||
//
|
||||
// How the pieces fit:
|
||||
//
|
||||
// - graph/schema/*.graphql is the source of truth. Running
|
||||
// `go run github.com/99designs/gqlgen generate` regenerates generated.go
|
||||
// and model/models_gen.go, and adds stubs for any new field to the
|
||||
// matching *.resolvers.go. Never edit those two generated files.
|
||||
// - gqlgen.yml maps most GraphQL object types straight onto the GORM
|
||||
// structs in backend/models, so model/ holds only input and payload
|
||||
// types. That is also why almost every type has a hand-written ID
|
||||
// resolver: model IDs are uint, GraphQL's Int is a Go int.
|
||||
// - Resolvers reach the database and the third-party caches through
|
||||
// Resolver.Store, the same handlers.Store the REST endpoints use.
|
||||
// - context.go and middleware.go carry the caller's identity from Gin into
|
||||
// the plain context.Context a resolver receives.
|
||||
//
|
||||
// Authorisation, which is the thing most likely to catch out a newcomer:
|
||||
// there is NO middleware guarding this endpoint. AuthContextMiddleware only
|
||||
// annotates the context and lets everything through, so each resolver checks
|
||||
// for itself with IsAdminFromCtx or UserIDFromCtx. A resolver that omits that
|
||||
// check is fully public. The rule of thumb in this schema is that queries are
|
||||
// public and mutations are admin-only, with these exceptions: the job
|
||||
// application and job reference queries are admin-only (they are private
|
||||
// data), the places mutations need only a signed-in user, and the messages
|
||||
// query hides private messages from non-admins rather than refusing.
|
||||
//
|
||||
// The files ending in _helpers.go are hand-written and are not touched by
|
||||
// gqlgen; the *.resolvers.go files are partly generated, so anything added to
|
||||
// them by hand may be moved to the end of the file on the next generate.
|
||||
package graph
|
||||
@@ -38,6 +38,9 @@ func (r *queryResolver) Favorites(ctx context.Context) ([]*models.Favorite, erro
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&favorites).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &favorites[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Favorite, len(favorites))
|
||||
for i := range favorites {
|
||||
result[i] = &favorites[i]
|
||||
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
|
||||
// GiteaFeed is the resolver for the giteaFeed field.
|
||||
func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, error) {
|
||||
// One-minute cache on the Store, shared by every visitor, so a busy home
|
||||
// page does not hammer the Gitea container.
|
||||
if r.Store.GiteaFeedFresh() {
|
||||
return mapGiteaFeed(r.Store.GiteaFeed), nil
|
||||
}
|
||||
@@ -23,6 +25,10 @@ func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, er
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// FetchLatestFeed returns (nil, nil) for an empty feed; mapGiteaFeed
|
||||
// would dereference it, so return null to the client instead. The cache
|
||||
// is deliberately not written in that case, so an empty feed is retried
|
||||
// on the next request.
|
||||
if feed == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,10 @@ import (
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// mapGiteaFeed flattens a Gitea feed entry into the GraphQL shape, pulling the
|
||||
// commit message out of the doubly-encoded Content field as it goes. It
|
||||
// dereferences feed, so callers must rule out the (nil, nil) that
|
||||
// FetchLatestFeed returns for an empty feed.
|
||||
func mapGiteaFeed(feed *services.GiteaFeedResponse) *model.GiteaFeedItem {
|
||||
return &model.GiteaFeedItem{
|
||||
AvatarURL: feed.ActUser.AvatarURL,
|
||||
|
||||
@@ -81,6 +81,8 @@ func (r *queryResolver) JobAppReferences(ctx context.Context) ([]*models.JobAppR
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var refs []*models.JobAppReference
|
||||
// created_at is the final tie-break so entries sharing a sort_order (the
|
||||
// default 0) keep a stable, insertion-ordered sequence.
|
||||
if err := r.Store.DB.Order("category ASC, sort_order ASC, created_at ASC").Find(&refs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -43,6 +43,10 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Partial update: every input field is a pointer so that "not supplied"
|
||||
// is distinguishable from "set to empty". A nil field is left untouched;
|
||||
// note this also means a nullable column can never be cleared back to
|
||||
// null through this mutation.
|
||||
var app models.JobApplication
|
||||
if err := r.Store.DB.First(&app, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -79,6 +83,8 @@ func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bo
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return false, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Soft delete straight by id, without loading first — so deleting an id
|
||||
// that does not exist still returns true.
|
||||
if err := r.Store.DB.Delete(&models.JobApplication{}, id).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -87,9 +93,12 @@ func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bo
|
||||
|
||||
// JobApplications is the resolver for the jobApplications field.
|
||||
func (r *queryResolver) JobApplications(ctx context.Context) ([]*models.JobApplication, error) {
|
||||
// Admin-only even though it is a query: job applications are private.
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Find can populate a slice of pointers directly, avoiding the
|
||||
// copy-to-pointers loop the other list resolvers need.
|
||||
var apps []*models.JobApplication
|
||||
if err := r.Store.DB.Order("created_at desc").Find(&apps).Error; err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -17,12 +17,21 @@ func (r *messageResolver) ID(ctx context.Context, obj *models.Message) (int, err
|
||||
}
|
||||
|
||||
// AuthorID is the resolver for the authorId field.
|
||||
// AuthorID is the resolver for the authorId field. The value is the chat
|
||||
// hub's per-connection counter, not a User id — see models.Message.
|
||||
func (r *messageResolver) AuthorID(ctx context.Context, obj *models.Message) (int, error) {
|
||||
return int(obj.AuthorID), nil
|
||||
}
|
||||
|
||||
// Messages is the resolver for the messages field.
|
||||
func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error) {
|
||||
// Non-admins get the public subset rather than an error, so the chat
|
||||
// history loads for everyone. The same filter is applied to the history
|
||||
// replayed over the WebSocket (services.HandleWebSocket) — change one and
|
||||
// the other must change too.
|
||||
//
|
||||
// Note the ordering differs between the two: newest first here, oldest
|
||||
// first over the socket.
|
||||
var messages []models.Message
|
||||
query := r.Store.DB.Order("created_at DESC")
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
@@ -31,6 +40,9 @@ func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error)
|
||||
if err := query.Find(&messages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &messages[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Message, len(messages))
|
||||
for i := range messages {
|
||||
result[i] = &messages[i]
|
||||
|
||||
@@ -7,6 +7,18 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// AuthContextMiddleware prepares the request context for the GraphQL handler.
|
||||
//
|
||||
// It always attaches the *gin.Context, and attaches the JWT claims only when a
|
||||
// valid access token is present. Crucially it never rejects a request: a
|
||||
// missing, expired or forged token simply leaves the context anonymous, which
|
||||
// is what lets public queries work and pushes every authorisation decision
|
||||
// into the individual resolvers (see IsAdminFromCtx). Both cookie and verify
|
||||
// errors are swallowed for exactly that reason.
|
||||
//
|
||||
// Unlike the REST path there is no refresh-token fallback here, so once the
|
||||
// access token expires GraphQL treats the caller as anonymous until the front
|
||||
// end refreshes.
|
||||
func AuthContextMiddleware(auth *services.Auth) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ctx := context.WithValue(c.Request.Context(), ginContextKey, c)
|
||||
@@ -19,6 +31,8 @@ func AuthContextMiddleware(auth *services.Auth) gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// The context is immutable, so the enriched one has to be written
|
||||
// back onto the request for the gqlgen handler to see it.
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Next()
|
||||
}
|
||||
|
||||
@@ -15,6 +15,9 @@ import (
|
||||
|
||||
// CreatePlace is the resolver for the createPlace field.
|
||||
func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePlaceInput) (*models.Place, error) {
|
||||
// Any signed-in user, not just an admin — places are the one shared,
|
||||
// collaboratively edited list on the site. There is no per-user
|
||||
// ownership, so any signed-in user can edit or delete any place.
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
@@ -43,6 +46,8 @@ func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
// Partial update, same pointer-means-supplied convention as job
|
||||
// applications: nil fields are left as they are.
|
||||
var place models.Place
|
||||
if err := r.Store.DB.First(&place, id).Error; err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -48,10 +48,14 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U
|
||||
return nil, fmt.Errorf("post not found")
|
||||
}
|
||||
|
||||
// Admin alone is not enough: a post may only be edited by its author, so
|
||||
// one admin cannot rewrite another's posts.
|
||||
if post.AuthorID != userID {
|
||||
return nil, fmt.Errorf("you can only update your own posts")
|
||||
}
|
||||
|
||||
// Both fields are non-pointer in the input, so this is a full replace —
|
||||
// omitting one in the mutation blanks it rather than leaving it alone.
|
||||
post.Title = input.Title
|
||||
post.Content = input.Content
|
||||
if err := r.Store.DB.Save(&post).Error; err != nil {
|
||||
@@ -81,6 +85,8 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post
|
||||
return nil, fmt.Errorf("you can only delete your own posts")
|
||||
}
|
||||
|
||||
// Soft delete; the error is dropped, so a failed delete still reports
|
||||
// success to the client.
|
||||
r.Store.DB.Delete(&post)
|
||||
return &post, nil
|
||||
}
|
||||
@@ -92,10 +98,16 @@ func (r *postResolver) ID(ctx context.Context, obj *models.Post) (int, error) {
|
||||
|
||||
// Posts is the resolver for the posts field.
|
||||
func (r *queryResolver) Posts(ctx context.Context) ([]*models.Post, error) {
|
||||
// Preload issues a second query for the authors and fills in Post.Author.
|
||||
// Without it the field is nil and the schema's author field resolves to
|
||||
// null — there is no lazy loading and no error to tell you why.
|
||||
var posts []models.Post
|
||||
if err := r.Store.DB.Preload("Author").Order("created_at DESC").Find(&posts).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &posts[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Post, len(posts))
|
||||
for i := range posts {
|
||||
result[i] = &posts[i]
|
||||
|
||||
@@ -7,6 +7,15 @@ import "adam-french.co.uk/backend/handlers"
|
||||
// It serves as dependency injection for your app, add any dependencies you require
|
||||
// here.
|
||||
|
||||
// Resolver is the root of the GraphQL schema and the only dependency every
|
||||
// resolver has. Rather than listing dependencies individually it holds the
|
||||
// same handlers.Store the REST handlers use, so GraphQL and REST share one
|
||||
// database handle and one set of third-party caches.
|
||||
//
|
||||
// The generated code embeds *Resolver in per-type resolver structs
|
||||
// (queryResolver, mutationResolver, postResolver, ...), which is why those
|
||||
// one-line `struct{ *Resolver }` declarations appear at the bottom of each
|
||||
// resolvers file.
|
||||
type Resolver struct {
|
||||
Store *handlers.Store
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, e
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &rows[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Rowing, len(rows))
|
||||
for i := range rows {
|
||||
result[i] = &rows[i]
|
||||
@@ -30,6 +33,8 @@ func (r *rowingResolver) ID(ctx context.Context, obj *models.Rowing) (int, error
|
||||
}
|
||||
|
||||
// Time is the resolver for the time field.
|
||||
// Time is the resolver for the time field: total session seconds, narrowed
|
||||
// from uint64 to GraphQL's Int.
|
||||
func (r *rowingResolver) Time(ctx context.Context, obj *models.Rowing) (int, error) {
|
||||
return int(obj.Time), nil
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# Latest activity from the self-hosted Gitea instance, proxied and cached for
|
||||
# one minute by the backend. Resolves to null when the feed is empty.
|
||||
|
||||
type GiteaFeedItem {
|
||||
avatarUrl: String!
|
||||
repoUrl: String!
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
# Job application tracker. Rows come from these mutations or automatically
|
||||
# from the email sync pipeline (backend/services/email_sync.go). These are
|
||||
# private data, so the queries here are admin-only as well as the mutations.
|
||||
#
|
||||
# status is a free-form String, but only the values ranked in
|
||||
# services.statusOrder can be advanced automatically by the email pipeline:
|
||||
# applied, screening, assessment, interviewing, offer, rejected, withdrawn.
|
||||
|
||||
type JobApplication {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
# Chat history. The live chat runs over the WebSocket at /ws, not GraphQL;
|
||||
# this query is the initial page load.
|
||||
#
|
||||
# Two gotchas: authorId is a per-connection counter from the chat hub, not a
|
||||
# User id, and private messages are silently filtered out for non-admins
|
||||
# rather than causing an error.
|
||||
|
||||
type Message {
|
||||
id: ID!
|
||||
content: String!
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# Places to go. Unlike most mutations these require only a signed-in user,
|
||||
# not an admin, and there is no per-user ownership: the list is shared.
|
||||
|
||||
type Place {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
|
||||
@@ -1,3 +1,19 @@
|
||||
# Root of the GraphQL schema.
|
||||
#
|
||||
# Query and Mutation are declared here with no fields; every other file in this
|
||||
# directory adds to them with `extend type Query` / `extend type Mutation`.
|
||||
# That is what lets the schema be split one file per domain, matching the
|
||||
# one-file-per-domain resolver layout (gqlgen.yml uses layout: follow-schema).
|
||||
#
|
||||
# Time is mapped to Go's time.Time by gqlgen's default scalar handling and is
|
||||
# serialised as RFC 3339.
|
||||
#
|
||||
# These files are the source of truth: after editing one, run
|
||||
# go run github.com/99designs/gqlgen generate
|
||||
# from backend/ to regenerate graph/generated.go and graph/model/models_gen.go.
|
||||
# Note that `#` comments like this one are invisible to clients; a `"""` block
|
||||
# would become a schema description and show up in introspection.
|
||||
|
||||
scalar Time
|
||||
|
||||
type Query
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
# Spotify "now playing" / "recently played" for the home page. Both resolve to
|
||||
# null / an empty list when the backend has never completed the Spotify OAuth
|
||||
# flow, so the page degrades rather than erroring.
|
||||
|
||||
type SpotifyArtist {
|
||||
name: String!
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# Steam presence and recent games for the home page, cached for five minutes.
|
||||
# headerImage is built from the app id rather than returned by Steam's API.
|
||||
|
||||
type SteamGame {
|
||||
appId: Int!
|
||||
name: String!
|
||||
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
|
||||
// SpotifyListening is the resolver for the spotifyListening field.
|
||||
func (r *queryResolver) SpotifyListening(ctx context.Context) (*model.SpotifyPlaying, error) {
|
||||
// A nil client means the OAuth flow has never been completed. Report that
|
||||
// as null rather than an error so the home page renders without it.
|
||||
if r.Store.SpotifyClient == nil {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -38,6 +40,8 @@ func (r *queryResolver) SpotifyRecent(ctx context.Context) ([]*model.SpotifyRece
|
||||
return []*model.SpotifyRecentItem{}, nil
|
||||
}
|
||||
|
||||
// One-minute cache. This resolver is the only writer of that cache; the
|
||||
// REST /spotify/recent endpoint reads it but never fills it.
|
||||
if r.Store.RecentSongsFresh() {
|
||||
return mapRecentItems(*r.Store.RecentSongs), nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,11 @@ import (
|
||||
"github.com/zmb3/spotify/v2"
|
||||
)
|
||||
|
||||
// Converters from the Spotify library's rich types to the deliberately narrow
|
||||
// GraphQL types — the schema exposes only the handful of fields the home page
|
||||
// renders.
|
||||
|
||||
// mapSpotifyImages keeps just the URLs of a set of album images.
|
||||
func mapSpotifyImages(images []spotify.Image) []*model.SpotifyImage {
|
||||
result := make([]*model.SpotifyImage, len(images))
|
||||
for i, img := range images {
|
||||
@@ -13,6 +18,7 @@ func mapSpotifyImages(images []spotify.Image) []*model.SpotifyImage {
|
||||
return result
|
||||
}
|
||||
|
||||
// mapSpotifyTrack converts a currently-playing track.
|
||||
func mapSpotifyTrack(track *spotify.FullTrack) *model.SpotifyTrack {
|
||||
artists := make([]*model.SpotifyArtist, len(track.Artists))
|
||||
for i, a := range track.Artists {
|
||||
@@ -28,6 +34,11 @@ func mapSpotifyTrack(track *spotify.FullTrack) *model.SpotifyTrack {
|
||||
}
|
||||
}
|
||||
|
||||
// mapRecentItems converts recently played history entries.
|
||||
//
|
||||
// It rebuilds the track inline instead of calling mapSpotifyTrack because a
|
||||
// RecentlyPlayedItem holds a SimpleTrack, not the FullTrack that function
|
||||
// takes — the duplication is forced by the library's types.
|
||||
func mapRecentItems(items []spotify.RecentlyPlayedItem) []*model.SpotifyRecentItem {
|
||||
result := make([]*model.SpotifyRecentItem, len(items))
|
||||
for i, item := range items {
|
||||
|
||||
@@ -19,6 +19,8 @@ func (r *queryResolver) SteamStatus(ctx context.Context) (*model.SteamStatus, er
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Five-minute cache across both Steam calls, which are made together and
|
||||
// expire together.
|
||||
if r.Store.SteamFresh() {
|
||||
return &model.SteamStatus{
|
||||
Online: r.Store.SteamOnline,
|
||||
@@ -36,6 +38,8 @@ func (r *queryResolver) SteamStatus(ctx context.Context) (*model.SteamStatus, er
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// PersonaState 0 is offline; every higher value is some flavour of
|
||||
// online. A nil summary (private profile) reads as offline.
|
||||
online := false
|
||||
if summary != nil {
|
||||
online = summary.PersonaState > 0
|
||||
|
||||
@@ -7,6 +7,11 @@ import (
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// mapSteamGames converts Steam API games into the GraphQL shape.
|
||||
//
|
||||
// HeaderImageURL is synthesised rather than returned by the API: Steam's CDN
|
||||
// serves every game's cover art at a predictable path keyed by app id, so
|
||||
// building the URL here saves an extra API call per game.
|
||||
func mapSteamGames(games []services.SteamRecentGame) []*model.SteamGame {
|
||||
result := make([]*model.SteamGame, len(games))
|
||||
for i, g := range games {
|
||||
|
||||
@@ -20,6 +20,8 @@ func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUse
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
// Only an existing admin can create accounts — there is no public
|
||||
// sign-up. New users are created non-admin; setUserAdmin promotes them.
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -62,6 +64,8 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
// Guards against the last admin demoting themselves and locking everyone
|
||||
// out of the admin UI.
|
||||
if uint(id) == callerID {
|
||||
return nil, fmt.Errorf("cannot change your own admin status")
|
||||
}
|
||||
@@ -88,6 +92,9 @@ func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
|
||||
if err := r.Store.DB.Find(&users).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &users[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.User, len(users))
|
||||
for i := range users {
|
||||
result[i] = &users[i]
|
||||
|
||||
@@ -5,16 +5,38 @@ import (
|
||||
"net/http"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// This file holds the REST authentication endpoints and the Gin middleware
|
||||
// that guards the other REST routes. GraphQL has its own parallel
|
||||
// implementation of login/logout/refresh in graph/auth.resolvers.go; both
|
||||
// mint the same cookies through services.Auth.
|
||||
//
|
||||
// Cookie model: `access_token` is short-lived and carries id + admin, so most
|
||||
// requests authorise without a database hit; `refresh_token` carries only the
|
||||
// id and is exchanged for a fresh pair. Both are set HttpOnly and Secure, so
|
||||
// JavaScript cannot read them and the browser attaches them automatically.
|
||||
|
||||
// UserCredentials is the JSON body of POST /auth/login. The binding tags make
|
||||
// Gin reject a request missing either field.
|
||||
type UserCredentials struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
// AuthMiddlewear requires a valid access token on a REST route and stashes
|
||||
// the claims for AdminMiddleware to read.
|
||||
//
|
||||
// (The name is misspelled but it is exported and referenced from main.go, so
|
||||
// it is left alone rather than renamed.)
|
||||
//
|
||||
// It deliberately does NOT fall back to the refresh token: an expired access
|
||||
// token yields a 401 and the front end is expected to call /auth/refresh and
|
||||
// retry.
|
||||
func (store *Store) AuthMiddlewear(ctx *gin.Context) {
|
||||
access_token, err := ctx.Cookie("access_token")
|
||||
if err != nil {
|
||||
@@ -28,11 +50,20 @@ func (store *Store) AuthMiddlewear(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// store claims in Gin context
|
||||
// Stored under a plain string key in the *Gin* context. This is a
|
||||
// different mechanism from graph/context.go, which puts the same claims
|
||||
// into the standard library request context under an unexported typed
|
||||
// key; the two do not see each other's values.
|
||||
ctx.Set("userClaims", claims)
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
// AdminMiddleware requires the access token to carry admin=true. It must be
|
||||
// chained after AuthMiddlewear, which is what populates "userClaims"; on its
|
||||
// own it always rejects.
|
||||
//
|
||||
// Admin is read from the token, not the database, so revoking someone's admin
|
||||
// flag only takes effect once their current access token expires.
|
||||
func (store *Store) AdminMiddleware(ctx *gin.Context) {
|
||||
claims, exists := ctx.Get("userClaims")
|
||||
if !exists {
|
||||
@@ -46,6 +77,8 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// A token minted before the admin claim existed simply has no "admin"
|
||||
// key, so a failed type assertion is treated as "not an admin".
|
||||
admin, ok := (*mapClaims)["admin"].(bool)
|
||||
if !ok || !admin {
|
||||
ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
||||
@@ -55,6 +88,13 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
// ValidateAdmin backs GET /auth/validate-admin, which the front end calls to
|
||||
// decide whether to show admin UI. It answers with a bare status code and no
|
||||
// body: 200 admin, 403 authenticated but not admin, 401 not authenticated.
|
||||
//
|
||||
// Unlike AdminMiddleware it falls back to the refresh token, and will mint a
|
||||
// new cookie pair as a side effect, so a returning admin is recognised
|
||||
// without a visible re-login.
|
||||
func (store *Store) ValidateAdmin(ctx *gin.Context) {
|
||||
accessToken, err := ctx.Cookie("access_token")
|
||||
if err != nil {
|
||||
@@ -83,6 +123,16 @@ func (store *Store) ValidateAdmin(ctx *gin.Context) {
|
||||
ctx.Status(http.StatusOK)
|
||||
}
|
||||
|
||||
// tryRefreshAndValidateAdmin re-authenticates from the refresh token.
|
||||
//
|
||||
// The bool does not mean "is an admin" — it means "this function already
|
||||
// wrote the response". It returns true both for a successful admin refresh
|
||||
// (200, new cookies set) and for a valid non-admin (403), and false only when
|
||||
// it could not decide, leaving the caller to send 401. Getting this backwards
|
||||
// would send two status codes for one request.
|
||||
//
|
||||
// Admin status is re-read from the database here, which is what makes the
|
||||
// refresh path pick up a revoked admin flag.
|
||||
func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
|
||||
refreshToken, err := ctx.Cookie("refresh_token")
|
||||
if err != nil {
|
||||
@@ -99,6 +149,9 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// Pre-setting ID and calling First with no explicit condition makes GORM
|
||||
// use the primary key already in the struct as the lookup. Soft-deleted
|
||||
// users are excluded automatically, so a deleted admin fails here.
|
||||
user := models.User{ID: uint(userIDF)}
|
||||
if err := store.DB.First(&user).Error; err != nil {
|
||||
return false
|
||||
@@ -114,6 +167,21 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
store.setAuthCookies(ctx, tokens)
|
||||
|
||||
ctx.Status(http.StatusOK)
|
||||
return true
|
||||
}
|
||||
|
||||
// setAuthCookies writes the access/refresh cookie pair.
|
||||
//
|
||||
// The two trailing booleans of gin's SetCookie are Secure and HttpOnly, both
|
||||
// true here: the cookies are never sent over plain HTTP and are invisible to
|
||||
// JavaScript. SameSite=Lax lets them survive a top-level navigation back from
|
||||
// an OAuth provider while still blocking cross-site POSTs. Each cookie's
|
||||
// max-age mirrors the lifetime baked into the token itself, so the browser
|
||||
// drops it at roughly the moment it stops being accepted.
|
||||
func (store *Store) setAuthCookies(ctx *gin.Context, tokens *services.Tokens) {
|
||||
ctx.SetSameSite(http.SameSiteLaxMode)
|
||||
ctx.SetCookie(
|
||||
"access_token",
|
||||
@@ -131,11 +199,12 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
|
||||
ctx.Status(http.StatusOK)
|
||||
return true
|
||||
}
|
||||
|
||||
// CheckToken backs GET /auth/check: it returns the current user for a valid
|
||||
// access token, or 401. If the token is valid but the user no longer exists
|
||||
// it answers 404 and clears the cookies, so the browser stops presenting a
|
||||
// token for a deleted account.
|
||||
func (store *Store) CheckToken(ctx *gin.Context) {
|
||||
access_token, err := ctx.Cookie("access_token")
|
||||
if err != nil {
|
||||
@@ -149,6 +218,8 @@ func (store *Store) CheckToken(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// JWT claims come back through encoding/json, so every number is a
|
||||
// float64 regardless of the Go type it was signed from.
|
||||
userIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
ctx.JSON(401, gin.H{"error": "unauthorized"})
|
||||
@@ -168,6 +239,11 @@ func (store *Store) CheckToken(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, user)
|
||||
}
|
||||
|
||||
// RefreshToken backs POST /auth/refresh: it exchanges a valid refresh token
|
||||
// for a new cookie pair and returns the user.
|
||||
//
|
||||
// Tokens are not rotated in any revocable sense — the old refresh token stays
|
||||
// valid until it expires, because nothing is tracked server-side.
|
||||
func (store *Store) RefreshToken(ctx *gin.Context) {
|
||||
refreshToken, err := ctx.Cookie("refresh_token")
|
||||
if err != nil {
|
||||
@@ -204,28 +280,18 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.SetSameSite(http.SameSiteLaxMode)
|
||||
ctx.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
ctx.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
store.setAuthCookies(ctx, tokens)
|
||||
|
||||
ctx.JSON(http.StatusAccepted, user)
|
||||
}
|
||||
|
||||
// Login backs POST /auth/login. The user object it returns omits the password
|
||||
// because models.User tags that field `json:"-"`.
|
||||
func (store *Store) Login(ctx *gin.Context) {
|
||||
// Per-IP limit (5/min) on top of nginx's own login rate limit.
|
||||
// ctx.ClientIP is only trustworthy because main.go pins the trusted
|
||||
// proxy range, so the X-Forwarded-For header cannot be spoofed by a
|
||||
// client talking through nginx.
|
||||
if !store.LoginLimiter.Allow(ctx.ClientIP()) {
|
||||
ctx.JSON(http.StatusTooManyRequests, gin.H{"error": "too many login attempts, please try again later"})
|
||||
return
|
||||
@@ -237,6 +303,9 @@ func (store *Store) Login(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Unknown user and wrong password return the identical message, so the
|
||||
// response cannot be used to enumerate usernames. (The timing does
|
||||
// differ, since only the second path runs bcrypt.)
|
||||
user := models.User{}
|
||||
if err := store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
|
||||
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
|
||||
@@ -255,33 +324,23 @@ func (store *Store) Login(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.SetSameSite(http.SameSiteLaxMode)
|
||||
ctx.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
ctx.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
store.setAuthCookies(ctx, tokens)
|
||||
|
||||
ctx.JSON(http.StatusAccepted, user)
|
||||
}
|
||||
|
||||
// Logout backs POST /auth/logout. It only clears the browser's cookies —
|
||||
// the tokens themselves stay cryptographically valid until they expire, so a
|
||||
// copy taken beforehand would still work.
|
||||
func (store *Store) Logout(ctx *gin.Context) {
|
||||
store.removeCookies(ctx)
|
||||
|
||||
ctx.Status(http.StatusOK)
|
||||
}
|
||||
|
||||
// removeCookies expires both auth cookies. The max-age of -1 is what tells
|
||||
// the browser to delete them; path, domain and the Secure/HttpOnly flags must
|
||||
// match those used when setting them or the browser keeps the originals.
|
||||
func (store *Store) removeCookies(ctx *gin.Context) {
|
||||
ctx.SetSameSite(http.SameSiteLaxMode)
|
||||
ctx.SetCookie(
|
||||
|
||||
@@ -7,7 +7,16 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// REST endpoints for the job-application email pipeline: a manual
|
||||
// admin-triggered sync, and the OAuth redirect target (which has to be REST
|
||||
// because Microsoft redirects a browser to it).
|
||||
|
||||
// TriggerEmailSync backs the admin-only POST /email/sync and runs one sync
|
||||
// synchronously, so the response reflects the result. If the scheduler is
|
||||
// mid-sync the service refuses via TryLock and this returns 500.
|
||||
func (store *Store) TriggerEmailSync(ctx *gin.Context) {
|
||||
// A nil HTTPClient is the service's readiness flag — see
|
||||
// services.EmailSyncService.
|
||||
if store.EmailSync == nil || store.EmailSync.HTTPClient == nil {
|
||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured or not authenticated"})
|
||||
return
|
||||
@@ -23,6 +32,13 @@ func (store *Store) TriggerEmailSync(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "sync completed"})
|
||||
}
|
||||
|
||||
// CompleteEmailAuth handles Microsoft's OAuth redirect to
|
||||
// GET /email/callback and stores the resulting token.
|
||||
//
|
||||
// The route is unauthenticated (Microsoft's redirect carries no site cookie),
|
||||
// which is safe only because the code is worthless without the app's client
|
||||
// secret. Note that completing auth here does not start the scheduler, which
|
||||
// only checks readiness at start-up — a restart is needed for that.
|
||||
func (store *Store) CompleteEmailAuth(ctx *gin.Context) {
|
||||
if store.EmailSync == nil {
|
||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured"})
|
||||
|
||||
@@ -12,18 +12,33 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Attachment upload for the chat. Files land in a directory that nginx serves
|
||||
// directly at /uploads/, so anything written here is publicly reachable by
|
||||
// URL — which is why the extension and content checks below matter.
|
||||
|
||||
// allowedExtensions is the upload allow-list, keyed by lower-cased extension.
|
||||
var allowedExtensions = map[string]bool{
|
||||
".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".webp": true,
|
||||
".mp4": true, ".webm": true, ".mp3": true, ".ogg": true,
|
||||
".pdf": true, ".txt": true,
|
||||
}
|
||||
|
||||
// extensionToMIMEPrefix cross-checks the sniffed content type against the
|
||||
// claimed extension, to stop e.g. HTML being served from a .png URL.
|
||||
//
|
||||
// The audio extensions (.mp3, .ogg) and .gif are deliberately absent:
|
||||
// http.DetectContentType's answers for them are unreliable enough to reject
|
||||
// legitimate files, so a missing entry means "extension allowed, content not
|
||||
// verified".
|
||||
var extensionToMIMEPrefix = map[string]string{
|
||||
".jpg": "image/", ".jpeg": "image/", ".png": "image/", ".gif": "image/", ".webp": "image/",
|
||||
".mp4": "video/", ".webm": "video/",
|
||||
".pdf": "application/pdf", ".txt": "text/",
|
||||
}
|
||||
|
||||
// UploadMessageFile backs POST /messages/upload (login required) and returns
|
||||
// the public URL of the stored file, which the client then sends over the
|
||||
// WebSocket as a message's fileUrl.
|
||||
func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
file, err := ctx.FormFile("file")
|
||||
if err != nil {
|
||||
@@ -49,6 +64,10 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read file"})
|
||||
return
|
||||
}
|
||||
// 512 bytes is exactly what http.DetectContentType inspects; reading more
|
||||
// would be wasted. A single Read may return fewer bytes than asked for,
|
||||
// which is fine — sniffing works on a short prefix — so only a read that
|
||||
// produced nothing at all is an error.
|
||||
buf := make([]byte, 512)
|
||||
n, err := f.Read(buf)
|
||||
f.Close()
|
||||
@@ -64,6 +83,10 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// The uploaded name is discarded entirely in favour of 16 random bytes
|
||||
// from crypto/rand. That kills path traversal and collisions in one go,
|
||||
// and makes the resulting URL unguessable. Only the extension is carried
|
||||
// over, and it has already been checked against the allow-list.
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate filename"})
|
||||
@@ -74,6 +97,9 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
uploadDir := "/backend/uploads/"
|
||||
dest := filepath.Join(uploadDir, filename)
|
||||
|
||||
// Reopened rather than rewound: the earlier handle was closed after
|
||||
// sniffing, and multipart files may be backed by either memory or a temp
|
||||
// file, so a fresh reader is the simplest correct option.
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read file"})
|
||||
|
||||
@@ -7,9 +7,16 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// GetNoteFile serves one file from the notes directory for the admin-only
|
||||
// route GET /notes/*path. The wildcard means `path` arrives with a leading
|
||||
// slash and may contain further slashes, so it has to be validated rather
|
||||
// than trusted — Notes.ParsePath does the containment check.
|
||||
|
||||
func (store *Store) GetNoteFile(ctx *gin.Context) {
|
||||
path := ctx.Param("path")
|
||||
|
||||
// A traversal attempt is reported as 404, not 403, so probing cannot
|
||||
// distinguish a blocked path from a missing one.
|
||||
path, err := store.Notes.ParsePath(path)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
@@ -22,6 +29,9 @@ func (store *Store) GetNoteFile(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// The SPA reads Last-Modified to show a note's edit date. Browsers hide
|
||||
// non-safelisted headers from cross-origin fetch() unless they are listed
|
||||
// in Access-Control-Expose-Headers, hence the second header.
|
||||
ctx.Header("Last-Modified", info.ModTime().UTC().Format(http.TimeFormat))
|
||||
ctx.Header("Access-Control-Expose-Headers", "Content-Disposition, Last-Modified")
|
||||
|
||||
|
||||
@@ -9,12 +9,27 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Admin management of the radio's fallback music. These handlers only move
|
||||
// files around on disk; the Python service is what actually streams them, and
|
||||
// it picks up the directory contents on its own.
|
||||
//
|
||||
// Disabling a song moves it into a "disabled" subdirectory rather than
|
||||
// deleting it — so presence in that directory IS the disabled flag, and there
|
||||
// is no database state for the radio at all.
|
||||
|
||||
// fallbackMusicDir is a shared volume, also mounted by the radio service.
|
||||
const fallbackMusicDir = "/backend/fallback_music"
|
||||
|
||||
// allowedAudioExtensions is the upload allow-list, keyed by lower-cased
|
||||
// extension. Unlike chat uploads, the content is not sniffed: the route is
|
||||
// admin-only and audio formats sniff unreliably.
|
||||
var allowedAudioExtensions = map[string]bool{
|
||||
".mp3": true, ".ogg": true, ".flac": true, ".wav": true, ".m4a": true, ".opus": true,
|
||||
}
|
||||
|
||||
// UploadRadioSong backs the admin-only POST /radio/upload. Unlike chat
|
||||
// uploads the original filename is kept, because it is what the admin sees in
|
||||
// the song list — hence the sanitisation below.
|
||||
func (store *Store) UploadRadioSong(ctx *gin.Context) {
|
||||
file, err := ctx.FormFile("file")
|
||||
if err != nil {
|
||||
@@ -34,16 +49,22 @@ func (store *Store) UploadRadioSong(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// filepath.Base strips any directory component, so "../../etc/passwd"
|
||||
// becomes "passwd". The absolute-path check below is a second, redundant
|
||||
// guard in case Base ever fails to neutralise some input.
|
||||
filename := filepath.Base(file.Filename)
|
||||
dest := filepath.Join(fallbackMusicDir, filename)
|
||||
|
||||
// Verify the resolved path stays within the music directory
|
||||
// The separator is appended before comparing so a sibling directory whose
|
||||
// name merely starts with the same characters cannot pass.
|
||||
absDest, err := filepath.Abs(dest)
|
||||
if err != nil || !strings.HasPrefix(absDest, fallbackMusicDir+string(os.PathSeparator)) {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
|
||||
return
|
||||
}
|
||||
|
||||
// Refuse to overwrite. There is a check-then-write race here, but the
|
||||
// route is admin-only and single-user in practice.
|
||||
if _, err := os.Stat(dest); err == nil {
|
||||
ctx.JSON(http.StatusConflict, gin.H{"error": "file already exists"})
|
||||
return
|
||||
@@ -57,7 +78,11 @@ func (store *Store) UploadRadioSong(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, gin.H{"name": filename})
|
||||
}
|
||||
|
||||
// ListRadioSongs backs the admin-only GET /radio/songs, returning both the
|
||||
// enabled songs and those parked in the disabled subdirectory, flagged.
|
||||
func (store *Store) ListRadioSongs(ctx *gin.Context) {
|
||||
// Declared inside the function because it is purely the JSON shape of
|
||||
// this one response.
|
||||
type songInfo struct {
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
@@ -65,6 +90,7 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) {
|
||||
Disabled bool `json:"disabled"`
|
||||
}
|
||||
|
||||
// Initialised empty rather than nil so the response is [] and not null.
|
||||
songs := []songInfo{}
|
||||
|
||||
// Read enabled songs
|
||||
@@ -73,6 +99,8 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read music directory"})
|
||||
return
|
||||
}
|
||||
// Skipping directories is also what keeps the "disabled" subdirectory out
|
||||
// of the enabled list; dotfiles skip editor and OS cruft.
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || strings.HasPrefix(entry.Name(), ".") {
|
||||
continue
|
||||
@@ -89,7 +117,9 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// Read disabled songs
|
||||
// The disabled directory is created lazily by DisableRadioSong, so a read
|
||||
// failure here is normally just "nothing has ever been disabled" and is
|
||||
// ignored rather than reported.
|
||||
disabledDir := filepath.Join(fallbackMusicDir, "disabled")
|
||||
disabledEntries, err := os.ReadDir(disabledDir)
|
||||
if err == nil {
|
||||
@@ -113,7 +143,12 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, gin.H{"songs": songs})
|
||||
}
|
||||
|
||||
// DisableRadioSong moves a song into the disabled subdirectory so the radio
|
||||
// stops playing it, keeping the file.
|
||||
func (store *Store) DisableRadioSong(ctx *gin.Context) {
|
||||
// filepath.Base neutralises traversal in the :filename route parameter.
|
||||
// It returns "." for an empty input and "/" for "/", neither of which is
|
||||
// a real file, so both are rejected explicitly.
|
||||
filename := filepath.Base(ctx.Param("filename"))
|
||||
if filename == "." || filename == "/" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
|
||||
@@ -141,6 +176,7 @@ func (store *Store) DisableRadioSong(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, gin.H{"disabled": filename})
|
||||
}
|
||||
|
||||
// EnableRadioSong moves a song back out of the disabled subdirectory.
|
||||
func (store *Store) EnableRadioSong(ctx *gin.Context) {
|
||||
filename := filepath.Base(ctx.Param("filename"))
|
||||
if filename == "." || filename == "/" {
|
||||
@@ -163,6 +199,9 @@ func (store *Store) EnableRadioSong(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, gin.H{"enabled": filename})
|
||||
}
|
||||
|
||||
// DeleteRadioSong permanently removes an enabled song. It cannot reach the
|
||||
// disabled subdirectory, so a disabled song must be enabled before it can be
|
||||
// deleted.
|
||||
func (store *Store) DeleteRadioSong(ctx *gin.Context) {
|
||||
filename := filepath.Base(ctx.Param("filename"))
|
||||
if filename == "." || filename == "/" {
|
||||
|
||||
@@ -16,14 +16,25 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Rowing log. The interesting endpoint is CreateRowing: rather than a form,
|
||||
// the admin uploads a photo of the rowing machine display and Claude reads the
|
||||
// numbers off it. The session date comes from the photo's EXIF metadata, which
|
||||
// also doubles as the deduplication key.
|
||||
|
||||
// ExtractedRowingData is the JSON contract for what Claude reads off the
|
||||
// display; the keys must match the prompt in CreateRowing.
|
||||
type ExtractedRowingData struct {
|
||||
TimeMinutes uint64 `json:"timeMinutes"`
|
||||
TimeSeconds uint64 `json:"timeSeconds"`
|
||||
Distance uint64 `json:"distance"`
|
||||
}
|
||||
|
||||
// GetRowing backs the public GET /rowing with every logged session, newest
|
||||
// first.
|
||||
func (store *Store) GetRowing(ctx *gin.Context) {
|
||||
var rowing []models.Rowing
|
||||
// "Created_At" works because Postgres folds unquoted identifiers to lower
|
||||
// case; the column is created_at.
|
||||
if err := store.DB.Order("Created_At DESC").Find(&rowing).Error; err != nil {
|
||||
log.Println(err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
@@ -32,6 +43,12 @@ func (store *Store) GetRowing(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, rowing)
|
||||
}
|
||||
|
||||
// CreateRowing backs the admin-only POST /rowing: it takes a photo of the
|
||||
// rowing machine display, dates it from EXIF, has Claude read the time and
|
||||
// distance, sanity-checks the result and stores a session.
|
||||
//
|
||||
// Note it is admin-gated and calls a paid API once per request, so the
|
||||
// validation below exists to catch misreadings rather than hostile input.
|
||||
func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
file, err := ctx.FormFile("image")
|
||||
if err != nil {
|
||||
@@ -46,20 +63,23 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// Get the date taken from the EXIF data
|
||||
x, err := exif.Decode(f)
|
||||
// EXIF is required, not optional: it is both the session date and the
|
||||
// duplicate key, so a stripped-metadata image (anything that has been
|
||||
// through most messaging apps) is rejected outright.
|
||||
exifData, err := exif.Decode(f)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "no EXIF data found"})
|
||||
return
|
||||
}
|
||||
|
||||
dateTaken, err := x.DateTime()
|
||||
dateTaken, err := exifData.DateTime()
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "no date found in EXIF data"})
|
||||
return
|
||||
}
|
||||
|
||||
// Seek back to start since exif.Decode advanced the cursor
|
||||
// exif.Decode consumed part of the stream, so rewind before reading the
|
||||
// bytes to send to Claude.
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to seek image"})
|
||||
return
|
||||
@@ -77,6 +97,9 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
"image/gif": true,
|
||||
"image/webp": true,
|
||||
}
|
||||
// This is the browser's claimed type, not a sniffed one; it is passed
|
||||
// straight through to the Anthropic API, so the allow-list is there to
|
||||
// keep the API call well-formed rather than to police the file.
|
||||
mediaType := file.Header.Get("Content-Type")
|
||||
if !allowedMediaTypes[mediaType] {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "unsupported image type"})
|
||||
@@ -84,7 +107,11 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
}
|
||||
encoded := base64.StdEncoding.EncodeToString(data)
|
||||
|
||||
// Reject duplicates: same EXIF datetime already recorded
|
||||
// Duplicate guard: two photos of the same session share an EXIF capture
|
||||
// time to the second. Checked before the Claude call so a re-upload costs
|
||||
// nothing. Note this reads err == nil as "found" — an actual database
|
||||
// error is indistinguishable from "no match" here and lets the insert
|
||||
// proceed.
|
||||
var existing models.Rowing
|
||||
if err := store.DB.Where("date = ?", dateTaken).First(&existing).Error; err == nil {
|
||||
ctx.JSON(http.StatusConflict, gin.H{"error": "duplicate entry for this date"})
|
||||
@@ -130,6 +157,8 @@ No text, no markdown, no explanation. Just the JSON object.`),
|
||||
return
|
||||
}
|
||||
|
||||
// Strip a markdown code fence if the model wrapped its JSON in one
|
||||
// despite the prompt. Same defensive dance as in services/email_sync.go.
|
||||
extractedData := ExtractedRowingData{}
|
||||
raw := message.Content[0].Text
|
||||
|
||||
@@ -153,7 +182,10 @@ No text, no markdown, no explanation. Just the JSON object.`),
|
||||
|
||||
totalSeconds := extractedData.TimeMinutes*60 + extractedData.TimeSeconds
|
||||
|
||||
// Validate for anomalous values
|
||||
// Sanity bounds on what Claude claims to have read. A misread digit
|
||||
// typically lands far outside human rowing performance, and the pace
|
||||
// check catches the case where time and distance are individually
|
||||
// plausible but inconsistent with each other.
|
||||
const (
|
||||
minDistance = 100 // metres
|
||||
maxDistance = 100000 // metres
|
||||
@@ -177,6 +209,9 @@ No text, no markdown, no explanation. Just the JSON object.`),
|
||||
return
|
||||
}
|
||||
|
||||
// Rough calorie estimate from distance alone: roughly 500 kcal per
|
||||
// 7500 m. Not from the machine and not physiologically derived — it is a
|
||||
// display figure only.
|
||||
calories := float64(extractedData.Distance) / 7500.0 * 500.0
|
||||
|
||||
rowing := models.Rowing{
|
||||
|
||||
@@ -11,11 +11,23 @@ import (
|
||||
"github.com/zmb3/spotify/v2"
|
||||
)
|
||||
|
||||
// These REST endpoints predate the equivalent GraphQL queries in
|
||||
// graph/spotify.resolvers.go and are kept for the OAuth callback (which must
|
||||
// be REST, because Spotify redirects a browser to it) and for direct use.
|
||||
|
||||
// CompleteSpotifyAuth handles Spotify's OAuth redirect to
|
||||
// GET /spotify/callback. It swaps the code for a token, saves it so the
|
||||
// authorisation survives restarts, and installs the authenticated client on
|
||||
// the Store — which is how Store.SpotifyClient becomes non-nil without a
|
||||
// restart.
|
||||
func (store *Store) CompleteSpotifyAuth(ctx *gin.Context) {
|
||||
state := ctx.Query("state")
|
||||
// context.Background, not the request context: the client built below
|
||||
// outlives this request and would otherwise be cancelled when it ends.
|
||||
c := context.Background()
|
||||
// code := c.Query("code")
|
||||
|
||||
// The library pulls the `code` out of the request itself and checks the
|
||||
// state parameter matches the one passed here.
|
||||
token, err := store.SpotifyAuth.Token(c, state, ctx.Request)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
@@ -38,6 +50,9 @@ func (store *Store) CompleteSpotifyAuth(ctx *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// ListeningTo backs GET /spotify/listening with the currently playing track.
|
||||
// A nil client means the OAuth flow has never been completed, reported here
|
||||
// as a 500.
|
||||
func (store *Store) ListeningTo(ctx *gin.Context) {
|
||||
c := ctx.Request.Context()
|
||||
|
||||
@@ -56,6 +71,12 @@ func (store *Store) ListeningTo(ctx *gin.Context) {
|
||||
ctx.JSON(200, playing)
|
||||
}
|
||||
|
||||
// RecentlyPlayed backs GET /spotify/recent.
|
||||
//
|
||||
// It reads the cache but never writes it: only the GraphQL spotifyRecent
|
||||
// resolver populates Store.RecentSongs. So this endpoint serves cached data
|
||||
// only when a GraphQL query happened to fill the cache in the last minute,
|
||||
// and otherwise calls Spotify every time.
|
||||
func (store *Store) RecentlyPlayed(ctx *gin.Context) {
|
||||
if store.SpotifyClient == nil {
|
||||
ctx.JSON(500, gin.H{"error": "Spotify not authenticated"})
|
||||
@@ -79,6 +100,9 @@ func (store *Store) RecentlyPlayed(ctx *gin.Context) {
|
||||
ctx.JSON(200, played)
|
||||
}
|
||||
|
||||
// RecentSongsFresh reports whether the cached recently-played list is within
|
||||
// its one-minute TTL. An empty list counts as stale, so an empty listening
|
||||
// history is re-fetched every time.
|
||||
func (s *Store) RecentSongsFresh() bool {
|
||||
if s.RecentSongs == nil {
|
||||
return false
|
||||
|
||||
@@ -6,6 +6,9 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ConnectWebSocket upgrades GET /ws into a chat connection. The route is
|
||||
// public: anyone may chat, and admin status only adds the ability to see and
|
||||
// send private messages and to delete.
|
||||
func (store *Store) ConnectWebSocket(ctx *gin.Context) {
|
||||
// Work out admin status before upgrading: the browser sends the auth
|
||||
// cookies with the upgrade request, but they are not available afterwards.
|
||||
|
||||
@@ -10,6 +10,18 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Package handlers holds the REST endpoints and the shared Store that every
|
||||
// request handler — and, through graph.Resolver, every GraphQL resolver —
|
||||
// depends on.
|
||||
//
|
||||
// Store is the backend's dependency container: it is built once in main and
|
||||
// passed around by pointer, so the caches on it are shared process-wide.
|
||||
//
|
||||
// Concurrency note: the cache fields below are read and written by concurrent
|
||||
// requests without a mutex. The races are benign in practice (worst case two
|
||||
// requests refresh the same third-party API at once, or one reads a value
|
||||
// being replaced), but this is a deliberate simplification, not an oversight
|
||||
// — do not add a field here that would be unsafe to tear.
|
||||
type Store struct {
|
||||
DB *gorm.DB
|
||||
SpotifyAuth *spotifyauth.Authenticator
|
||||
@@ -20,14 +32,19 @@ type Store struct {
|
||||
LoginLimiter *services.RateLimiter
|
||||
EmailSync *services.EmailSyncService
|
||||
|
||||
// Cached "recently played" tracks, refreshed at most once a minute by the
|
||||
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
|
||||
// mean "never fetched" distinctly from "fetched, empty".
|
||||
RecentSongs *[]spotify.RecentlyPlayedItem
|
||||
RecentSongsFetchedAt time.Time
|
||||
|
||||
// Cached latest Gitea activity entry, 1 minute TTL.
|
||||
GiteaHost string
|
||||
GiteaPort string
|
||||
GiteaFeed *services.GiteaFeedResponse
|
||||
GiteaFeedFetchedAt time.Time
|
||||
|
||||
// Cached Steam status and recent games, 5 minute TTL.
|
||||
SteamAPIKey string
|
||||
SteamID string
|
||||
SteamRecentGames []services.SteamRecentGame
|
||||
@@ -35,6 +52,9 @@ type Store struct {
|
||||
SteamFetchedAt time.Time
|
||||
}
|
||||
|
||||
// GiteaFeedFresh reports whether the cached Gitea feed entry is still within
|
||||
// its one-minute TTL. A nil cache is never fresh, so the first request always
|
||||
// hits Gitea.
|
||||
func (s *Store) GiteaFeedFresh() bool {
|
||||
if s.GiteaFeed == nil {
|
||||
return false
|
||||
@@ -42,6 +62,10 @@ func (s *Store) GiteaFeedFresh() bool {
|
||||
return time.Since(s.GiteaFeedFetchedAt) < time.Minute
|
||||
}
|
||||
|
||||
// SteamFresh reports whether the cached Steam data is still within its
|
||||
// five-minute TTL. Note it tests only SteamRecentGames: if Steam legitimately
|
||||
// returns no recent games, the cache never registers as fresh and every
|
||||
// request re-queries the API.
|
||||
func (s *Store) SteamFresh() bool {
|
||||
if s.SteamRecentGames == nil {
|
||||
return false
|
||||
|
||||
+51
-1
@@ -21,7 +21,17 @@ 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 does its own per-resolver authorisation
|
||||
// instead of using middleware. See backend/README.md for the wider picture.
|
||||
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 {
|
||||
@@ -35,6 +45,10 @@ func main() {
|
||||
|
||||
r := gin.Default()
|
||||
|
||||
// Only the Docker network nginx 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.
|
||||
err = r.SetTrustedProxies([]string{"172.28.0.0/16"})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
@@ -50,10 +64,15 @@ 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.
|
||||
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
|
||||
@@ -71,6 +90,9 @@ func main() {
|
||||
|
||||
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}
|
||||
@@ -87,6 +109,8 @@ func main() {
|
||||
steamID := os.Getenv("STEAM_ID")
|
||||
|
||||
// EMAIL SYNC
|
||||
// An unparseable EMAIL_SYNC_INTERVAL is silently ignored and the 30
|
||||
// minute default stands — a typo here fails quietly.
|
||||
emailSyncInterval := 30 * time.Minute
|
||||
if interval := os.Getenv("EMAIL_SYNC_INTERVAL"); interval != "" {
|
||||
if parsed, err := time.ParseDuration(interval); err == nil {
|
||||
@@ -110,10 +134,16 @@ func main() {
|
||||
}
|
||||
emailSync := services.InitEmailSync(&emailSyncConfig, db, claudeClient)
|
||||
|
||||
// 5 login attempts per IP per minute, applied by both the REST handler
|
||||
// and the GraphQL login mutation. Nginx rate-limits the login route too.
|
||||
loginLimiter := services.NewRateLimiter(5, time.Minute)
|
||||
|
||||
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, ClaudeClient: claudeClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, EmailSync: emailSync, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID}
|
||||
|
||||
// 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: nginx strips it before proxying.
|
||||
protected := r.Group("/", store.AuthMiddlewear)
|
||||
admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware)
|
||||
|
||||
@@ -146,6 +176,8 @@ func main() {
|
||||
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.
|
||||
r.GET("/ws", store.ConnectWebSocket)
|
||||
protected.POST("/messages/upload", store.UploadMessageFile)
|
||||
|
||||
@@ -153,6 +185,12 @@ func main() {
|
||||
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 happens per resolver via IsAdminFromCtx / UserIDFromCtx,
|
||||
// so a new resolver is PUBLIC until it checks for itself.
|
||||
gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{
|
||||
Resolvers: &graph.Resolver{Store: &store},
|
||||
}))
|
||||
@@ -160,12 +198,20 @@ 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.
|
||||
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), func(c *gin.Context) {
|
||||
gqlSrv.ServeHTTP(c.Writer, c.Request)
|
||||
})
|
||||
@@ -180,11 +226,15 @@ func main() {
|
||||
c.JSON(200, gin.H{"message": "Hello World"})
|
||||
})
|
||||
|
||||
// Launch email sync scheduler
|
||||
// The scheduler runs until ctx is cancelled, which in practice only
|
||||
// happens if r.Run returns — there is no signal handling or graceful
|
||||
// shutdown, so the container is simply killed.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go store.EmailSync.StartScheduler(ctx)
|
||||
|
||||
port := os.Getenv("BACKEND_PORT")
|
||||
// Blocks forever; its error is not checked, so a failure to bind the port
|
||||
// exits main silently with status 0.
|
||||
r.Run(fmt.Sprintf(":%s", port))
|
||||
}
|
||||
|
||||
+85
-12
@@ -6,16 +6,42 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Package models holds the GORM entities, which are also the GraphQL object
|
||||
// types: gqlgen.yml maps each GraphQL type straight onto the struct here, so
|
||||
// graph/model/ only contains generated input and payload types. That means
|
||||
// these structs carry three sets of contracts at once — database columns,
|
||||
// JSON field names for the REST endpoints, and the shape resolvers return —
|
||||
// and renaming a field or changing a tag breaks at least one of them.
|
||||
//
|
||||
// Conventions across every model:
|
||||
// - There are no migration files; services.migrateDatabase runs AutoMigrate,
|
||||
// so a model must be listed there to get a table.
|
||||
// - A gorm.DeletedAt field means soft delete: Delete sets deleted_at, and
|
||||
// every subsequent query silently filters those rows out. Rows are never
|
||||
// actually removed, and a uniqueIndex still sees deleted rows, so a
|
||||
// soft-deleted username cannot be reused.
|
||||
// - IDs are uint in Go but Int in GraphQL, which is why nearly every type
|
||||
// has a hand-written ID resolver doing int(obj.ID).
|
||||
|
||||
// User is an account. There is no public sign-up: users are created by an
|
||||
// existing admin through the createUser mutation, or by the dev seeder.
|
||||
type User struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
Username string `gorm:"uniqueIndex" json:"username"`
|
||||
Password []byte `json:"-"`
|
||||
Admin bool `json:"admin"`
|
||||
// bcrypt hash, never the plaintext. `json:"-"` keeps it out of REST
|
||||
// responses, and gqlgen.yml marks the GraphQL password field
|
||||
// resolver:false so it is not exposed there either.
|
||||
Password []byte `json:"-"`
|
||||
// Admin gates almost every mutation. It is copied into the access token,
|
||||
// so a change here only takes effect on the user's next token refresh.
|
||||
Admin bool `json:"admin"`
|
||||
}
|
||||
|
||||
// Post is a blog entry. Author is loaded with Preload("Author") by the post
|
||||
// resolvers; without that preload it is nil rather than an error.
|
||||
type Post struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
@@ -27,16 +53,27 @@ type Post struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// Message is one chat message. The table is capped at 50 rows by the
|
||||
// WebSocket hub, which soft-deletes older ones on every insert.
|
||||
//
|
||||
// Two things to watch: Content is exposed as "text", not "content"; and
|
||||
// AuthorID is a per-process connection counter from the WebSocket hub, NOT a
|
||||
// User ID — chat is pseudonymous and the number is meaningless across
|
||||
// restarts.
|
||||
type Message struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
Content string `json:"text"`
|
||||
AuthorID uint `json:"authorId"`
|
||||
FileURL string `json:"fileUrl,omitempty"`
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
Content string `json:"text"`
|
||||
AuthorID uint `json:"authorId"`
|
||||
FileURL string `json:"fileUrl,omitempty"`
|
||||
// Private messages are visible only to admins; both the WebSocket
|
||||
// broadcast and the messages query filter on it.
|
||||
Private bool `gorm:"not null;default:false" json:"private"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
}
|
||||
|
||||
// Activity is a "currently doing" entry on the home page. Structurally
|
||||
// identical to Favorite but kept separate so the two lists can diverge.
|
||||
type Activity struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
@@ -47,6 +84,7 @@ type Activity struct {
|
||||
Link *string `json:"link"`
|
||||
}
|
||||
|
||||
// Favorite is a "currently enjoying" entry on the home page.
|
||||
type Favorite struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
@@ -57,6 +95,13 @@ type Favorite struct {
|
||||
Link *string `json:"link"`
|
||||
}
|
||||
|
||||
// Rowing is one rowing machine session, created by uploading a photo of the
|
||||
// display (see handlers.CreateRowing).
|
||||
//
|
||||
// Date is the photo's EXIF capture time and acts as the deduplication key —
|
||||
// it is not the row's creation time. Time is total seconds; Distance is
|
||||
// metres; TimePer500m is seconds and derived from the other two; Calories is
|
||||
// an estimate computed from distance, not read off the machine.
|
||||
type Rowing struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
@@ -68,6 +113,7 @@ type Rowing struct {
|
||||
Calories float64 `json:"calories"`
|
||||
}
|
||||
|
||||
// Bookmark is a link on the bookmarks page, grouped by Category.
|
||||
type Bookmark struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
@@ -78,6 +124,9 @@ type Bookmark struct {
|
||||
Link string `gorm:"not null" json:"link"`
|
||||
}
|
||||
|
||||
// JobAppReference is a reusable snippet for filling in job application forms
|
||||
// (a stock answer, a profile link, and so on), grouped by Category and
|
||||
// ordered within it by SortOrder.
|
||||
type JobAppReference struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
@@ -89,15 +138,31 @@ type JobAppReference struct {
|
||||
SortOrder int `gorm:"default:0" json:"sortOrder"`
|
||||
}
|
||||
|
||||
// ProcessedEmail records that the email pipeline has already looked at a
|
||||
// message, so it is never classified twice.
|
||||
//
|
||||
// Unlike every other model it has no DeletedAt and so is NOT soft deleted —
|
||||
// the dedup check must see every historical row. Its CreatedAt also drives
|
||||
// the next sync's time window, so the most recent row here is effectively the
|
||||
// pipeline's cursor. A row is written even when classification failed, with
|
||||
// Action "error", which means failures are never retried.
|
||||
type ProcessedEmail struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
GraphMessageID string `gorm:"uniqueIndex;not null" json:"graphMessageId"`
|
||||
Subject string `gorm:"not null" json:"subject"`
|
||||
Action string `gorm:"not null" json:"action"`
|
||||
JobAppID *uint `json:"jobAppId"`
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
// The provider's message id: Microsoft Graph's id on the Graph backend,
|
||||
// the RFC822 Message-ID header on IMAP. Unique, which is what makes the
|
||||
// dedup check safe against a concurrent sync.
|
||||
GraphMessageID string `gorm:"uniqueIndex;not null" json:"graphMessageId"`
|
||||
Subject string `gorm:"not null" json:"subject"`
|
||||
Action string `gorm:"not null" json:"action"`
|
||||
// The application this email created or updated, if any. A plain nullable
|
||||
// column, not a GORM association — nothing preloads it.
|
||||
JobAppID *uint `json:"jobAppId"`
|
||||
}
|
||||
|
||||
// Place is an entry on the places-to-go list. Creating or editing one needs
|
||||
// only a signed-in user, not an admin — the one exception to the
|
||||
// admin-writes-everything rule.
|
||||
type Place struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
@@ -113,6 +178,14 @@ type Place struct {
|
||||
Done bool `gorm:"default:false" json:"done"`
|
||||
}
|
||||
|
||||
// JobApplication is a tracked job application. Rows are created by hand
|
||||
// through GraphQL or automatically by the email pipeline.
|
||||
//
|
||||
// Status is a free-form string, but only the values ranked in
|
||||
// services.statusOrder ("applied", "screening", "assessment",
|
||||
// "interviewing", "offer", "rejected", "withdrawn") can be advanced
|
||||
// automatically; the pipeline matches an existing application on
|
||||
// (Company, JobTitle) compared case-insensitively.
|
||||
type JobApplication struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
|
||||
@@ -8,10 +8,16 @@ import (
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// Auth mints and verifies the HS256 JWTs that back the site's login. Tokens
|
||||
// are handed to the browser as HTTP-only cookies (see handlers.Store.Login);
|
||||
// there is no server-side session or token blacklist, so a token stays valid
|
||||
// until it expires even after logout.
|
||||
type Auth struct {
|
||||
Config *AuthConfig
|
||||
}
|
||||
|
||||
// AuthConfig carries the signing secret and cookie/token lifetimes. Domain is
|
||||
// the cookie domain; Endpoint is the backend's public base URL.
|
||||
type AuthConfig struct {
|
||||
Secret []byte
|
||||
Domain string
|
||||
@@ -20,17 +26,26 @@ type AuthConfig struct {
|
||||
Endpoint string
|
||||
}
|
||||
|
||||
// Tokens is a freshly minted access/refresh token pair, both already signed.
|
||||
type Tokens struct {
|
||||
AccessToken string
|
||||
RefreshToken string
|
||||
}
|
||||
|
||||
// InitAuth builds the Auth service from config.
|
||||
func InitAuth(config *AuthConfig) *Auth {
|
||||
auth := Auth{Config: config}
|
||||
|
||||
return &auth
|
||||
}
|
||||
|
||||
// GenerateJWT issues an access/refresh pair for user.
|
||||
//
|
||||
// The access token carries the authorisation data the API needs (id, admin)
|
||||
// so that most requests can be authorised without touching the database. The
|
||||
// refresh token deliberately carries only the id: admin status is re-read
|
||||
// from the database when refreshing, so revoking someone's admin flag takes
|
||||
// effect on their next refresh rather than only when they log in again.
|
||||
func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) {
|
||||
accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"username": user.Username,
|
||||
@@ -57,10 +72,20 @@ func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) {
|
||||
return &Tokens{AccessToken: accessTokenString, RefreshToken: refreshTokenString}, nil
|
||||
}
|
||||
|
||||
// keyFunc supplies the HMAC secret to the JWT parser. The token argument is
|
||||
// ignored because only one key is ever in use; VerifyJWT separately pins the
|
||||
// algorithm, which is what actually prevents the "alg: none"/algorithm
|
||||
// confusion attack.
|
||||
func (auth *Auth) keyFunc(_ *jwt.Token) (any, error) {
|
||||
return auth.Config.Secret, nil
|
||||
}
|
||||
|
||||
// VerifyJWT parses and validates a signed token, returning its claims.
|
||||
// Expiry is checked by the jwt library. Note the *jwt.MapClaims return: a
|
||||
// pointer to a map is unusual, but every caller in this codebase expects it,
|
||||
// so the type is part of the internal contract. Numeric claims come back as
|
||||
// float64 because that is what encoding/json produces, hence the
|
||||
// `(*claims)["id"].(float64)` conversions at the call sites.
|
||||
func (auth *Auth) VerifyJWT(tokenStr string) (*jwt.MapClaims, error) {
|
||||
token, err := jwt.Parse(tokenStr, auth.keyFunc, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
|
||||
if err != nil {
|
||||
|
||||
@@ -5,11 +5,20 @@ import (
|
||||
"github.com/anthropics/anthropic-sdk-go/option"
|
||||
)
|
||||
|
||||
// ClaudeConfig holds the Anthropic API credentials.
|
||||
type ClaudeConfig struct {
|
||||
APIKey string
|
||||
}
|
||||
|
||||
// InitClaude builds the shared Anthropic client. It is used in two places:
|
||||
// reading a rowing machine display from a photo (handlers.CreateRowing) and
|
||||
// classifying job-application emails (EmailSyncService.processEmail).
|
||||
//
|
||||
// No validation happens here: with an empty or wrong API key construction
|
||||
// still succeeds and the failure only surfaces on the first request.
|
||||
func InitClaude(config *ClaudeConfig) *anthropic.Client {
|
||||
// anthropic.NewClient returns a value, not a pointer, so take its address
|
||||
// to share one client across every caller.
|
||||
client := anthropic.NewClient(option.WithAPIKey(config.APIKey))
|
||||
return &client
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// SQLConfig holds the PostgreSQL connection parameters, all read from the
|
||||
// environment in main.
|
||||
type SQLConfig struct {
|
||||
User string
|
||||
Password string
|
||||
@@ -16,6 +18,9 @@ type SQLConfig struct {
|
||||
Port string
|
||||
}
|
||||
|
||||
// connectToPostgreSQL opens the GORM connection. sslmode=disable is safe
|
||||
// only because Postgres is reachable exclusively on the private Docker
|
||||
// network, never over the internet.
|
||||
func connectToPostgreSQL(config *SQLConfig) (*gorm.DB, error) {
|
||||
dsn := fmt.Sprintf(
|
||||
"user=%s password=%s dbname=%s host=%s port=%s sslmode=disable",
|
||||
@@ -30,6 +35,12 @@ func connectToPostgreSQL(config *SQLConfig) (*gorm.DB, error) {
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// migrateDatabase brings the schema up to date. This project has no
|
||||
// migration files: GORM's AutoMigrate is the only schema source, so it will
|
||||
// add tables, columns and indexes but never drop or rename anything. Removing
|
||||
// a field from a model therefore leaves the column behind, and a renamed
|
||||
// field appears as a brand-new column with no data. Any model added to
|
||||
// models.go must also be listed here or its table will never be created.
|
||||
func migrateDatabase(db *gorm.DB) error {
|
||||
err := db.AutoMigrate(
|
||||
&models.User{},
|
||||
@@ -51,6 +62,7 @@ func migrateDatabase(db *gorm.DB) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// InitDatabase connects to Postgres and runs the auto-migration.
|
||||
func InitDatabase(config *SQLConfig) (*gorm.DB, error) {
|
||||
db, err := connectToPostgreSQL(config)
|
||||
if err != nil {
|
||||
|
||||
@@ -15,6 +15,17 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// This file is a hand-rolled IMAP client, used as an alternative mail source
|
||||
// to Microsoft Graph. It exists because the Graph path needs an Azure app
|
||||
// registration and admin consent, while IMAP needs only an app password.
|
||||
//
|
||||
// It implements the bare minimum of RFC 3501 — LOGIN, SELECT, SEARCH, FETCH,
|
||||
// LOGOUT — by matching on string prefixes rather than parsing IMAP's grammar
|
||||
// properly. It works against Outlook and similar servers with the response
|
||||
// shapes seen in practice; it is not a general-purpose IMAP client.
|
||||
|
||||
// IMAPConfig holds the mailbox credentials. Password is an app password, not
|
||||
// an account password.
|
||||
type IMAPConfig struct {
|
||||
Host string
|
||||
Port string
|
||||
@@ -27,9 +38,15 @@ type IMAPConfig struct {
|
||||
type imapClient struct {
|
||||
conn net.Conn
|
||||
reader *bufio.Reader
|
||||
tag atomic.Int64
|
||||
// tag numbers the commands. IMAP allows several in flight at once
|
||||
// identified by tag; this client never does that, so the atomic is
|
||||
// belt-and-braces rather than load-bearing.
|
||||
tag atomic.Int64
|
||||
}
|
||||
|
||||
// imapDial opens an implicit-TLS IMAP connection (port 993 style, TLS from the
|
||||
// first byte — there is no STARTTLS support here) and consumes the server
|
||||
// greeting, which arrives unsolicited before any command.
|
||||
func imapDial(addr string) (*imapClient, error) {
|
||||
conn, err := tls.Dial("tcp", addr, nil)
|
||||
if err != nil {
|
||||
@@ -47,21 +64,31 @@ func imapDial(addr string) (*imapClient, error) {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Close drops the TCP connection. Callers normally send LOGOUT first.
|
||||
func (c *imapClient) Close() error {
|
||||
return c.conn.Close()
|
||||
}
|
||||
|
||||
// nextTag returns the next command tag, e.g. "A0001". The width is cosmetic:
|
||||
// past 9999 the tags simply get longer, and they stay unique.
|
||||
func (c *imapClient) nextTag() string {
|
||||
return fmt.Sprintf("A%04d", c.tag.Add(1))
|
||||
}
|
||||
|
||||
// readLine reads one CRLF-terminated protocol line with the terminator
|
||||
// stripped. There is no read deadline anywhere in this client, so an
|
||||
// unresponsive server can block a sync until the TCP connection itself fails.
|
||||
func (c *imapClient) readLine() (string, error) {
|
||||
line, err := c.reader.ReadString('\n')
|
||||
return strings.TrimRight(line, "\r\n"), err
|
||||
}
|
||||
|
||||
// sendCommand sends a tagged command and reads lines until the tagged response.
|
||||
// Returns all untagged response lines and the final tagged status line.
|
||||
// sendCommand sends a tagged command and reads lines until the line beginning
|
||||
// with that tag, which is the server's final status for the command.
|
||||
// Everything before it is an untagged ("* ...") response and is returned.
|
||||
//
|
||||
// This must not be used for FETCH: it reads line by line and would mistake the
|
||||
// bytes of a literal for protocol lines. Use sendFetch instead.
|
||||
func (c *imapClient) sendCommand(cmd string) (untagged []string, status string, err error) {
|
||||
tag := c.nextTag()
|
||||
_, err = fmt.Fprintf(c.conn, "%s %s\r\n", tag, cmd)
|
||||
@@ -87,7 +114,8 @@ func (c *imapClient) sendCommandOK(cmd string) ([]string, error) {
|
||||
if err != nil {
|
||||
return untagged, err
|
||||
}
|
||||
// Status line is like: A0001 OK ... or A0001 NO ...
|
||||
// Status line is "<tag> OK ..." on success, "<tag> NO ..." or
|
||||
// "<tag> BAD ..." otherwise; only the second field matters.
|
||||
parts := strings.SplitN(status, " ", 3)
|
||||
if len(parts) < 2 || parts[1] != "OK" {
|
||||
return untagged, fmt.Errorf("command %q failed: %s", cmd, status)
|
||||
@@ -95,7 +123,10 @@ func (c *imapClient) sendCommandOK(cmd string) ([]string, error) {
|
||||
return untagged, nil
|
||||
}
|
||||
|
||||
// fetchLiteral reads an IMAP literal {N}\r\n followed by N bytes.
|
||||
// readLiteral reads exactly size bytes of an IMAP literal, i.e. the payload
|
||||
// announced by a trailing "{N}" on the preceding line. It must read by byte
|
||||
// count rather than by line because the payload is arbitrary binary data that
|
||||
// will itself contain CRLFs.
|
||||
func (c *imapClient) readLiteral(size int) (string, error) {
|
||||
buf := make([]byte, size)
|
||||
_, err := io.ReadFull(c.reader, buf)
|
||||
@@ -105,8 +136,15 @@ func (c *imapClient) readLiteral(size int) (string, error) {
|
||||
return string(buf), nil
|
||||
}
|
||||
|
||||
// sendFetch sends a FETCH command and collects the full response including literals.
|
||||
// Returns raw response lines (with literals inlined after their header lines).
|
||||
// sendFetch sends a FETCH and collects its response, handling literals.
|
||||
//
|
||||
// The returned slice interleaves protocol lines with literal payloads: when a
|
||||
// line ends in "{N}" the next entry is the N bytes that followed it. The
|
||||
// caller (fetchEmailsIMAP) relies on that pairing.
|
||||
//
|
||||
// The literal is detected with LastIndex("{") plus a "}" suffix rather than a
|
||||
// real parse, so a line whose text merely ends in braces could be misread —
|
||||
// tolerable because only FETCH responses reach this code.
|
||||
func (c *imapClient) sendFetch(cmd string) ([]string, error) {
|
||||
tag := c.nextTag()
|
||||
_, err := fmt.Fprintf(c.conn, "%s %s\r\n", tag, cmd)
|
||||
@@ -158,7 +196,11 @@ func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, err
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
// Quote the password to handle special characters
|
||||
// %q wraps the password in double quotes and backslash-escapes any quote
|
||||
// or backslash inside it, which happens to be exactly IMAP's quoted-string
|
||||
// syntax. The username is NOT quoted: an address needs no escaping.
|
||||
// Note this sends the password in a LOGIN command, so it is only safe
|
||||
// because the connection is TLS from the first byte.
|
||||
quotedPass := fmt.Sprintf("%q", s.Config.IMAP.Password)
|
||||
if _, err := c.sendCommandOK(fmt.Sprintf("LOGIN %s %s", s.Config.IMAP.Email, quotedPass)); err != nil {
|
||||
return nil, fmt.Errorf("IMAP login: %w", err)
|
||||
@@ -168,14 +210,19 @@ func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, err
|
||||
return nil, fmt.Errorf("IMAP select INBOX: %w", err)
|
||||
}
|
||||
|
||||
// SEARCH SINCE uses date only (no time), per IMAP spec
|
||||
// SEARCH SINCE has day granularity only — the time of day is not
|
||||
// expressible — so this always over-fetches back to midnight of `since`.
|
||||
// Harmless: SyncEmails deduplicates by message id. The date must be in
|
||||
// IMAP's dd-Mon-yyyy form, hence this exact layout string.
|
||||
dateStr := since.UTC().Format("02-Jan-2006")
|
||||
untagged, err := c.sendCommandOK(fmt.Sprintf("SEARCH SINCE %s", dateStr))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("IMAP search: %w", err)
|
||||
}
|
||||
|
||||
// Parse sequence numbers from "* SEARCH 1 2 3 ..."
|
||||
// Parse sequence numbers from "* SEARCH 1 2 3 ...". parts[2:] skips the
|
||||
// "*" and "SEARCH" tokens; a bare "* SEARCH" (no matches) has len 2 and
|
||||
// is skipped by the length test.
|
||||
var seqNums []string
|
||||
for _, line := range untagged {
|
||||
if strings.HasPrefix(line, "* SEARCH") {
|
||||
@@ -194,13 +241,18 @@ func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, err
|
||||
|
||||
log.Printf("[EmailSync/IMAP] Found %d messages since %s", len(seqNums), dateStr)
|
||||
|
||||
// Every matching message is fetched in one command with a comma-separated
|
||||
// sequence set, and each full body is held in memory. A mailbox with a
|
||||
// very busy day could make this large — there is no batching.
|
||||
seqSet := strings.Join(seqNums, ",")
|
||||
fetchLines, err := c.sendFetch(fmt.Sprintf("FETCH %s (BODY[])", seqSet))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("IMAP fetch: %w", err)
|
||||
}
|
||||
|
||||
// Parse fetched messages - literals contain the raw RFC822 message
|
||||
// Pair each "... BODY[] {N}" header line with the literal that sendFetch
|
||||
// stored immediately after it. A message that fails to parse is logged and
|
||||
// skipped rather than failing the whole sync.
|
||||
var messages []graphMessage
|
||||
for i := 0; i < len(fetchLines); i++ {
|
||||
line := fetchLines[i]
|
||||
@@ -208,7 +260,11 @@ func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, err
|
||||
if strings.Contains(line, "BODY[]") && strings.HasSuffix(line, "}") {
|
||||
if i+1 < len(fetchLines) {
|
||||
raw := fetchLines[i+1]
|
||||
i++ // skip the literal
|
||||
// Advance past the literal so its contents are never
|
||||
// examined as a protocol line. Note this is a C-style loop
|
||||
// precisely so i can be advanced here; a range loop could
|
||||
// not do it.
|
||||
i++
|
||||
gm, err := parseRawEmail(raw)
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync/IMAP] Error parsing email: %v", err)
|
||||
@@ -219,11 +275,16 @@ func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, err
|
||||
}
|
||||
}
|
||||
|
||||
// LOGOUT errors are ignored: the emails are already in hand and the
|
||||
// deferred Close will drop the connection regardless.
|
||||
c.sendCommand("LOGOUT")
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// parseRawEmail parses an RFC822 email into a graphMessage.
|
||||
// parseRawEmail parses a raw RFC822 message into the same graphMessage struct
|
||||
// the Graph API path produces, so everything downstream is source-agnostic.
|
||||
// An unparseable Date falls back to now, and a missing From leaves both name
|
||||
// and address empty rather than failing.
|
||||
func parseRawEmail(raw string) (graphMessage, error) {
|
||||
msg, err := mail.ReadMessage(strings.NewReader(raw))
|
||||
if err != nil {
|
||||
@@ -266,7 +327,16 @@ func parseRawEmail(raw string) (graphMessage, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// extractTextBody pulls the text/plain or text/html content from a message body.
|
||||
// extractTextBody pulls readable content out of a message body, preferring
|
||||
// text/plain and falling back to text/html.
|
||||
//
|
||||
// It recurses into nested multipart parts by re-wrapping the part's bytes in a
|
||||
// synthetic mail.Header carrying just its Content-Type — a shortcut that works
|
||||
// because this function only ever reads Content-Type.
|
||||
//
|
||||
// Quoted-printable and base64 transfer encodings are NOT decoded, so a
|
||||
// base64-encoded body reaches Claude as base64. Read errors on a part are
|
||||
// swallowed and the part is skipped.
|
||||
func extractTextBody(header mail.Header, body io.Reader) string {
|
||||
contentType := header.Get("Content-Type")
|
||||
if contentType == "" {
|
||||
@@ -326,7 +396,9 @@ func extractTextBody(header mail.Header, body io.Reader) string {
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// decodeHeader decodes RFC 2047 encoded header values.
|
||||
// decodeHeader decodes RFC 2047 encoded-words (the "=?UTF-8?Q?...?=" form
|
||||
// used for non-ASCII subjects), returning the input unchanged if it is not
|
||||
// encoded or cannot be decoded.
|
||||
func decodeHeader(s string) string {
|
||||
dec := new(mime.WordDecoder)
|
||||
decoded, err := dec.DecodeHeader(s)
|
||||
|
||||
+137
-11
@@ -21,8 +21,18 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// This file is the job-application email pipeline. On a timer it fetches
|
||||
// recent mail (via Microsoft Graph or plain IMAP), keeps the ones that look
|
||||
// recruitment-related, asks Claude to turn each into structured data, and
|
||||
// creates or advances a models.JobApplication row. Every email it has looked
|
||||
// at is recorded as a models.ProcessedEmail so it is never handled twice.
|
||||
|
||||
// MSGRAPH_TOKEN_JSON_PATH lives in a Docker volume so the OAuth refresh token
|
||||
// survives restarts, exactly like the Spotify token.
|
||||
const MSGRAPH_TOKEN_JSON_PATH = "/backend/token/msgraph_token.json"
|
||||
|
||||
// EmailSyncConfig configures the pipeline. Backend picks the mail source;
|
||||
// anything other than "graph" or "imap" leaves the service permanently idle.
|
||||
type EmailSyncConfig struct {
|
||||
Backend string // "graph" or "imap"
|
||||
ClientID string
|
||||
@@ -34,22 +44,38 @@ type EmailSyncConfig struct {
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
// EmailSyncService owns the sync pipeline.
|
||||
type EmailSyncService struct {
|
||||
Config *EmailSyncConfig
|
||||
OAuthConfig *oauth2.Config
|
||||
Config *EmailSyncConfig
|
||||
OAuthConfig *oauth2.Config
|
||||
// HTTPClient doubles as the readiness flag: nil means "not configured or
|
||||
// not yet authenticated", and both the scheduler and the manual-trigger
|
||||
// handler refuse to run while it is nil. On the Graph backend it is a
|
||||
// real token-injecting client; on the IMAP backend it is set to
|
||||
// http.DefaultClient purely so this check passes (IMAP never uses it).
|
||||
HTTPClient *http.Client
|
||||
DB *gorm.DB
|
||||
ClaudeClient *anthropic.Client
|
||||
mu sync.Mutex
|
||||
// mu is used with TryLock, not Lock: it makes a sync a no-op while
|
||||
// another one is running rather than queueing behind it, so the manual
|
||||
// admin trigger cannot pile up on top of the scheduled run.
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// Microsoft Graph API response types
|
||||
|
||||
// Microsoft Graph API response types. The IMAP backend parses raw RFC822
|
||||
// messages into these same structs (see parseRawEmail) so that everything
|
||||
// downstream of fetchEmails is backend-agnostic.
|
||||
|
||||
// graphMessagesResponse is one page of /me/messages; NextLink is Graph's
|
||||
// cursor for the next page and is empty on the last one.
|
||||
type graphMessagesResponse struct {
|
||||
Value []graphMessage `json:"value"`
|
||||
NextLink string `json:"@odata.nextLink"`
|
||||
}
|
||||
|
||||
// graphMessage is a single email.
|
||||
type graphMessage struct {
|
||||
ID string `json:"id"`
|
||||
Subject string `json:"subject"`
|
||||
@@ -59,15 +85,18 @@ type graphMessage struct {
|
||||
BodyPreview string `json:"bodyPreview"`
|
||||
}
|
||||
|
||||
// graphFrom wraps the sender, which Graph nests one level deep.
|
||||
type graphFrom struct {
|
||||
EmailAddress graphEmailAddress `json:"emailAddress"`
|
||||
}
|
||||
|
||||
// graphEmailAddress is a display name plus address.
|
||||
type graphEmailAddress struct {
|
||||
Name string `json:"name"`
|
||||
Address string `json:"address"`
|
||||
}
|
||||
|
||||
// graphBody is the message body; ContentType is "html" or "text".
|
||||
type graphBody struct {
|
||||
ContentType string `json:"contentType"`
|
||||
Content string `json:"content"`
|
||||
@@ -75,6 +104,9 @@ type graphBody struct {
|
||||
|
||||
// Claude response type
|
||||
|
||||
// EmailAnalysis is the JSON contract Claude is asked to return; the keys here
|
||||
// must stay in step with emailClassificationPrompt at the bottom of this file.
|
||||
// Pointer fields are the ones Claude is allowed to answer null for.
|
||||
type EmailAnalysis struct {
|
||||
IsJobEmail bool `json:"isJobEmail"`
|
||||
Action string `json:"action"`
|
||||
@@ -89,6 +121,12 @@ type EmailAnalysis struct {
|
||||
|
||||
// Email filtering config
|
||||
|
||||
// Cheap pre-filter, applied before any Claude call so that the bulk of a
|
||||
// mailbox never costs an API request. It is intentionally over-inclusive:
|
||||
// false positives are cheap (Claude rejects them), false negatives are not
|
||||
// (the email is never looked at again once its window has passed).
|
||||
|
||||
// subjectKeywords match case-insensitively anywhere in the subject line.
|
||||
var subjectKeywords = []string{
|
||||
"application", "interview", "offer", "rejected", "assessment",
|
||||
"applied", "candidate", "position", "role", "hiring",
|
||||
@@ -96,6 +134,8 @@ var subjectKeywords = []string{
|
||||
"next steps", "coding challenge", "take-home",
|
||||
}
|
||||
|
||||
// senderDomains are applicant-tracking systems; mail from any of them is
|
||||
// considered job-related whatever the subject says.
|
||||
var senderDomains = []string{
|
||||
"greenhouse.io", "lever.co", "workday.com", "myworkday.com",
|
||||
"ashbyhq.com", "smartrecruiters.com", "icims.com",
|
||||
@@ -105,6 +145,11 @@ var senderDomains = []string{
|
||||
|
||||
// Status progression order
|
||||
|
||||
// statusOrder ranks the application lifecycle so updates can only move an
|
||||
// application forwards (see updateJobApplication). A status missing from this
|
||||
// map is treated as unknown and never applied. Note that "rejected" and
|
||||
// "withdrawn" sit at the top, so once an application reaches them nothing can
|
||||
// move it back.
|
||||
var statusOrder = map[string]int{
|
||||
"applied": 0,
|
||||
"screening": 1,
|
||||
@@ -117,6 +162,9 @@ var statusOrder = map[string]int{
|
||||
|
||||
// Token persistence
|
||||
|
||||
// SaveMSGraphToken persists an OAuth token to disk with 0600 permissions.
|
||||
// Like the Spotify equivalent it copies into a local struct so the on-disk
|
||||
// shape does not depend on the oauth2 package's own JSON tags.
|
||||
func SaveMSGraphToken(path string, tok *oauth2.Token) error {
|
||||
data := struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
@@ -142,6 +190,8 @@ func SaveMSGraphToken(path string, tok *oauth2.Token) error {
|
||||
return os.WriteFile(path, jsonBytes, 0600)
|
||||
}
|
||||
|
||||
// LoadMSGraphToken reads a token written by SaveMSGraphToken. A missing file
|
||||
// is reported as an error and means "not yet authenticated".
|
||||
func LoadMSGraphToken(path string) (*oauth2.Token, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
@@ -174,6 +224,18 @@ type persistingTokenSource struct {
|
||||
lastToken *oauth2.Token
|
||||
}
|
||||
|
||||
// Token returns a valid token, refreshing through the wrapped source when
|
||||
// needed and writing any new token back to disk.
|
||||
//
|
||||
// Without this wrapper the oauth2 client would refresh happily in memory but
|
||||
// the file on disk would keep the original refresh token; Microsoft rotates
|
||||
// refresh tokens, so after the original expired the service would have to be
|
||||
// re-authorised by hand on the next restart.
|
||||
//
|
||||
// There is no mutex here even though oauth2's client may call Token from
|
||||
// several goroutines. In practice syncs are serialised by EmailSyncService.mu
|
||||
// so concurrent calls do not arise; the worst case if they ever did is a
|
||||
// duplicate write of the same token.
|
||||
func (p *persistingTokenSource) Token() (*oauth2.Token, error) {
|
||||
tok, err := p.base.Token()
|
||||
if err != nil {
|
||||
@@ -189,6 +251,12 @@ func (p *persistingTokenSource) Token() (*oauth2.Token, error) {
|
||||
return tok, nil
|
||||
}
|
||||
|
||||
// InitEmailSync builds the service and, for the Graph backend, restores a
|
||||
// saved OAuth session. It never fails: a misconfigured or unauthenticated
|
||||
// service is returned with a nil HTTPClient, which leaves the pipeline idle
|
||||
// while the rest of the backend starts normally. For Graph, the authorisation
|
||||
// URL is printed to the container log for a one-off manual sign-in that
|
||||
// lands on GET /email/callback.
|
||||
func InitEmailSync(config *EmailSyncConfig, db *gorm.DB, claudeClient *anthropic.Client) *EmailSyncService {
|
||||
svc := &EmailSyncService{
|
||||
Config: config,
|
||||
@@ -264,7 +332,13 @@ func (s *EmailSyncService) CompleteAuth(ctx context.Context, code string) error
|
||||
return nil
|
||||
}
|
||||
|
||||
// StartScheduler runs SyncEmails on a recurring interval.
|
||||
// StartScheduler runs SyncEmails immediately and then on every tick until ctx
|
||||
// is cancelled. It is meant to be run in its own goroutine and returns
|
||||
// straight away when the service is disabled or unauthenticated.
|
||||
//
|
||||
// Because readiness is only checked once here, authenticating later via
|
||||
// /email/callback does NOT start the scheduler; the backend has to be
|
||||
// restarted, or syncs triggered by hand through POST /email/sync.
|
||||
func (s *EmailSyncService) StartScheduler(ctx context.Context) {
|
||||
if !s.Config.Enabled {
|
||||
log.Println("[EmailSync] Disabled, skipping scheduler")
|
||||
@@ -300,11 +374,17 @@ func (s *EmailSyncService) StartScheduler(ctx context.Context) {
|
||||
|
||||
// SyncEmails is the main pipeline: fetch, filter, dedup, classify, create/update.
|
||||
func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
// TryLock, so a manual trigger during a scheduled run is rejected
|
||||
// immediately instead of blocking a request for minutes.
|
||||
if !s.mu.TryLock() {
|
||||
return fmt.Errorf("sync already in progress")
|
||||
}
|
||||
defer s.mu.Unlock()
|
||||
|
||||
// Registered after the unlock defer, therefore it runs BEFORE it: the
|
||||
// panic is absorbed here and the mutex is still released afterwards.
|
||||
// A recovered panic makes SyncEmails return nil, so the caller sees a
|
||||
// successful sync — the log line is the only evidence.
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Printf("[EmailSync] PANIC recovered: %v", r)
|
||||
@@ -313,7 +393,13 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
|
||||
log.Println("[EmailSync] Starting sync...")
|
||||
|
||||
// Determine the time window: use the most recent ProcessedEmail timestamp, or default to 24h ago
|
||||
// Window start = when the last email was *processed*, not when it was
|
||||
// received. Those differ by up to one sync interval, which is deliberate:
|
||||
// it overlaps the windows so nothing that arrived mid-sync is missed. The
|
||||
// overlap re-fetches a few emails, and the ProcessedEmail dedup below is
|
||||
// what stops them being handled twice. On a cold database (no processed
|
||||
// emails at all) it falls back to the last 24 hours, so the pipeline
|
||||
// never tries to ingest an entire mailbox.
|
||||
since := time.Now().Add(-24 * time.Hour)
|
||||
var latest models.ProcessedEmail
|
||||
if err := s.DB.Order("created_at DESC").First(&latest).Error; err == nil {
|
||||
@@ -342,7 +428,10 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
continue
|
||||
}
|
||||
|
||||
// Process this email
|
||||
// A failed email is still recorded (with action "error") so the next
|
||||
// sync skips it rather than retrying — and, importantly, so it does
|
||||
// not hold the window open. The trade-off is that a transient Claude
|
||||
// outage permanently drops those emails.
|
||||
action, jobAppID, processErr := s.processEmail(ctx, email)
|
||||
if processErr != nil {
|
||||
log.Printf("[EmailSync] Error processing email %q: %v", email.Subject, processErr)
|
||||
@@ -379,7 +468,8 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// fetchEmails retrieves emails since the given time using the configured backend.
|
||||
// fetchEmails retrieves emails since the given time using the configured
|
||||
// backend, normalising both into []graphMessage.
|
||||
func (s *EmailSyncService) fetchEmails(ctx context.Context, since time.Time) ([]graphMessage, error) {
|
||||
if s.Config.Backend == "imap" {
|
||||
return s.fetchEmailsIMAP(since)
|
||||
@@ -399,6 +489,8 @@ func (s *EmailSyncService) fetchEmailsGraph(ctx context.Context, since time.Time
|
||||
"$orderby": {"receivedDateTime asc"},
|
||||
}
|
||||
|
||||
// Graph paginates with @odata.nextLink, which already carries every query
|
||||
// parameter, so the loop below only builds this first URL by hand.
|
||||
nextURL := fmt.Sprintf("https://graph.microsoft.com/v1.0/me/messages?%s", params.Encode())
|
||||
|
||||
for nextURL != "" {
|
||||
@@ -415,6 +507,8 @@ func (s *EmailSyncService) fetchEmailsGraph(ctx context.Context, since time.Time
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
|
||||
// Status is checked before the read error so that a non-200 reports
|
||||
// Graph's own error body rather than a generic read failure.
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("Graph API returned %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
@@ -446,6 +540,9 @@ func (s *EmailSyncService) filterEmails(emails []graphMessage) []graphMessage {
|
||||
return matched
|
||||
}
|
||||
|
||||
// matchesFilter reports whether an email looks job-related on subject or
|
||||
// sender alone. See subjectKeywords for why this errs towards including too
|
||||
// much.
|
||||
func (s *EmailSyncService) matchesFilter(email graphMessage) bool {
|
||||
subjectLower := strings.ToLower(email.Subject)
|
||||
for _, kw := range subjectKeywords {
|
||||
@@ -498,6 +595,10 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage)
|
||||
return "", nil, fmt.Errorf("empty response from Claude")
|
||||
}
|
||||
|
||||
// Only the first content block is read, and the prompt asks for bare JSON,
|
||||
// but models still wrap output in a markdown fence often enough that it is
|
||||
// stripped defensively here. The two TrimPrefix calls are ordered so that
|
||||
// "```json" is removed first and a plain "```" otherwise.
|
||||
raw := message.Content[0].Text
|
||||
raw = strings.TrimSpace(raw)
|
||||
raw = strings.TrimPrefix(raw, "```json")
|
||||
@@ -518,7 +619,11 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage)
|
||||
return "skipped", nil, nil
|
||||
}
|
||||
|
||||
// Try to find an existing job application
|
||||
// Applications are identified by (company, job title) compared
|
||||
// case-insensitively — there is no external id to match on. Claude
|
||||
// wording the same role slightly differently therefore creates a second
|
||||
// application rather than updating the first. The most recent match wins
|
||||
// when there are several.
|
||||
var existing models.JobApplication
|
||||
found := s.DB.Where("LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)",
|
||||
analysis.Company, analysis.JobTitle).
|
||||
@@ -537,6 +642,7 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage)
|
||||
return "skipped", &existing.ID, nil
|
||||
}
|
||||
|
||||
// createJobApplication inserts a new application from Claude's analysis.
|
||||
func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string, *uint, error) {
|
||||
app := models.JobApplication{
|
||||
Company: analysis.Company,
|
||||
@@ -547,6 +653,8 @@ func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string
|
||||
Notes: analysis.Notes,
|
||||
}
|
||||
|
||||
// The prompt asks for YYYY-MM-DD but full RFC3339 comes back often enough
|
||||
// to be worth trying first; an unparseable date is dropped silently.
|
||||
if analysis.AppliedAt != nil {
|
||||
if t, err := time.Parse(time.RFC3339, *analysis.AppliedAt); err == nil {
|
||||
app.AppliedAt = &t
|
||||
@@ -567,6 +675,10 @@ func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string
|
||||
return "created", &app.ID, nil
|
||||
}
|
||||
|
||||
// updateJobApplication advances an existing application's status, but only
|
||||
// ever forwards through statusOrder. Emails commonly arrive out of order (a
|
||||
// delayed "thanks for applying" after an interview invite), and this is what
|
||||
// stops a stale email dragging an application backwards.
|
||||
func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication, analysis *EmailAnalysis) (string, *uint, error) {
|
||||
newOrder, newExists := statusOrder[analysis.Status]
|
||||
currentOrder, currentExists := statusOrder[existing.Status]
|
||||
@@ -596,7 +708,13 @@ func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication,
|
||||
return "updated", &existing.ID, nil
|
||||
}
|
||||
|
||||
// cleanEmailBody strips HTML and truncates the email body for Claude.
|
||||
// cleanEmailBody reduces an email body to plain-ish text before it is sent to
|
||||
// Claude, cutting token cost and noise.
|
||||
//
|
||||
// The HTML handling is a regex tag-strip, not a parser: fine for extracting
|
||||
// prose, but it would mangle inline <script>/<style> content and mis-handle
|
||||
// tags inside attribute values. That is acceptable because the output is only
|
||||
// ever read by a language model, never rendered.
|
||||
func cleanEmailBody(content string, contentType string) string {
|
||||
text := content
|
||||
|
||||
@@ -625,7 +743,9 @@ func cleanEmailBody(content string, contentType string) string {
|
||||
text = nlRegex.ReplaceAllString(text, "\n\n")
|
||||
text = strings.TrimSpace(text)
|
||||
|
||||
// Remove common signatures
|
||||
// Cut everything from the first signature marker onwards. The idx > 0
|
||||
// test (not >= 0) means a body that begins with a marker is left alone,
|
||||
// which avoids blanking the whole message.
|
||||
sigPatterns := []string{
|
||||
"\n-- \n",
|
||||
"\nSent from my iPhone",
|
||||
@@ -649,7 +769,8 @@ func cleanEmailBody(content string, contentType string) string {
|
||||
}
|
||||
text = strings.Join(cleaned, "\n")
|
||||
|
||||
// Truncate to ~4000 characters
|
||||
// Cap the prompt size. This slices by bytes, so a cut can land mid-rune
|
||||
// and leave an invalid UTF-8 tail; harmless for a model prompt.
|
||||
if len(text) > 4000 {
|
||||
text = text[:4000]
|
||||
}
|
||||
@@ -657,6 +778,8 @@ func cleanEmailBody(content string, contentType string) string {
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
|
||||
// truncate caps a string at maxLen bytes (not runes) before it is stored in
|
||||
// ProcessedEmail.Subject.
|
||||
func truncate(s string, maxLen int) string {
|
||||
if len(s) <= maxLen {
|
||||
return s
|
||||
@@ -664,6 +787,9 @@ func truncate(s string, maxLen int) string {
|
||||
return s[:maxLen]
|
||||
}
|
||||
|
||||
// emailClassificationPrompt must stay in sync with the EmailAnalysis struct:
|
||||
// every key it names is a field there, and the status values it lists are the
|
||||
// keys of statusOrder.
|
||||
const emailClassificationPrompt = `You are an email classifier for job applications. You will receive the subject line, sender, and body of an email. Determine if this email is related to a job application, and if so, extract structured data.
|
||||
|
||||
Return ONLY a JSON object with these exact keys:
|
||||
|
||||
@@ -8,23 +8,35 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// This file talks to the self-hosted Gitea instance over the private Docker
|
||||
// network to surface "what did Adam push most recently" on the home page.
|
||||
// The response is cached by the caller (handlers.Store, 1 minute TTL).
|
||||
|
||||
// GiteaFeedCommit is one commit inside a push event's Content payload.
|
||||
// The capitalised JSON keys are Gitea's, not a typo.
|
||||
type GiteaFeedCommit struct {
|
||||
Message string `json:"Message"`
|
||||
}
|
||||
|
||||
// GiteaFeedContent is the shape of the JSON *string* stored in
|
||||
// GiteaFeedResponse.Content for push events; see ParseCommitMessage.
|
||||
type GiteaFeedContent struct {
|
||||
Commits []GiteaFeedCommit `json:"Commits"`
|
||||
}
|
||||
|
||||
// GiteaFeedUser is the acting user on a feed entry.
|
||||
type GiteaFeedUser struct {
|
||||
AvatarURL string `json:"avatar_url"`
|
||||
}
|
||||
|
||||
// GiteaFeedRepo is the repository a feed entry belongs to.
|
||||
type GiteaFeedRepo struct {
|
||||
FullName string `json:"full_name"`
|
||||
HTMLURL string `json:"html_url"`
|
||||
}
|
||||
|
||||
// GiteaFeedResponse is a single Gitea activity feed entry. Only the fields
|
||||
// the front end renders are declared; the rest of the payload is discarded.
|
||||
type GiteaFeedResponse struct {
|
||||
ActUser GiteaFeedUser `json:"act_user"`
|
||||
Repo GiteaFeedRepo `json:"repo"`
|
||||
@@ -33,6 +45,13 @@ type GiteaFeedResponse struct {
|
||||
Created time.Time `json:"created"`
|
||||
}
|
||||
|
||||
// FetchLatestFeed returns the single most recent public activity entry for
|
||||
// user "adamf", or (nil, nil) when the feed is empty — callers must handle
|
||||
// that nil-without-error case.
|
||||
//
|
||||
// The username is hard-coded and the call is plain HTTP with no token: this
|
||||
// only ever reaches the Gitea container over the internal Docker network,
|
||||
// where the public feed needs no authentication.
|
||||
func FetchLatestFeed(host, port string) (*GiteaFeedResponse, error) {
|
||||
url := fmt.Sprintf("http://%s:%s/api/v1/users/adamf/activities/feeds?limit=1", host, port)
|
||||
|
||||
@@ -60,6 +79,11 @@ func FetchLatestFeed(host, port string) (*GiteaFeedResponse, error) {
|
||||
return &items[0], nil
|
||||
}
|
||||
|
||||
// ParseCommitMessage pulls the first commit message out of a feed entry's
|
||||
// Content field, which Gitea delivers as JSON encoded inside a JSON string
|
||||
// (so it needs a second Unmarshal). Non-push events have Content in a
|
||||
// different shape entirely, so any parse failure is intentionally swallowed
|
||||
// and reported as "no commit message".
|
||||
func ParseCommitMessage(content string) string {
|
||||
var c GiteaFeedContent
|
||||
if err := json.Unmarshal([]byte(content), &c); err != nil {
|
||||
|
||||
@@ -7,21 +7,35 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// NotesConfig points at the directory of markdown notes mounted into the
|
||||
// container.
|
||||
type NotesConfig struct {
|
||||
Dir string
|
||||
}
|
||||
|
||||
// Notes serves files out of a single directory, guarding against path
|
||||
// traversal. It is admin-only at the route level (see main.go).
|
||||
type Notes struct {
|
||||
Config NotesConfig
|
||||
}
|
||||
|
||||
// InitNotes builds the Notes service.
|
||||
func InitNotes(config *NotesConfig) *Notes {
|
||||
return &Notes{
|
||||
Config: *config,
|
||||
}
|
||||
}
|
||||
|
||||
// ParsePath resolves a user-supplied request path to an absolute path inside
|
||||
// the notes directory, or returns an error if it would escape.
|
||||
//
|
||||
// The traversal guard is the prefix check at the end. filepath.Join already
|
||||
// cleans "..", but the separator is appended to baseDir before comparing so
|
||||
// that a sibling directory whose name merely starts with the same characters
|
||||
// (e.g. /backend/notes-private next to /backend/notes) cannot pass the check.
|
||||
func (notes *Notes) ParsePath(path string) (string, error) {
|
||||
// The route is /notes/*path, so a bare /notes/ arrives as "" or "/";
|
||||
// treat both as a request for the wiki index.
|
||||
if path == "" || path == "/" {
|
||||
path = "Index.md"
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
// Package services holds the backend's stateful collaborators: the database
|
||||
// handle, JWT signing, the chat WebSocket hub, third-party API clients
|
||||
// (Spotify, Steam, Gitea, Claude) and the email-sync pipeline. Handlers and
|
||||
// GraphQL resolvers reach them through handlers.Store.
|
||||
package services
|
||||
|
||||
import (
|
||||
@@ -5,13 +9,24 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// RateLimiter is an in-memory sliding-window limiter keyed by an arbitrary
|
||||
// string (in practice the client IP). It is process-local: restarting the
|
||||
// backend clears every window, and a multi-replica deployment would limit
|
||||
// per replica rather than globally. Nginx applies its own rate limits in
|
||||
// front of this, so this layer is a second line of defence, not the only one.
|
||||
type RateLimiter struct {
|
||||
mu sync.Mutex
|
||||
mu sync.Mutex
|
||||
// attempts holds the timestamps of recent allowed attempts per key.
|
||||
// Keys are never evicted, so memory grows with the number of distinct
|
||||
// client IPs seen since start-up; acceptable for a personal site, but
|
||||
// worth knowing before reusing this elsewhere.
|
||||
attempts map[string][]time.Time
|
||||
max int
|
||||
window time.Duration
|
||||
}
|
||||
|
||||
// NewRateLimiter returns a limiter allowing at most max calls to Allow per
|
||||
// key within any window-length period.
|
||||
func NewRateLimiter(max int, window time.Duration) *RateLimiter {
|
||||
return &RateLimiter{
|
||||
attempts: make(map[string][]time.Time),
|
||||
@@ -20,6 +35,9 @@ func NewRateLimiter(max int, window time.Duration) *RateLimiter {
|
||||
}
|
||||
}
|
||||
|
||||
// Allow records an attempt for key and reports whether it is within the
|
||||
// limit. A rejected attempt is deliberately NOT recorded, so a caller that
|
||||
// keeps hammering does not extend its own lockout indefinitely.
|
||||
func (rl *RateLimiter) Allow(key string) bool {
|
||||
rl.mu.Lock()
|
||||
defer rl.mu.Unlock()
|
||||
@@ -27,7 +45,11 @@ func (rl *RateLimiter) Allow(key string) bool {
|
||||
now := time.Now()
|
||||
cutoff := now.Add(-rl.window)
|
||||
|
||||
// Remove expired entries
|
||||
// Filter in place: slicing to [:0] reuses the existing backing array, so
|
||||
// the append below overwrites the old timestamps instead of allocating a
|
||||
// new slice on every request. Safe here because we only ever write an
|
||||
// element at an index we have already read past. A missing key yields a
|
||||
// nil slice, and nil[:0] is legal and yields nil.
|
||||
valid := rl.attempts[key][:0]
|
||||
for _, t := range rl.attempts[key] {
|
||||
if t.After(cutoff) {
|
||||
|
||||
@@ -9,7 +9,13 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// SeedDatabase populates an empty database with demo content for local
|
||||
// development. It is called from main only when SEED_DB=true, which
|
||||
// docker-compose.dev.yml sets; it must never run in production because it
|
||||
// creates an admin account with the password "password".
|
||||
func SeedDatabase(db *gorm.DB) {
|
||||
// "Any user exists" is the whole idempotency check — if the users table
|
||||
// has a row, nothing is seeded, even if the other tables were emptied.
|
||||
var user models.User
|
||||
if db.First(&user).Error == nil {
|
||||
log.Println("Database already has data, skipping seed")
|
||||
@@ -23,11 +29,14 @@ func SeedDatabase(db *gorm.DB) {
|
||||
log.Fatal("Failed to hash seed password:", err)
|
||||
}
|
||||
|
||||
// Dev-only credentials: testuser / password.
|
||||
testUser := models.User{
|
||||
Username: "testuser",
|
||||
Password: hashedPassword,
|
||||
Admin: true,
|
||||
}
|
||||
// GORM writes the generated primary key back into testUser, which the
|
||||
// posts below then reference as their author.
|
||||
db.Create(&testUser)
|
||||
|
||||
posts := []models.Post{
|
||||
|
||||
@@ -13,6 +13,10 @@ import (
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// SpotifyConfig holds the OAuth app credentials. AuthState is the fixed
|
||||
// `state` value used in the authorisation URL; because the flow is only ever
|
||||
// driven by hand by the site owner, it is a constant rather than a
|
||||
// per-request nonce.
|
||||
type SpotifyConfig struct {
|
||||
AuthState string
|
||||
RedirectURL string
|
||||
@@ -20,8 +24,15 @@ type SpotifyConfig struct {
|
||||
ClientSecret string
|
||||
}
|
||||
|
||||
// SPOTIFY_TOKEN_JSON_PATH is inside a Docker volume, so the refresh token
|
||||
// survives container restarts and the OAuth dance only has to be done once.
|
||||
const SPOTIFY_TOKEN_JSON_PATH = "/backend/token/spotify_token.json"
|
||||
|
||||
// SaveSpotifyToken persists an OAuth token to disk.
|
||||
//
|
||||
// It copies the fields into a local anonymous struct rather than marshalling
|
||||
// oauth2.Token directly, so the on-disk format stays stable regardless of what
|
||||
// the oauth2 package adds to its own struct or its JSON tags.
|
||||
func SaveSpotifyToken(path string, tok *oauth2.Token) error {
|
||||
data := struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
@@ -48,6 +59,9 @@ func SaveSpotifyToken(path string, tok *oauth2.Token) error {
|
||||
return os.WriteFile(path, jsonBytes, 0600)
|
||||
}
|
||||
|
||||
// LoadSpotifyToken reads a token previously written by SaveSpotifyToken.
|
||||
// A missing file returns an error, which callers treat as "not yet
|
||||
// authenticated" rather than a fault.
|
||||
func LoadSpotifyToken(path string) (*oauth2.Token, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
@@ -75,6 +89,14 @@ func LoadSpotifyToken(path string) (*oauth2.Token, error) {
|
||||
return tok, nil
|
||||
}
|
||||
|
||||
// InitSpotifyAuth builds the OAuth authenticator and, if a saved token
|
||||
// exists, an authenticated client.
|
||||
//
|
||||
// Start-up never fails on Spotify problems: when there is no token or the
|
||||
// refresh is rejected it prints the authorisation URL to the container log
|
||||
// and returns a nil client. Every Spotify handler and resolver therefore has
|
||||
// to nil-check Store.SpotifyClient. Visiting that URL sends the browser to
|
||||
// /spotify/callback, which fills the client in at runtime.
|
||||
func InitSpotifyAuth(config *SpotifyConfig) (*spotifyauth.Authenticator, *spotify.Client) {
|
||||
auth := spotifyauth.New(
|
||||
spotifyauth.WithRedirectURL(config.RedirectURL),
|
||||
@@ -106,7 +128,18 @@ func InitSpotifyAuth(config *SpotifyConfig) (*spotifyauth.Authenticator, *spotif
|
||||
return auth, client
|
||||
}
|
||||
|
||||
// RefreshClient exchanges a stored token for a fresh one and returns a client
|
||||
// using it.
|
||||
//
|
||||
// Spotify may issue a new refresh token during this exchange, so the result is
|
||||
// written straight back to disk; the write error is ignored because a failed
|
||||
// save only costs a re-authentication later, and failing the whole start-up
|
||||
// over it would be worse. The returned client also holds the token source
|
||||
// internally and keeps refreshing on its own — but those later refreshes are
|
||||
// NOT persisted, so after a long uptime the file on disk can be stale.
|
||||
func RefreshClient(auth *spotifyauth.Authenticator, token *oauth2.Token) (*spotify.Client, error) {
|
||||
// context.Background rather than a request context: the resulting client
|
||||
// is long-lived and must outlive whichever request triggered this.
|
||||
ctx := context.Background()
|
||||
|
||||
token, err := auth.RefreshToken(ctx, token)
|
||||
|
||||
@@ -8,6 +8,12 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// This file wraps the two public Steam Web API endpoints used by the home
|
||||
// page. Results are cached by the caller (handlers.Store, 5 minute TTL) to
|
||||
// stay well inside Steam's rate limits.
|
||||
|
||||
// SteamRecentGame is one game from GetRecentlyPlayedGames. Playtimes are in
|
||||
// minutes.
|
||||
type SteamRecentGame struct {
|
||||
AppID int `json:"appid"`
|
||||
Name string `json:"name"`
|
||||
@@ -15,6 +21,8 @@ type SteamRecentGame struct {
|
||||
PlaytimeForever int `json:"playtime_forever"`
|
||||
}
|
||||
|
||||
// SteamRecentGamesResponse mirrors Steam's envelope, which wraps everything
|
||||
// in a "response" object.
|
||||
type SteamRecentGamesResponse struct {
|
||||
Response struct {
|
||||
TotalCount int `json:"total_count"`
|
||||
@@ -22,16 +30,26 @@ type SteamRecentGamesResponse struct {
|
||||
} `json:"response"`
|
||||
}
|
||||
|
||||
// SteamPlayerSummary is the subset of GetPlayerSummaries we care about.
|
||||
// PersonaState is Steam's online status enum: 0 = offline, anything higher
|
||||
// is some flavour of online (online, busy, away, snooze, looking to trade or
|
||||
// play), which is why the caller treats "> 0" as online.
|
||||
type SteamPlayerSummary struct {
|
||||
PersonaState int `json:"personastate"`
|
||||
}
|
||||
|
||||
// SteamPlayerSummariesResponse mirrors Steam's response envelope.
|
||||
type SteamPlayerSummariesResponse struct {
|
||||
Response struct {
|
||||
Players []SteamPlayerSummary `json:"players"`
|
||||
} `json:"response"`
|
||||
}
|
||||
|
||||
// FetchRecentlyPlayedGames returns the three most recently played games.
|
||||
//
|
||||
// Steam answers with HTTP 200 and an empty envelope for a private profile or
|
||||
// a bad key, so an empty slice and no error is the normal "nothing to show"
|
||||
// result rather than a failure.
|
||||
func FetchRecentlyPlayedGames(apiKey, steamID string) ([]SteamRecentGame, error) {
|
||||
url := fmt.Sprintf("https://api.steampowered.com/IPlayerService/GetRecentlyPlayedGames/v1/?key=%s&steamid=%s&count=3", apiKey, steamID)
|
||||
|
||||
@@ -55,6 +73,8 @@ func FetchRecentlyPlayedGames(apiKey, steamID string) ([]SteamRecentGame, error)
|
||||
return result.Response.Games, nil
|
||||
}
|
||||
|
||||
// FetchPlayerSummary returns the profile's online status, or (nil, nil) when
|
||||
// Steam returns no players (private or unknown profile).
|
||||
func FetchPlayerSummary(apiKey, steamID string) (*SteamPlayerSummary, error) {
|
||||
url := fmt.Sprintf("https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/?key=%s&steamids=%s", apiKey, steamID)
|
||||
|
||||
|
||||
@@ -12,10 +12,27 @@ import (
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// This file is the chat hub behind GET /ws. It is deliberately a package-level
|
||||
// singleton (one process, one chat room) rather than an injectable type, so the
|
||||
// connection set, the database handle and the allowed origin all live in
|
||||
// package vars initialised once by InitWebSocket.
|
||||
|
||||
// maxMessages is both the size of the history replayed to a new client and the
|
||||
// number of rows kept in the database: every insert trims older messages.
|
||||
const maxMessages = 50
|
||||
|
||||
// allowedDomain is the site's domain, set by InitWebSocket and read by
|
||||
// Upgrader.CheckOrigin. It is a package var because the Upgrader is one too.
|
||||
var allowedDomain string
|
||||
|
||||
// Upgrader turns the HTTP request into a WebSocket.
|
||||
//
|
||||
// CheckOrigin is the only cross-origin defence on this endpoint: the browser
|
||||
// sends cookies with a WebSocket handshake regardless of origin and there is
|
||||
// no preflight, so without this check any site could open a socket as a
|
||||
// logged-in visitor. Default gorilla behaviour (same-host only) is too strict
|
||||
// here because the site is reached as both example.com and www.example.com,
|
||||
// and "localhost" is allowed for the Vite dev server.
|
||||
var Upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
@@ -35,12 +52,21 @@ var Upgrader = websocket.Upgrader{
|
||||
|
||||
var (
|
||||
// clients maps each open connection to whether it belongs to an admin.
|
||||
clients = make(map[*websocket.Conn]bool)
|
||||
mu sync.Mutex
|
||||
wsDB *gorm.DB
|
||||
clients = make(map[*websocket.Conn]bool)
|
||||
// mu guards clients AND serialises the write-then-broadcast sequence, so
|
||||
// that two concurrent senders cannot interleave and deliver messages to
|
||||
// different clients in different orders.
|
||||
mu sync.Mutex
|
||||
wsDB *gorm.DB
|
||||
// nextAuthorID is a per-process counter handed out on connect. It is NOT
|
||||
// a user id and has no meaning across restarts: the chat is pseudonymous,
|
||||
// and the front end only uses it to colour/group consecutive messages
|
||||
// from the same connection.
|
||||
nextAuthorID uint
|
||||
)
|
||||
|
||||
// Per-connection flood limit, separate from services.RateLimiter because it
|
||||
// counts frames on one socket rather than requests from one IP.
|
||||
const (
|
||||
rateLimitWindow = time.Second
|
||||
rateLimitMaxMsgs = 10
|
||||
@@ -70,6 +96,8 @@ type wsHistoryEvent struct {
|
||||
Messages []models.Message `json:"messages"`
|
||||
}
|
||||
|
||||
// InitWebSocket wires the package-level hub to the database and the origin
|
||||
// allow-list. Call it once, before serving.
|
||||
func InitWebSocket(database *gorm.DB, domain string) {
|
||||
wsDB = database
|
||||
allowedDomain = domain
|
||||
@@ -80,6 +108,11 @@ func InitWebSocket(database *gorm.DB, domain string) {
|
||||
func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
|
||||
defer conn.Close()
|
||||
|
||||
// Registration, history read and history send all happen under one lock.
|
||||
// That is the point: it guarantees the client is already in `clients`
|
||||
// before its snapshot is taken, so a message broadcast concurrently is
|
||||
// either in the history or delivered afterwards — never dropped in the
|
||||
// gap, and never delivered before the history that would overwrite it.
|
||||
mu.Lock()
|
||||
clients[conn] = isAdmin
|
||||
nextAuthorID++
|
||||
@@ -99,11 +132,15 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
|
||||
}
|
||||
mu.Unlock()
|
||||
|
||||
// Fixed-window flood limit. Over-limit frames are dropped silently with
|
||||
// no error to the client and without resetting the window.
|
||||
msgCount := 0
|
||||
windowStart := time.Now()
|
||||
|
||||
for {
|
||||
var incoming wsIncoming
|
||||
// Any read error — clean close, network drop or malformed JSON —
|
||||
// ends the connection; there is no attempt to resynchronise.
|
||||
if err := conn.ReadJSON(&incoming); err != nil {
|
||||
break
|
||||
}
|
||||
@@ -135,10 +172,18 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
|
||||
|
||||
mu.Lock()
|
||||
wsDB.Create(&msg)
|
||||
// Keep only the newest maxMessages rows. This is a soft delete
|
||||
// (models.Message has gorm.DeletedAt), so the rows stay in the table
|
||||
// with deleted_at set and GORM filters them out of later reads; the
|
||||
// table therefore grows forever even though the chat does not.
|
||||
// The subquery is itself soft-delete filtered, so already-trimmed
|
||||
// rows are not re-deleted.
|
||||
wsDB.Where("id NOT IN (?)",
|
||||
wsDB.Model(&models.Message{}).Select("id").Order("created_at DESC").Limit(maxMessages),
|
||||
).Delete(&models.Message{})
|
||||
|
||||
// Deleting from a map while ranging over it is explicitly allowed in
|
||||
// Go, so pruning dead clients inline here is safe.
|
||||
for client, clientAdmin := range clients {
|
||||
if msg.Private && !clientAdmin {
|
||||
continue
|
||||
|
||||
Reference in New Issue
Block a user