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:
@@ -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