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
+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")
}
})
}
}