Fix security issues, bugs, and convoluted code across the stack
Security: - Token revocation. User gains a TokenVersion counter embedded in both tokens as a "tv" claim; AuthenticateToken rejects a token whose version no longer matches the row. Logout bumps it, so logging out now kills outstanding tokens rather than only clearing cookies. Costs one primary-key SELECT per authenticated request, which is the price of having revocation at all. - Spotify OAuth CSRF. The fixed SPOTIFY_AUTH_STATE constant is replaced by a per-request one-shot nonce, verified and consumed on callback. - Private chat attachments. Attachments on private messages are written to /backend/uploads/private/ and served at /uploads/private/, gated by the same nginx auth_request admin check used for /hasura/ and /notes/. Private uploads are rejected from non-admin callers. - The icecast admin UI (/radio/admin/) is behind the admin gate; listener traffic is untouched. - Store caches are mutex-guarded, so -race is clean. Bugs: - The email pipeline no longer drops emails permanently on transient failure. Failures record an attempt counter and are retried up to 3 times; the fetch window rewinds to the oldest retryable email's ReceivedAt, without which a retry could never re-fetch it. - Rowing duplicate detection distinguishes ErrRecordNotFound from a real DB error, so a transient failure no longer causes a duplicate insert plus a paid Claude call. - DeletePost propagates its delete error instead of reporting success. - RecentlyPlayed populates the cache it reads. - main.go exits non-zero if r.Run fails, so a port conflict is visible. - Python: the scan truncation flag is set on every deadline path; timed_out is reported by the worker rather than inferred from the clock; date validation uses Europe/London rather than server-local time. - Vue: Time.vue and Radio.vue intervals are cleared on unmount; Feed.vue guards a missing author; Timer.vue gets an explicit state machine and compares total elapsed seconds; Elle.vue's comma-operator call and per-frame console.log are fixed. Simplification: - One TTLCache replaces three near-identical cache implementations, with the differing eviction rules as explicit parameters. - run_scan's transport index no longer uses one object as both ordering record and live output; its three phases are separate functions. - _price_hotels submits all work to a single pool, so the nested-executor deadlock hazard is gone by construction. - The NDJSON event generators share one implementation. - IMAP FETCH responses pair each line with its literal in the type, so callers no longer hand-skip alternate entries. - Shared helpers for slice-of-pointers, markdown fences and auth cookies. - Vue: useHotelSearch, createMirrorStore, useRotation, useCreateForm, useLinkAttrs, ListWidget and LinkTableItems replace duplicated blocks. - nginx dev config's duplicated :80/:443 bodies share one partial. Infra: certbot passes --deploy-hook touching a sentinel that nginx's watcher reloads on, so renewed certs are served without a restart, and the watcher also removes the manual restart after first issuance. db is gated on service_healthy, autoheal is pinned, and the unused envsubst entries are dropped. Verified: go build/vet, npx vite build, py_compile, docker compose config for both overlays, bash -n on all scripts, and an envsubst render of every nginx template (no leftover placeholders, runtime vars preserved, braces balanced). Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
+160
-6
@@ -2,16 +2,23 @@ package services
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 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.
|
||||
// are handed to the browser as HTTP-only cookies (see handlers.Store.Login).
|
||||
//
|
||||
// There is no token blacklist, but there is coarse server-side revocation:
|
||||
// every token carries the user's models.User.TokenVersion in a "tv" claim,
|
||||
// and AuthenticateToken rejects a token whose version has moved on. Bumping
|
||||
// that column (BumpTokenVersion) therefore kills all of a user's outstanding
|
||||
// tokens at once — which is what logout and a password change do.
|
||||
type Auth struct {
|
||||
Config *AuthConfig
|
||||
}
|
||||
@@ -43,19 +50,26 @@ func InitAuth(config *AuthConfig) *Auth {
|
||||
//
|
||||
// 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.
|
||||
// refresh token deliberately carries only the id (plus the version): 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.
|
||||
//
|
||||
// Both tokens carry "tv", the user's TokenVersion at minting time. Anything
|
||||
// that validates a token against the database checks it, so the pair dies the
|
||||
// moment the column is bumped.
|
||||
func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) {
|
||||
accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"username": user.Username,
|
||||
"id": user.ID,
|
||||
"admin": user.Admin,
|
||||
"tv": tokenVersionOf(user.TokenVersion),
|
||||
"exp": time.Now().Add(auth.Config.AccessTokenLifetime).Unix(),
|
||||
})
|
||||
|
||||
refreshToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"id": user.ID,
|
||||
"tv": tokenVersionOf(user.TokenVersion),
|
||||
"exp": time.Now().Add(auth.Config.RefreshTokenLifetime).Unix(),
|
||||
})
|
||||
|
||||
@@ -99,3 +113,143 @@ func (auth *Auth) VerifyJWT(tokenStr string) (*jwt.MapClaims, error) {
|
||||
|
||||
return &claims, nil
|
||||
}
|
||||
|
||||
// Typed errors returned by AuthenticateToken so each call site can keep its
|
||||
// own response for each case — the REST and GraphQL entry points deliberately
|
||||
// answer differently (401 vs 500 vs 404-plus-cookie-clear).
|
||||
var (
|
||||
// ErrInvalidToken means the token is missing, malformed, expired or not
|
||||
// correctly signed.
|
||||
ErrInvalidToken = errors.New("invalid token")
|
||||
// ErrInvalidClaims means the token verified but its "id" claim is absent
|
||||
// or not a number — a server-side inconsistency, not a client error.
|
||||
ErrInvalidClaims = errors.New("invalid token claims")
|
||||
// ErrUserNotFound means the token named a user that no longer exists (or
|
||||
// has been soft deleted).
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
// ErrTokenRevoked means the token is otherwise valid but was minted
|
||||
// before the user's TokenVersion was bumped, i.e. logout or a password
|
||||
// change has invalidated it.
|
||||
ErrTokenRevoked = errors.New("token revoked")
|
||||
)
|
||||
|
||||
// tokenVersionOf normalises a stored or claimed token version.
|
||||
//
|
||||
// Zero means "unset": either a row that predates the token_version column, or
|
||||
// a token minted before the "tv" claim existed. Both are normalised to 1, the
|
||||
// column's default, so introducing versioning logs nobody out. The first
|
||||
// BumpTokenVersion moves a user to 2 and invalidates every older token.
|
||||
func tokenVersionOf(v uint) uint {
|
||||
if v == 0 {
|
||||
return 1
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// AuthenticateToken is the one place a token string is turned into a user: it
|
||||
// verifies the signature and expiry, reads the id claim, loads the row, and
|
||||
// checks the token version. Every caller that used to hand-roll this sequence
|
||||
// (handlers.Store.CheckToken, handlers.Store.RefreshToken,
|
||||
// handlers.Store.tryRefreshAndValidateAdmin and the GraphQL refreshToken
|
||||
// resolver) now goes through here, so the checks cannot drift apart.
|
||||
//
|
||||
// The returned error is always one of the sentinels above, wrapped or not, so
|
||||
// call sites can map each case onto whatever status code they already used.
|
||||
func (auth *Auth) AuthenticateToken(db *gorm.DB, tokenStr string) (*models.User, error) {
|
||||
user, _, err := auth.AuthenticateTokenWithClaims(db, tokenStr)
|
||||
return user, err
|
||||
}
|
||||
|
||||
// AuthenticateTokenWithClaims is AuthenticateToken plus the raw claims, for
|
||||
// the middlewares that go on to read claims the User struct does not carry
|
||||
// (notably "admin", which is authoritative from the token rather than the
|
||||
// row — see handlers.AdminMiddleware).
|
||||
//
|
||||
// Note this costs one primary-key SELECT per authenticated request. That is
|
||||
// the price of revocation: without loading the row there is no version to
|
||||
// compare against, and logout could not kill a live access token.
|
||||
func (auth *Auth) AuthenticateTokenWithClaims(db *gorm.DB, tokenStr string) (*models.User, *jwt.MapClaims, error) {
|
||||
claims, err := auth.VerifyJWT(tokenStr)
|
||||
if err != nil {
|
||||
return nil, nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
// Claims are decoded by encoding/json, so every number arrives as a
|
||||
// float64 regardless of the Go type it was signed from.
|
||||
userIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
return nil, nil, ErrInvalidClaims
|
||||
}
|
||||
|
||||
// Pre-setting the primary key and calling First with no explicit
|
||||
// condition makes GORM look the row up by that key. Soft-deleted users
|
||||
// are excluded automatically, so a deleted account fails here.
|
||||
user := models.User{ID: uint(userIDF)}
|
||||
if err := db.First(&user).Error; err != nil {
|
||||
return nil, nil, ErrUserNotFound
|
||||
}
|
||||
|
||||
// A token with no "tv" claim reads as 0 and is normalised to 1, matching
|
||||
// an un-bumped user — see tokenVersionOf.
|
||||
claimedVersion, _ := (*claims)["tv"].(float64)
|
||||
if tokenVersionOf(uint(claimedVersion)) != tokenVersionOf(user.TokenVersion) {
|
||||
return nil, nil, ErrTokenRevoked
|
||||
}
|
||||
|
||||
return &user, claims, nil
|
||||
}
|
||||
|
||||
// BumpTokenVersion invalidates every token previously issued to userID by
|
||||
// incrementing the user's version counter. Callers treat a failure as
|
||||
// non-fatal (logout still clears the cookies), but it must be logged: a
|
||||
// silent failure here means a logout that did not actually revoke anything.
|
||||
//
|
||||
// COALESCE covers a pre-migration row sitting at 0 or NULL: it is treated as
|
||||
// 1, so the bump lands on 2 and invalidates tokens claiming either.
|
||||
func BumpTokenVersion(db *gorm.DB, userID uint) error {
|
||||
return db.Model(&models.User{}).
|
||||
Where("id = ?", userID).
|
||||
UpdateColumn("token_version", gorm.Expr("COALESCE(token_version, 1) + 1")).
|
||||
Error
|
||||
}
|
||||
|
||||
// SetAuthCookies writes the access/refresh cookie pair.
|
||||
//
|
||||
// It lives in services because both handlers and graph need it and handlers
|
||||
// cannot import graph (that would be an import cycle); keeping one copy is
|
||||
// what stops REST login and GraphQL login drifting apart.
|
||||
//
|
||||
// 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 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 SetAuthCookies(gc *gin.Context, config *AuthConfig, tokens *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,
|
||||
)
|
||||
}
|
||||
|
||||
// ClearAuthCookies 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 ClearAuthCookies(gc *gin.Context, config *AuthConfig) {
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie("access_token", "", -1, "/", config.Domain, true, true)
|
||||
gc.SetCookie("refresh_token", "", -1, "/", config.Domain, true, true)
|
||||
}
|
||||
|
||||
@@ -136,27 +136,35 @@ func (c *imapClient) readLiteral(size int) (string, error) {
|
||||
return string(buf), nil
|
||||
}
|
||||
|
||||
// fetchPart is one FETCH response line plus the literal payload that followed
|
||||
// it, if any. Pairing them in the type removes the need for callers to walk an
|
||||
// interleaved slice and manually skip every second entry — the previous shape,
|
||||
// where a literal was simply the next element and a caller that forgot to
|
||||
// advance would parse message bytes as a protocol line.
|
||||
type fetchPart struct {
|
||||
Line string
|
||||
// Literal is the payload that followed Line, valid only when HasLiteral.
|
||||
Literal string
|
||||
HasLiteral bool
|
||||
}
|
||||
|
||||
// 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) {
|
||||
func (c *imapClient) sendFetch(cmd string) ([]fetchPart, error) {
|
||||
tag := c.nextTag()
|
||||
_, err := fmt.Fprintf(c.conn, "%s %s\r\n", tag, cmd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var lines []string
|
||||
var parts []fetchPart
|
||||
for {
|
||||
line, err := c.readLine()
|
||||
if err != nil {
|
||||
return lines, err
|
||||
return parts, err
|
||||
}
|
||||
|
||||
// Check for literal marker {N} at end of line
|
||||
@@ -166,23 +174,22 @@ func (c *imapClient) sendFetch(cmd string) ([]string, error) {
|
||||
if _, err := fmt.Sscanf(sizeStr, "%d", &size); err == nil && size > 0 {
|
||||
literal, err := c.readLiteral(size)
|
||||
if err != nil {
|
||||
return lines, fmt.Errorf("reading literal of %d bytes: %w", size, err)
|
||||
return parts, fmt.Errorf("reading literal of %d bytes: %w", size, err)
|
||||
}
|
||||
lines = append(lines, line)
|
||||
lines = append(lines, literal)
|
||||
parts = append(parts, fetchPart{Line: line, Literal: literal, HasLiteral: true})
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if strings.HasPrefix(line, tag+" ") {
|
||||
// Check for OK
|
||||
parts := strings.SplitN(line, " ", 3)
|
||||
if len(parts) >= 2 && parts[1] != "OK" {
|
||||
return lines, fmt.Errorf("FETCH failed: %s", line)
|
||||
fields := strings.SplitN(line, " ", 3)
|
||||
if len(fields) >= 2 && fields[1] != "OK" {
|
||||
return parts, fmt.Errorf("FETCH failed: %s", line)
|
||||
}
|
||||
return lines, nil
|
||||
return parts, nil
|
||||
}
|
||||
lines = append(lines, line)
|
||||
parts = append(parts, fetchPart{Line: line})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,33 +252,24 @@ func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, err
|
||||
// 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))
|
||||
fetchParts, err := c.sendFetch(fmt.Sprintf("FETCH %s (BODY[])", seqSet))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("IMAP fetch: %w", err)
|
||||
}
|
||||
|
||||
// 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.
|
||||
// Each body arrives as a "... BODY[] {N}" line carrying its literal, so
|
||||
// the pairing is now part of the value rather than something this loop has
|
||||
// to reconstruct by skipping entries. 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]
|
||||
// Look for a literal following this line
|
||||
if strings.Contains(line, "BODY[]") && strings.HasSuffix(line, "}") {
|
||||
if i+1 < len(fetchLines) {
|
||||
raw := fetchLines[i+1]
|
||||
// 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)
|
||||
continue
|
||||
}
|
||||
messages = append(messages, gm)
|
||||
for _, part := range fetchParts {
|
||||
if part.HasLiteral && strings.Contains(part.Line, "BODY[]") {
|
||||
gm, err := parseRawEmail(part.Literal)
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync/IMAP] Error parsing email: %v", err)
|
||||
continue
|
||||
}
|
||||
messages = append(messages, gm)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+126
-28
@@ -406,6 +406,21 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
since = latest.CreatedAt
|
||||
}
|
||||
|
||||
// Pull the window back to cover any still-retryable failure. Without this
|
||||
// the clamp above would have advanced past a failed email — the error row
|
||||
// is written now, so the next window starts after it — and the retry
|
||||
// below could never see the email again. Rows predating ReceivedAt have
|
||||
// a zero value and are ignored rather than dragging the window to 0001.
|
||||
var oldestRetryable models.ProcessedEmail
|
||||
if err := s.DB.
|
||||
Where("action = ? AND attempts < ? AND received_at > ?", "error", maxEmailAttempts, time.Time{}).
|
||||
Order("received_at ASC").
|
||||
First(&oldestRetryable).Error; err == nil && oldestRetryable.ReceivedAt.Before(since) {
|
||||
log.Printf("[EmailSync] Rewinding window to %s to retry a previous failure",
|
||||
oldestRetryable.ReceivedAt.Format(time.RFC3339))
|
||||
since = oldestRetryable.ReceivedAt
|
||||
}
|
||||
|
||||
// Fetch emails from Microsoft Graph
|
||||
emails, err := s.fetchEmails(ctx, since)
|
||||
if err != nil {
|
||||
@@ -421,36 +436,50 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
var created, updated, skipped, errored int
|
||||
|
||||
for _, email := range filtered {
|
||||
// Dedup check
|
||||
// Dedup check. A row is terminal — and so genuinely skippable — if it
|
||||
// succeeded, or if it failed the maximum number of times. A row that
|
||||
// failed but has attempts left is deliberately NOT skipped: it is
|
||||
// reprocessed below and the same row updated, so a transient Claude
|
||||
// or network outage no longer drops the email permanently.
|
||||
var existing models.ProcessedEmail
|
||||
if err := s.DB.Where("graph_message_id = ?", email.ID).First(&existing).Error; err == nil {
|
||||
found := s.DB.Where("graph_message_id = ?", email.ID).First(&existing).Error == nil
|
||||
if found && !retryableFailure(&existing) {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
// 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)
|
||||
s.DB.Create(&models.ProcessedEmail{
|
||||
GraphMessageID: email.ID,
|
||||
Subject: truncate(email.Subject, 255),
|
||||
Action: "error",
|
||||
})
|
||||
errored++
|
||||
continue
|
||||
if found {
|
||||
log.Printf("[EmailSync] Retrying previously failed email %q (attempt %d of %d)",
|
||||
email.Subject, existing.Attempts+1, maxEmailAttempts)
|
||||
}
|
||||
|
||||
// Record as processed
|
||||
s.DB.Create(&models.ProcessedEmail{
|
||||
action, jobAppID, processErr := s.processEmail(ctx, email)
|
||||
|
||||
// The row carries the outcome either way. On failure the attempt
|
||||
// counter advances, so repeated failures walk the row towards the cap
|
||||
// and it eventually stops being retried.
|
||||
record := models.ProcessedEmail{
|
||||
GraphMessageID: email.ID,
|
||||
Subject: truncate(email.Subject, 255),
|
||||
Action: action,
|
||||
JobAppID: jobAppID,
|
||||
})
|
||||
ReceivedAt: parseReceivedAt(email.ReceivedDateTime),
|
||||
Attempts: existing.Attempts + 1,
|
||||
}
|
||||
|
||||
if processErr != nil {
|
||||
log.Printf("[EmailSync] Error processing email %q: %v", email.Subject, processErr)
|
||||
record.Action = "error"
|
||||
record.JobAppID = nil
|
||||
if record.Attempts >= maxEmailAttempts {
|
||||
log.Printf("[EmailSync] Email %q has failed %d times; giving up on it",
|
||||
email.Subject, record.Attempts)
|
||||
}
|
||||
s.saveProcessed(found, &existing, &record)
|
||||
errored++
|
||||
continue
|
||||
}
|
||||
|
||||
s.saveProcessed(found, &existing, &record)
|
||||
|
||||
switch action {
|
||||
case "created":
|
||||
@@ -597,14 +626,8 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage)
|
||||
|
||||
// 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")
|
||||
raw = strings.TrimPrefix(raw, "```")
|
||||
raw = strings.TrimSuffix(raw, "```")
|
||||
raw = strings.TrimSpace(raw)
|
||||
// stripped defensively here.
|
||||
raw := StripMarkdownFence(message.Content[0].Text)
|
||||
|
||||
var analysis EmailAnalysis
|
||||
if err := json.Unmarshal([]byte(raw), &analysis); err != nil {
|
||||
@@ -804,3 +827,78 @@ Return ONLY a JSON object with these exact keys:
|
||||
- "notes": string or null - brief summary of what this email communicates (e.g. "Interview scheduled for March 15", "Application confirmed via Greenhouse")
|
||||
|
||||
If isJobEmail is false, only include that field. No text, no markdown, no explanation. Just the JSON object.`
|
||||
|
||||
// StripMarkdownFence removes a surrounding markdown code fence from a model's
|
||||
// response, so text that should have been bare JSON can be unmarshalled
|
||||
// whether or not the model wrapped it.
|
||||
//
|
||||
// The two TrimPrefix calls are ordered so that "```json" is removed first and
|
||||
// a plain "```" otherwise. It is deliberately forgiving: unfenced input is
|
||||
// returned unchanged apart from surrounding whitespace.
|
||||
//
|
||||
// Shared with handlers.CreateRowing, which prompts for bare JSON in the same
|
||||
// way and gets the same fenced output.
|
||||
func StripMarkdownFence(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
raw = strings.TrimPrefix(raw, "```json")
|
||||
raw = strings.TrimPrefix(raw, "```")
|
||||
raw = strings.TrimSuffix(raw, "```")
|
||||
|
||||
return strings.TrimSpace(raw)
|
||||
}
|
||||
|
||||
// maxEmailAttempts caps how many times a failing email is reprocessed. Each
|
||||
// attempt costs a Claude call, so the cap is what stops one permanently
|
||||
// unparseable email billing on every sync forever. Three gives a transient
|
||||
// outage two further chances across subsequent syncs.
|
||||
const maxEmailAttempts = 3
|
||||
|
||||
// retryableFailure reports whether a previously recorded email should be
|
||||
// processed again. Only failures are retried, and only while they have
|
||||
// attempts left; anything that succeeded is terminal.
|
||||
func retryableFailure(row *models.ProcessedEmail) bool {
|
||||
return row.Action == "error" && row.Attempts < maxEmailAttempts
|
||||
}
|
||||
|
||||
// parseReceivedAt converts the provider's timestamp to a time.Time, returning
|
||||
// the zero value if it is missing or malformed. A zero value is safe: it only
|
||||
// means this row cannot pull the fetch window back, so the email is retried
|
||||
// on the next sync that happens to cover it rather than being chased.
|
||||
func parseReceivedAt(raw string) time.Time {
|
||||
if raw == "" {
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
received, err := time.Parse(time.RFC3339, raw)
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync] Unparseable receivedDateTime %q: %v", raw, err)
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
return received
|
||||
}
|
||||
|
||||
// saveProcessed writes the outcome of an attempt: updating the existing row
|
||||
// when this was a retry, inserting when it is the first attempt. Update is
|
||||
// used rather than Save so the row keeps its original CreatedAt, which the
|
||||
// fetch window depends on.
|
||||
func (s *EmailSyncService) saveProcessed(found bool, existing, record *models.ProcessedEmail) {
|
||||
var err error
|
||||
if found {
|
||||
err = s.DB.Model(existing).Updates(map[string]any{
|
||||
"action": record.Action,
|
||||
"job_app_id": record.JobAppID,
|
||||
"attempts": record.Attempts,
|
||||
"received_at": record.ReceivedAt,
|
||||
}).Error
|
||||
} else {
|
||||
err = s.DB.Create(record).Error
|
||||
}
|
||||
|
||||
// Logged rather than returned: a bookkeeping failure must not abort the
|
||||
// rest of the batch. It does mean the email is reprocessed next sync,
|
||||
// which the dedup treats as a first attempt.
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync] Failed to record processed email %q: %v", record.Subject, err)
|
||||
}
|
||||
}
|
||||
|
||||
+13
-13
@@ -13,12 +13,12 @@ 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.
|
||||
// SpotifyConfig holds the OAuth app credentials.
|
||||
//
|
||||
// There is no state value here any more: the `state` parameter is a one-shot
|
||||
// CSRF nonce minted per authorisation request by handlers.Store, so a fixed
|
||||
// configured value would defeat the point.
|
||||
type SpotifyConfig struct {
|
||||
AuthState string
|
||||
RedirectURL string
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
@@ -93,10 +93,12 @@ func LoadSpotifyToken(path string) (*oauth2.Token, error) {
|
||||
// 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.
|
||||
// refresh is rejected it logs how to authenticate and returns a nil client.
|
||||
// Every Spotify handler and resolver therefore has to nil-check
|
||||
// Store.SpotifyClient. The authorisation URL can no longer be printed here
|
||||
// because its state nonce is per-request (see handlers.Store.StartSpotifyAuth);
|
||||
// following it 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),
|
||||
@@ -112,16 +114,14 @@ func InitSpotifyAuth(config *SpotifyConfig) (*spotifyauth.Authenticator, *spotif
|
||||
// check if token exists locally
|
||||
token, err := LoadSpotifyToken(SPOTIFY_TOKEN_JSON_PATH)
|
||||
if err != nil || token == nil {
|
||||
fmt.Println("No token saved. Authenticate Spotify with:")
|
||||
fmt.Println(auth.AuthURL(config.AuthState))
|
||||
fmt.Println("No Spotify token saved. Authenticate by calling GET /api/spotify/auth as an admin and opening the URL it returns.")
|
||||
return auth, nil
|
||||
}
|
||||
|
||||
// refresh token and client
|
||||
client, err := RefreshClient(auth, token)
|
||||
if err != nil {
|
||||
fmt.Println("Failed to refresh token. Authenticate Spotify with:")
|
||||
fmt.Println(auth.AuthURL(config.AuthState))
|
||||
fmt.Println("Failed to refresh Spotify token. Re-authenticate by calling GET /api/spotify/auth as an admin and opening the URL it returns.")
|
||||
return auth, nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user