Generate the job capture token from the admin panel
Deploy with Docker Compose / deploy (push) Successful in 52s

The userscript's bearer token was an env var, JOB_CAPTURE_TOKEN, so rotating
it meant editing .env and redeploying. It is now minted on the admin
diagnostics panel instead, and the env var is gone.

- services.CaptureToken keeps only a SHA-256 of the token, in
  backend/token/job_capture_token.json beside the OAuth tokens, so it
  survives rebuilds and cannot be read back. The token is shown once.
- GET/POST/DELETE /admin/capture-token report, generate (replacing any
  existing token) and revoke it, behind the cookie-authenticated admin group.
- With no token generated the capture routes still answer 503.
- Userscript bumped to 1.0.1 for the changed prompt text.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-12 13:40:30 +01:00
co-authored by Claude Opus 5.5
parent b8670246a8
commit 26f312e307
15 changed files with 600 additions and 64 deletions
-6
View File
@@ -158,12 +158,6 @@ EMAIL=
# calls for the rowing photo reader and the job posting reader; the backend # calls for the rowing photo reader and the job posting reader; the backend
# uses it for the email pipeline. # uses it for the email pipeline.
CLAUDE_API_KEY= CLAUDE_API_KEY=
# Bearer token for the job capture userscript (/api/jobs/capture*; see "Job
# capture" in backend/README.md). Generate a long random string, e.g.
# `openssl rand -hex 32`, and paste the same value into the script's
# "Configure job capture" menu command. Left EMPTY, the capture routes answer
# 503 — this is the one secret where blank means "off", not "open".
JOB_CAPTURE_TOKEN=
STEAM_API_KEY= STEAM_API_KEY=
STEAM_ID= STEAM_ID=
+1 -1
View File
@@ -78,7 +78,7 @@ Dockerized multi-service personal website self-hosted on a Raspberry Pi.
- **Auth flow**: Login sets `access_token` (7 days) and `refresh_token` (365 days) as HTTP-only cookies (`backend/main.go:96`). `AuthMiddleware` validates tokens and injects user into Gin context. `AuthContextMiddleware` passes Gin context into GraphQL resolver context. There is no token revocation — logout only clears cookies. - **Auth flow**: Login sets `access_token` (7 days) and `refresh_token` (365 days) as HTTP-only cookies (`backend/main.go:96`). `AuthMiddleware` validates tokens and injects user into Gin context. `AuthContextMiddleware` passes Gin context into GraphQL resolver context. There is no token revocation — logout only clears cookies.
- **GraphQL resolvers authorise themselves.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. Every resolver that needs auth must check it itself. See `backend/graph/doc.go`. - **GraphQL resolvers authorise themselves.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. Every resolver that needs auth must check it itself. See `backend/graph/doc.go`.
- **Spotify tokens**: Persisted to `/backend/token/spotify_token.json` inside the container, surviving restarts. - **Spotify tokens**: Persisted to `/backend/token/spotify_token.json` inside the container, surviving restarts.
- **Job capture**: `vue/public/job-capture.user.js` is a Violentmonkey userscript, served by the site and installed from `/cv/jobs`, that adds the posting open in the browser to the tracker. It calls the three `/api/jobs/capture` REST routes with a bearer token (`JOB_CAPTURE_TOKEN`) because cookies do not travel from other origins. Bump its `@version` on every edit or installed copies will not update. See "Job capture" in `backend/README.md`. - **Job capture**: `vue/public/job-capture.user.js` is a Violentmonkey userscript, served by the site and installed from `/cv/jobs`, that adds the posting open in the browser to the tracker. It calls the three `/api/jobs/capture` REST routes with a bearer token because cookies do not travel from other origins. The token is generated on the admin panel and stored hashed in `backend/token/job_capture_token.json`; there is no env var for it. Bump its `@version` on every edit or installed copies will not update. See "Job capture" in `backend/README.md`.
- **Gitea feed**: Backend proxies and caches (1 min TTL) the Gitea activity feed API. - **Gitea feed**: Backend proxies and caches (1 min TTL) the Gitea activity feed API.
- **All GORM models use soft delete** (`gorm.DeletedAt` field) — except `ProcessedEmail`, whose dedup must see history. Note that a `uniqueIndex` still collides with soft-deleted rows. - **All GORM models use soft delete** (`gorm.DeletedAt` field) — except `ProcessedEmail`, whose dedup must see history. Note that a `uniqueIndex` still collides with soft-deleted rows.
+1 -1
View File
@@ -210,7 +210,7 @@ of deleting the directory:
|---|---|---| |---|---|---|
| `./certbot/conf` | TLS certificates and **private keys** | Gitignored. Never commit. | | `./certbot/conf` | TLS certificates and **private keys** | Gitignored. Never commit. |
| `./certbot/www` | ACME challenge webroot | Transient by nature | | `./certbot/www` | ACME challenge webroot | Transient by nature |
| `./backend/token/` | **Spotify OAuth refresh token** (`spotify_token.json`) | Gitignored. Without this mount, Spotify would need re-authorising after every rebuild. | | `./backend/token/` | **Spotify OAuth refresh token** (`spotify_token.json`) and the **job capture token hash** (`job_capture_token.json`) | Gitignored. Without this mount, Spotify would need re-authorising after every rebuild, and the capture userscript a new token from the admin panel. |
| `./gitea/data` | Git repositories, LFS objects, avatars, sessions | The actual git data | | `./gitea/data` | Git repositories, LFS objects, avatars, sessions | The actual git data |
| `./gitea/config` | Gitea's live `app.ini` | Gitignored; generated from the template on first boot and then owned by Gitea | | `./gitea/config` | Gitea's live `app.ini` | Gitignored; generated from the template on first boot and then owned by Gitea |
| `./logs` | Backend logs | | | `./logs` | Backend logs | |
-1
View File
@@ -243,7 +243,6 @@ Create a `.env` file in the project root. All services read from this file.
| `DOMAIN` | Production domain name | | `DOMAIN` | Production domain name |
| `EMAIL` | Email for Let's Encrypt registration | | `EMAIL` | Email for Let's Encrypt registration |
| `CLAUDE_API_KEY` | Anthropic Claude API key | | `CLAUDE_API_KEY` | Anthropic Claude API key |
| `JOB_CAPTURE_TOKEN` | Bearer token for the job capture userscript; empty disables it |
| `STEAM_API_KEY` | Steam Web API key | | `STEAM_API_KEY` | Steam Web API key |
| `STEAM_ID` | Steam user ID | | `STEAM_ID` | Steam user ID |
| `PYTHON_HOST` | Python API hostname (defaults to `python`) | | `PYTHON_HOST` | Python API hostname (defaults to `python`) |
+11 -3
View File
@@ -83,6 +83,7 @@ for the things GraphQL cannot do:
| `/notes/*path` | streams a file download, not JSON | | `/notes/*path` | streams a file download, not JSON |
| `/ws` | WebSocket upgrade | | `/ws` | WebSocket upgrade |
| `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working | | `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working |
| `/admin/config`, `/admin/logs`, `/admin/capture-token` | process environment and files on disk, not the data model |
| `/jobs/capture`, `/jobs/capture/status`, `/jobs/capture/extract` | called by a userscript on other sites' origins, where the `SameSite=Lax` auth cookies are never sent; they take a bearer token instead | | `/jobs/capture`, `/jobs/capture/status`, `/jobs/capture/extract` | called by a userscript on other sites' origins, where the `SameSite=Lax` auth cookies are never sent; they take a bearer token instead |
### Job capture ### Job capture
@@ -91,10 +92,17 @@ for the things GraphQL cannot do:
(`vue/public/job-capture.user.js`, installed from the tracker page) that adds (`vue/public/job-capture.user.js`, installed from the tracker page) that adds
the posting open in the browser to the job tracker. the posting open in the browser to the job tracker.
- **Auth** is `Authorization: Bearer $JOB_CAPTURE_TOKEN`, checked by - **Auth** is `Authorization: Bearer <token>`, checked by
`CaptureTokenMiddleware`. The token opens these three routes and nothing `CaptureTokenMiddleware`. The token opens these three routes and nothing
else — it cannot read the tracker or reach GraphQL. **An unset token turns else — it cannot read the tracker or reach GraphQL. **With no token
the routes off (503)**; it never means "no auth". generated the routes are off (503)**; that never means "no auth".
- **The token is generated in the admin panel**, not set in `.env`
(`services/capture_token.go`; `GET`/`POST`/`DELETE /admin/capture-token`,
cookie-authenticated like the rest of the admin group). It is 32 random
bytes, shown once; only its SHA-256 is kept, in
`/backend/token/job_capture_token.json` beside the OAuth tokens, so it
survives restarts and rebuilds. There is one token at a time: generating
again replaces it, which is how a leaked one is rotated.
- `GET /jobs/capture/status?url=` — is this posting already tracked, and at - `GET /jobs/capture/status?url=` — is this posting already tracked, and at
what status. Drives the script's badge. what status. Drives the script's badge.
- `POST /jobs/capture/extract` — page text in, `{jobTitle, company, location, - `POST /jobs/capture/extract` — page text in, `{jobTitle, company, location,
-2
View File
@@ -38,7 +38,6 @@ var configVars = []ConfigVar{
{"STEAM_API_KEY", "Steam status widget", false}, {"STEAM_API_KEY", "Steam status widget", false},
{"STEAM_ID", "Steam status widget", false}, {"STEAM_ID", "Steam status widget", false},
{"CLAUDE_API_KEY", "Email summarisation", false}, {"CLAUDE_API_KEY", "Email summarisation", false},
{"JOB_CAPTURE_TOKEN", "Job capture userscript", false},
{"EMAIL_BACKEND", "Email sync (graph/imap)", false}, {"EMAIL_BACKEND", "Email sync (graph/imap)", false},
{"MSGRAPH_CLIENT_ID", "Email sync (Microsoft Graph)", false}, {"MSGRAPH_CLIENT_ID", "Email sync (Microsoft Graph)", false},
{"MSGRAPH_CLIENT_SECRET", "Email sync (Microsoft Graph)", false}, {"MSGRAPH_CLIENT_SECRET", "Email sync (Microsoft Graph)", false},
@@ -82,7 +81,6 @@ func (store *Store) ConfigCheck(ctx *gin.Context) {
"SPOTIFY_CLIENT_SECRET": true, "SPOTIFY_CLIENT_SECRET": true,
"MSGRAPH_CLIENT_SECRET": true, "MSGRAPH_CLIENT_SECRET": true,
"CLAUDE_API_KEY": true, "CLAUDE_API_KEY": true,
"JOB_CAPTURE_TOKEN": true,
"STEAM_API_KEY": true, "STEAM_API_KEY": true,
"IMAP_PASSWORD": true, "IMAP_PASSWORD": true,
} }
+56 -8
View File
@@ -3,7 +3,6 @@ package handlers
import ( import (
"bytes" "bytes"
"context" "context"
"crypto/subtle"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@@ -56,25 +55,74 @@ const (
// rowingReadClient for why two minutes. // rowingReadClient for why two minutes.
var jobExtractClient = &http.Client{Timeout: 2 * time.Minute} var jobExtractClient = &http.Client{Timeout: 2 * time.Minute}
// CaptureTokenMiddleware guards the capture routes with JOB_CAPTURE_TOKEN, // CaptureTokenMiddleware guards the capture routes with the token generated
// presented as "Authorization: Bearer <token>". // in the admin panel (services.CaptureToken), presented as
// "Authorization: Bearer <token>".
// //
// An unset token turns the routes off (503) rather than leaving them open: // Until a token has been generated the routes are off (503) rather than
// an empty env var is the stack's failure mode for a forgotten secret (see // open; "no token" must never be satisfied by a request that sends none.
// .env.example), and comparing "" to "" would otherwise let everyone in.
func (store *Store) CaptureTokenMiddleware(ctx *gin.Context) { func (store *Store) CaptureTokenMiddleware(ctx *gin.Context) {
if store.JobCaptureToken == "" { if store.CaptureToken == nil {
ctx.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "job capture is not configured"}) ctx.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "job capture is not configured"})
return return
} }
if set, _ := store.CaptureToken.Status(); !set {
ctx.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "no capture token has been generated"})
return
}
presented, ok := strings.CutPrefix(ctx.GetHeader("Authorization"), "Bearer ") presented, ok := strings.CutPrefix(ctx.GetHeader("Authorization"), "Bearer ")
if !ok || subtle.ConstantTimeCompare([]byte(presented), []byte(store.JobCaptureToken)) != 1 { if !ok || !store.CaptureToken.Verify(presented) {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return return
} }
ctx.Next() ctx.Next()
} }
// The three handlers below manage that token from the admin panel. They sit
// in the cookie-authenticated admin group, not behind the token: the token
// must not be able to replace itself.
func captureTokenStatus(token *services.CaptureToken) gin.H {
set, createdAt := token.Status()
if !set {
return gin.H{"set": false}
}
return gin.H{"set": true, "createdAt": createdAt}
}
// GetCaptureToken backs GET /admin/capture-token: whether a token exists and
// when it was made. The token itself is not recoverable — only its hash is
// stored.
func (store *Store) GetCaptureToken(ctx *gin.Context) {
ctx.JSON(http.StatusOK, captureTokenStatus(store.CaptureToken))
}
// GenerateCaptureToken backs POST /admin/capture-token. It replaces any
// existing token, so the userscript must be reconfigured with the new one,
// and its response is the only time the token is ever sent anywhere.
func (store *Store) GenerateCaptureToken(ctx *gin.Context) {
token, createdAt, err := store.CaptureToken.Generate()
if err != nil {
log.Println("Generating capture token failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to store the token"})
return
}
// The response carries a credential; keep it out of any cache.
ctx.Header("Cache-Control", "no-store")
ctx.JSON(http.StatusOK, gin.H{"token": token, "createdAt": createdAt})
}
// RevokeCaptureToken backs DELETE /admin/capture-token, switching the capture
// routes off until a new token is generated.
func (store *Store) RevokeCaptureToken(ctx *gin.Context) {
if err := store.CaptureToken.Revoke(); err != nil {
log.Println("Revoking capture token failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to revoke the token"})
return
}
ctx.JSON(http.StatusOK, captureTokenStatus(store.CaptureToken))
}
// trackingParams are query parameters that say how the visitor arrived, not // trackingParams are query parameters that say how the visitor arrived, not
// which posting this is. Anything not listed is kept: ATS boards identify the // which posting this is. Anything not listed is kept: ATS boards identify the
// job in the query string often enough (gh_jid, jk, jobId) that dropping // job in the query string often enough (gh_jid, jk, jobId) that dropping
+109 -24
View File
@@ -6,11 +6,13 @@ import (
"errors" "errors"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"path/filepath"
"strings" "strings"
"testing" "testing"
"time" "time"
"adam-french.co.uk/backend/models" "adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@@ -22,40 +24,123 @@ import (
func TestCaptureTokenMiddleware(t *testing.T) { func TestCaptureTokenMiddleware(t *testing.T) {
gin.SetMode(gin.TestMode) gin.SetMode(gin.TestMode)
serve := func(store *Store, header string) int {
r := gin.New()
r.GET("/x", store.CaptureTokenMiddleware, func(ctx *gin.Context) { ctx.Status(http.StatusOK) })
req := httptest.NewRequest(http.MethodGet, "/x", nil)
if header != "" {
req.Header.Set("Authorization", header)
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
return rec.Code
}
newToken := func() *services.CaptureToken {
tok, err := services.InitCaptureToken(filepath.Join(t.TempDir(), "token.json"))
if err != nil {
t.Fatalf("InitCaptureToken: %v", err)
}
return tok
}
// The case the middleware exists to get right: with no token generated,
// a request presenting nothing (or an empty bearer) must not get in.
t.Run("no token generated switches the routes off", func(t *testing.T) {
store := &Store{CaptureToken: newToken()}
for _, header := range []string{"", "Bearer ", "Bearer anything"} {
if got := serve(store, header); got != http.StatusServiceUnavailable {
t.Fatalf("header %q: status = %d, want 503", header, got)
}
}
})
t.Run("a store built without the token service is off too", func(t *testing.T) {
if got := serve(&Store{}, "Bearer x"); got != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503", got)
}
})
store := &Store{CaptureToken: newToken()}
token, _, err := store.CaptureToken.Generate()
if err != nil {
t.Fatalf("Generate: %v", err)
}
cases := []struct { cases := []struct {
name string name string
configured string header string
header string want int
want int
}{ }{
{"the right token is let through", "s3cret", "Bearer s3cret", http.StatusOK}, {"the generated token is let through", "Bearer " + token, http.StatusOK},
{"a wrong token is refused", "s3cret", "Bearer nope", http.StatusUnauthorized}, {"a wrong token is refused", "Bearer nope", http.StatusUnauthorized},
{"no header is refused", "s3cret", "", http.StatusUnauthorized}, {"no header is refused", "", http.StatusUnauthorized},
{"the bare token without the scheme is refused", "s3cret", "s3cret", http.StatusUnauthorized}, {"the bare token without the scheme is refused", token, http.StatusUnauthorized},
// The case the middleware exists to get right: an unset token must
// not match the empty credential of an anonymous request.
{"an unset token switches the routes off", "", "", http.StatusServiceUnavailable},
{"an unset token is not matched by an empty bearer", "", "Bearer ", http.StatusServiceUnavailable},
} }
for _, c := range cases { for _, c := range cases {
t.Run(c.name, func(t *testing.T) { t.Run(c.name, func(t *testing.T) {
store := &Store{JobCaptureToken: c.configured} if got := serve(store, c.header); got != c.want {
r := gin.New() t.Fatalf("status = %d, want %d", got, c.want)
r.GET("/x", store.CaptureTokenMiddleware, func(ctx *gin.Context) { ctx.Status(http.StatusOK) })
req := httptest.NewRequest(http.MethodGet, "/x", nil)
if c.header != "" {
req.Header.Set("Authorization", c.header)
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
if rec.Code != c.want {
t.Fatalf("status = %d, want %d", rec.Code, c.want)
} }
}) })
} }
} }
// The admin endpoints, driven without the admin middleware (covered
// elsewhere): generate shows the token once, status never does, and a second
// generate or a revoke stops the first token working.
func TestCaptureTokenAdminEndpoints(t *testing.T) {
gin.SetMode(gin.TestMode)
tok, err := services.InitCaptureToken(filepath.Join(t.TempDir(), "token.json"))
if err != nil {
t.Fatalf("InitCaptureToken: %v", err)
}
store := &Store{CaptureToken: tok}
r := gin.New()
r.GET("/t", store.GetCaptureToken)
r.POST("/t", store.GenerateCaptureToken)
r.DELETE("/t", store.RevokeCaptureToken)
call := func(method string) (map[string]any, *httptest.ResponseRecorder) {
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest(method, "/t", nil))
if rec.Code != http.StatusOK {
t.Fatalf("%s: status = %d, body = %s", method, rec.Code, rec.Body)
}
var out map[string]any
json.Unmarshal(rec.Body.Bytes(), &out)
return out, rec
}
if out, _ := call(http.MethodGet); out["set"] != false {
t.Fatalf("fresh status = %v", out)
}
out, rec := call(http.MethodPost)
first, _ := out["token"].(string)
if !tok.Verify(first) {
t.Fatalf("generated token %q does not verify", first)
}
if rec.Header().Get("Cache-Control") != "no-store" {
t.Fatal("the response carrying the token must not be cacheable")
}
out, _ = call(http.MethodGet)
if out["set"] != true || out["createdAt"] == nil {
t.Fatalf("status after generate = %v", out)
}
if _, leaked := out["token"]; leaked {
t.Fatal("status must never return the token")
}
call(http.MethodPost)
if tok.Verify(first) {
t.Fatal("regenerating must invalidate the previous token")
}
if out, _ := call(http.MethodDelete); out["set"] != false {
t.Fatalf("status after revoke = %v", out)
}
}
func TestCanonicalJobURL(t *testing.T) { func TestCanonicalJobURL(t *testing.T) {
const linkedIn = "https://www.linkedin.com/jobs/view/4012345678/" const linkedIn = "https://www.linkedin.com/jobs/view/4012345678/"
cases := []struct { cases := []struct {
+4 -3
View File
@@ -39,9 +39,10 @@ type Store struct {
// photo (handle_rowing.go) and a job posting (handle_job_capture.go). // photo (handle_rowing.go) and a job posting (handle_job_capture.go).
PythonURL string PythonURL string
// Bearer token for the browser capture routes (handle_job_capture.go). // Bearer token for the browser capture routes (handle_job_capture.go),
// Empty means those routes are switched off, not open. // generated from the admin panel. Nil, or holding no token, means those
JobCaptureToken string // routes are switched off, not open.
CaptureToken *services.CaptureToken
// Cached "recently played" tracks, refreshed at most once a minute by the // Cached "recently played" tracks, refreshed at most once a minute by the
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can // GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
+13 -5
View File
@@ -6,7 +6,6 @@ import (
"io" "io"
"log" "log"
"os" "os"
"strings"
"time" "time"
"github.com/99designs/gqlgen/graphql/handler" "github.com/99designs/gqlgen/graphql/handler"
@@ -162,11 +161,15 @@ func main() {
loginLimiter := services.NewRateLimiter(5, time.Minute) loginLimiter := services.NewRateLimiter(5, time.Minute)
// JOB CAPTURE // JOB CAPTURE
// Trimmed because a stray newline in .env would otherwise make every // The userscript's bearer token is generated in the admin panel and kept
// request fail the comparison with nothing to show why. // (hashed) beside the OAuth tokens. A damaged file is logged, not fatal:
jobCaptureToken := strings.TrimSpace(os.Getenv("JOB_CAPTURE_TOKEN")) // capture stays off until a new token is generated.
captureToken, err := services.InitCaptureToken(services.CAPTURE_TOKEN_JSON_PATH)
if err != nil {
log.Println("Job capture token not loaded:", err)
}
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, EmailSync: emailSync, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL, JobCaptureToken: jobCaptureToken} store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, EmailSync: emailSync, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL, CaptureToken: captureToken}
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in // Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
// the Gin context, so the order in the admin group matters. // the Gin context, so the order in the admin group matters.
@@ -226,6 +229,11 @@ func main() {
// ADMIN DIAGNOSTICS: env-var checklist and log tail for the admin panel. // ADMIN DIAGNOSTICS: env-var checklist and log tail for the admin panel.
admin.GET("/admin/config", store.ConfigCheck) admin.GET("/admin/config", store.ConfigCheck)
admin.GET("/admin/logs", store.Logs) admin.GET("/admin/logs", store.Logs)
// The job capture token is managed with the session cookie, never with
// the token itself.
admin.GET("/admin/capture-token", store.GetCaptureToken)
admin.POST("/admin/capture-token", store.GenerateCaptureToken)
admin.DELETE("/admin/capture-token", store.RevokeCaptureToken)
// GRAPHQL // GRAPHQL
// GraphQL is assembled by hand rather than with handler.NewDefaultServer // GraphQL is assembled by hand rather than with handler.NewDefaultServer
+133
View File
@@ -0,0 +1,133 @@
package services
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sync"
"time"
)
// CAPTURE_TOKEN_JSON_PATH sits beside the Spotify and Graph tokens, in the
// directory docker-compose bind-mounts so that it survives a rebuild.
const CAPTURE_TOKEN_JSON_PATH = "/backend/token/job_capture_token.json"
// CaptureToken holds the bearer token the job capture userscript presents
// (handlers/handle_job_capture.go). The token is minted from the admin panel
// rather than set in .env, so it can be replaced without a redeploy when the
// browser profile holding it is lost.
//
// Only a SHA-256 of the token is kept, in memory and on disk: the token is
// shown once, when generated, and cannot be read back afterwards. A plain
// hash is enough because the token is 32 random bytes, not a password — there
// is nothing to brute-force.
//
// There is at most one token. Generating replaces it, which is also how a
// leaked one is rotated.
type CaptureToken struct {
path string
mu sync.RWMutex
hash []byte
createdAt time.Time
}
type captureTokenFile struct {
SHA256 string `json:"sha256"`
CreatedAt time.Time `json:"created_at"`
}
// InitCaptureToken loads the token file if there is one. A missing file is
// the normal first-run state and means "no token": the capture routes stay
// off until one is generated. A file that cannot be read or parsed is
// reported, and likewise leaves the routes off rather than open.
func InitCaptureToken(path string) (*CaptureToken, error) {
t := &CaptureToken{path: path}
raw, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) {
return t, nil
}
if err != nil {
return t, fmt.Errorf("reading capture token: %w", err)
}
var stored captureTokenFile
if err := json.Unmarshal(raw, &stored); err != nil {
return t, fmt.Errorf("parsing capture token: %w", err)
}
hash, err := hex.DecodeString(stored.SHA256)
if err != nil || len(hash) != sha256.Size {
return t, fmt.Errorf("capture token file holds no valid hash")
}
t.hash, t.createdAt = hash, stored.CreatedAt
return t, nil
}
// Generate mints a new token, replacing any existing one, and returns it.
// This is the only moment the token itself exists on the server.
//
// The file is written before the in-memory hash is swapped, so a failed write
// leaves the old token working instead of handing out one that would stop
// working at the next restart.
func (t *CaptureToken) Generate() (string, time.Time, error) {
raw := make([]byte, 32)
if _, err := rand.Read(raw); err != nil {
return "", time.Time{}, err
}
token := hex.EncodeToString(raw)
sum := sha256.Sum256([]byte(token))
now := time.Now().UTC()
data, err := json.MarshalIndent(captureTokenFile{SHA256: hex.EncodeToString(sum[:]), CreatedAt: now}, "", " ")
if err != nil {
return "", time.Time{}, err
}
if err := os.MkdirAll(filepath.Dir(t.path), 0755); err != nil {
return "", time.Time{}, fmt.Errorf("creating token directory: %w", err)
}
if err := os.WriteFile(t.path, data, 0600); err != nil {
return "", time.Time{}, fmt.Errorf("writing capture token: %w", err)
}
t.mu.Lock()
t.hash, t.createdAt = sum[:], now
t.mu.Unlock()
return token, now, nil
}
// Revoke deletes the token, switching the capture routes off.
func (t *CaptureToken) Revoke() error {
if err := os.Remove(t.path); err != nil && !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("removing capture token: %w", err)
}
t.mu.Lock()
t.hash, t.createdAt = nil, time.Time{}
t.mu.Unlock()
return nil
}
// Status reports whether a token exists and when it was generated.
func (t *CaptureToken) Status() (set bool, createdAt time.Time) {
t.mu.RLock()
defer t.mu.RUnlock()
return t.hash != nil, t.createdAt
}
// Verify reports whether presented is the current token. With no token it is
// false for every input, the empty string included.
func (t *CaptureToken) Verify(presented string) bool {
t.mu.RLock()
defer t.mu.RUnlock()
if t.hash == nil {
return false
}
sum := sha256.Sum256([]byte(presented))
return subtle.ConstantTimeCompare(sum[:], t.hash) == 1
}
+126
View File
@@ -0,0 +1,126 @@
package services
import (
"os"
"path/filepath"
"strings"
"testing"
)
func newCaptureToken(t *testing.T) (*CaptureToken, string) {
t.Helper()
// A nested path: the token directory may not exist on a fresh checkout.
path := filepath.Join(t.TempDir(), "token", "job_capture_token.json")
tok, err := InitCaptureToken(path)
if err != nil {
t.Fatalf("InitCaptureToken: %v", err)
}
return tok, path
}
func TestCaptureTokenStartsUnsetAndRejectsEverything(t *testing.T) {
tok, _ := newCaptureToken(t)
if set, _ := tok.Status(); set {
t.Fatal("a fresh store reports a token")
}
// The empty string is the credential of a request with no token at all.
for _, presented := range []string{"", "anything"} {
if tok.Verify(presented) {
t.Fatalf("Verify(%q) passed with no token generated", presented)
}
}
}
func TestCaptureTokenGenerateVerifyAndRotate(t *testing.T) {
tok, path := newCaptureToken(t)
first, createdAt, err := tok.Generate()
if err != nil {
t.Fatalf("Generate: %v", err)
}
if len(first) != 64 {
t.Fatalf("token is %d chars, want 64 hex chars (32 bytes)", len(first))
}
if set, at := tok.Status(); !set || !at.Equal(createdAt) {
t.Fatalf("Status = %v, %v", set, at)
}
if !tok.Verify(first) || tok.Verify(first+"x") || tok.Verify("") {
t.Fatal("Verify does not accept exactly the generated token")
}
// The file must be useless to someone who reads it, and private anyway.
raw, err := os.ReadFile(path)
if err != nil {
t.Fatalf("reading token file: %v", err)
}
if strings.Contains(string(raw), first) {
t.Fatal("the token itself was written to disk")
}
if info, _ := os.Stat(path); info.Mode().Perm() != 0o600 {
t.Fatalf("token file mode = %v, want 0600", info.Mode().Perm())
}
second, _, err := tok.Generate()
if err != nil {
t.Fatalf("Generate: %v", err)
}
if tok.Verify(first) || !tok.Verify(second) {
t.Fatal("generating again must replace the old token")
}
}
func TestCaptureTokenSurvivesRestart(t *testing.T) {
tok, path := newCaptureToken(t)
token, createdAt, _ := tok.Generate()
reloaded, err := InitCaptureToken(path)
if err != nil {
t.Fatalf("InitCaptureToken: %v", err)
}
if !reloaded.Verify(token) {
t.Fatal("token no longer verifies after a reload")
}
if _, at := reloaded.Status(); !at.Equal(createdAt) {
t.Fatalf("createdAt = %v, want %v", at, createdAt)
}
}
func TestCaptureTokenRevoke(t *testing.T) {
tok, path := newCaptureToken(t)
token, _, _ := tok.Generate()
if err := tok.Revoke(); err != nil {
t.Fatalf("Revoke: %v", err)
}
if tok.Verify(token) {
t.Fatal("token still verifies after Revoke")
}
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatal("token file still exists, so the token would return on restart")
}
if err := tok.Revoke(); err != nil {
t.Fatalf("revoking with nothing to revoke: %v", err)
}
}
// A damaged file must leave the routes off, never open and never fatal.
func TestCaptureTokenCorruptFile(t *testing.T) {
for name, content := range map[string]string{
"not json": "{",
"not a hash": `{"sha256": "zz"}`,
"short hash": `{"sha256": "abcd"}`,
"empty object": `{}`,
} {
t.Run(name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "t.json")
os.WriteFile(path, []byte(content), 0o600)
tok, err := InitCaptureToken(path)
if err == nil {
t.Fatal("expected an error")
}
if tok == nil || tok.Verify("") {
t.Fatal("a corrupt file must yield a usable store that rejects everything")
}
})
}
}
+4 -4
View File
@@ -1,7 +1,7 @@
// ==UserScript== // ==UserScript==
// @name Job tracker capture // @name Job tracker capture
// @namespace https://www.adam-french.co.uk/ // @namespace https://www.adam-french.co.uk/
// @version 1.0.0 // @version 1.0.1
// @description Add the job posting you are looking at to the tracker at /cv/jobs. // @description Add the job posting you are looking at to the tracker at /cv/jobs.
// @match *://*/* // @match *://*/*
// @noframes // @noframes
@@ -30,8 +30,8 @@
* *
* CONFIGURE: Violentmonkey menu -> "Configure job capture". It asks for the * CONFIGURE: Violentmonkey menu -> "Configure job capture". It asks for the
* API base (default below; http://localhost/api for the dev stack) and the * API base (default below; http://localhost/api for the dev stack) and the
* token, which is the server's JOB_CAPTURE_TOKEN. Both are kept in * token, which is generated on the site's admin panel (/admin, "Job capture
* Violentmonkey's own storage. THE TOKEN MUST NEVER BE WRITTEN INTO THIS FILE: * token") and shown there once. Both are kept in Violentmonkey's own storage. THE TOKEN MUST NEVER BE WRITTEN INTO THIS FILE:
* it is served publicly. * it is served publicly.
* *
* WHAT RUNS WHERE: the script matches every site so that the menu command * WHAT RUNS WHERE: the script matches every site so that the menu command
@@ -135,7 +135,7 @@
); );
if (base === null) return false; if (base === null) return false;
const token = prompt( const token = prompt(
"Capture token (the server's JOB_CAPTURE_TOKEN)", "Capture token (generate one on the site's admin panel)",
config.token, config.token,
); );
if (token === null) return false; if (token === null) return false;
+2 -2
View File
@@ -481,13 +481,13 @@ onMounted(() => {
<div class="ja-header-right"> <div class="ja-header-right">
<!-- A plain link to a static file: Violentmonkey intercepts any <!-- A plain link to a static file: Violentmonkey intercepts any
navigation to a URL ending in .user.js and offers to install it. navigation to a URL ending in .user.js and offers to install it.
The token it then asks for is the server's JOB_CAPTURE_TOKEN. --> The token it then asks for is generated on the admin panel. -->
<a <a
class="cv-btn" class="cv-btn"
href="/job-capture.user.js" href="/job-capture.user.js"
target="_blank" target="_blank"
rel="noopener" rel="noopener"
title="Violentmonkey userscript that adds the job you are viewing. After installing, set the capture token from its menu: Configure job capture." title="Violentmonkey userscript that adds the job you are viewing. After installing, generate a capture token on the admin panel and paste it into the script's menu: Configure job capture."
> >
Install capture script Install capture script
</a> </a>
+140 -4
View File
@@ -1,10 +1,14 @@
<script setup> <script setup>
/** /**
* Admin panel: configuration checklist and log tail. * Admin panel: configuration checklist, the job capture token, and log tail.
* *
* Both come from the backend as JSON (GET /api/admin/config, GET * All of it comes from the backend as JSON (GET /api/admin/config,
* /api/admin/logs). Nothing here is GraphQL — the data is process * /api/admin/capture-token, /api/admin/logs). Nothing here is GraphQL — the
* environment and filesystem, not the site's data model. * data is process environment and filesystem, not the site's data model.
*
* The capture token is the credential the job capture userscript
* (public/job-capture.user.js) sends. The server keeps only a hash, so the
* token can be shown exactly once, in the response to generating it.
* *
* The log tail loads lazily (only when the Logs tab is selected first) * The log tail loads lazily (only when the Logs tab is selected first)
* because reading the file on every /admin visit would be waste; an admin * because reading the file on every /admin visit would be waste; an admin
@@ -45,6 +49,75 @@ async function fetchLogs() {
} }
} }
// Job capture token. `newToken` holds a just-generated token and lives only in
// this component's memory: leaving the tab is the end of it.
const capture = ref(null);
const captureError = ref("");
const captureBusy = ref(false);
const newToken = ref("");
const copied = ref(false);
async function fetchCaptureToken() {
try {
capture.value = (await axios.get("/api/admin/capture-token")).data;
captureError.value = "";
} catch (err) {
captureError.value =
err.response?.data?.error || "Failed to load the capture token state";
}
}
async function generateCaptureToken() {
// Generating replaces: an installed script stops working until it is
// given the new token, which is worth a pause when one already exists.
if (
capture.value?.set &&
!confirm(
"Replace the existing capture token? The installed userscript will stop working until you paste the new one into it.",
)
)
return;
captureBusy.value = true;
try {
const res = await axios.post("/api/admin/capture-token");
newToken.value = res.data.token;
capture.value = { set: true, createdAt: res.data.createdAt };
copied.value = false;
captureError.value = "";
} catch (err) {
captureError.value =
err.response?.data?.error || "Failed to generate a token";
} finally {
captureBusy.value = false;
}
}
async function revokeCaptureToken() {
if (!confirm("Revoke the capture token? The userscript will stop working."))
return;
captureBusy.value = true;
try {
capture.value = (await axios.delete("/api/admin/capture-token")).data;
newToken.value = "";
captureError.value = "";
} catch (err) {
captureError.value =
err.response?.data?.error || "Failed to revoke the token";
} finally {
captureBusy.value = false;
}
}
async function copyToken() {
try {
await navigator.clipboard.writeText(newToken.value);
copied.value = true;
} catch {
// Clipboard access can be refused; the token is on screen to select.
captureError.value = "Could not copy — select the token and copy it by hand.";
}
}
const blank = computed(() => const blank = computed(() =>
vars.value.filter((v) => !v.set), vars.value.filter((v) => !v.set),
); );
@@ -60,6 +133,7 @@ const shownLines = computed(() => {
onMounted(() => { onMounted(() => {
fetchConfig(); fetchConfig();
fetchCaptureToken();
fetchLogs(); fetchLogs();
}); });
</script> </script>
@@ -95,6 +169,44 @@ onMounted(() => {
</tbody> </tbody>
</table> </table>
<h1>Job capture token</h1>
<p class="hint">
The credential for the
<a href="/job-capture.user.js" target="_blank" rel="noopener"
>job capture userscript</a
>. Generate one, then paste it into the script's
<em>Configure job capture</em> menu command. Only a hash is stored, so a
token is shown once and cannot be recovered — generate again to replace
it.
</p>
<p v-if="captureError" class="error">{{ captureError }}</p>
<template v-if="capture">
<p v-if="capture.set">
A token is active, generated
{{ new Date(capture.createdAt).toLocaleString() }}.
</p>
<p v-else class="warn">
No token — the capture script cannot reach the tracker.
</p>
<div v-if="newToken" class="token-box">
<p class="hint">Copy this now. It will not be shown again.</p>
<code class="token">{{ newToken }}</code>
<Button @click="copyToken">{{ copied ? "Copied" : "Copy" }}</Button>
</div>
<div class="token-controls">
<Button :disabled="captureBusy" @click="generateCaptureToken">
{{ capture.set ? "Regenerate" : "Generate token" }}
</Button>
<Button
v-if="capture.set"
:disabled="captureBusy"
@click="revokeCaptureToken"
>
Revoke
</Button>
</div>
</template>
<h1>Logs</h1> <h1>Logs</h1>
<p class="hint"> <p class="hint">
Tail of the backend log (up to 500 lines): HTTP traffic and application Tail of the backend log (up to 500 lines): HTTP traffic and application
@@ -149,6 +261,30 @@ td {
opacity: 0.75; opacity: 0.75;
} }
.token-box {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
padding: 8px;
border: 1px solid var(--color-quaternary);
}
.token-box .hint {
flex-basis: 100%;
margin: 0;
}
.token {
flex: 1;
min-width: 0;
font-size: 0.8rem;
word-break: break-all;
user-select: all;
}
.token-controls {
display: flex;
gap: 12px;
}
.log-controls { .log-controls {
display: flex; display: flex;
justify-content: flex-end; justify-content: flex-end;