feat(backend): per-Reader userscript credential with UI install and rotation (#24)
Each Reader's userscript credential is derived from TOKEN_KEY, their Discord id and a token epoch (HMAC-SHA256, hex); only its SHA-256 sits in readers.token_sha256, so install URLs survive restarts while a database leak yields nothing but hashes. One credential authenticates the script download path and the API bearer header. - internal/token: derivation + hashing; migration 0006 adds token_epoch - seed refreshes the owner's epoch-0 hash only before first rotation - httpmw.Auth resolves the acting Reader from the credential hash and stashes it in the request context; the retired API_TOKEN resolves to the owner until API_TOKEN_GRACE_UNTIL, logged per use, on both the bearer and script-download paths - userscript handler renders the bindmounted file with the resolved Reader's credential substituted for __API_TOKEN__; a legacy-path request during grace serves the derived credential, so devices self-migrate on their next update poll - web UI: Userscripts panel with session-gated install endpoints that render the script directly (credential never in markup, address bar or a redirect) and confirm-gated rotation; atomic epoch bump + hash rewrite in the store - both userscripts carry __API_TOKEN__ placeholders; the committed global-token literal is removed (rotating at deploy retires it for real — it survives in git history) - env: TOKEN_KEY required, API_TOKEN/API_TOKEN_GRACE_UNTIL retire the legacy credential; docs and compose updated
This commit is contained in:
@@ -7,15 +7,13 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"bookmarkmanager/backend/internal/httpmw"
|
||||
"bookmarkmanager/backend/internal/store"
|
||||
)
|
||||
|
||||
// Handler serves the userscript-facing JSON bookmark API.
|
||||
type Handler struct {
|
||||
Store *store.Store
|
||||
// ReaderID is the Reader this request acts as. Authentication is still the
|
||||
// single global token, so that is always the seeded owner (issue #22).
|
||||
ReaderID int64
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
@@ -30,7 +28,7 @@ func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
|
||||
// List returns all bookmarks of the acting Reader. GET /bookmarks
|
||||
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
||||
items, err := h.Store.List(h.ReaderID)
|
||||
items, err := h.Store.List(httpmw.ReaderID(r))
|
||||
if err != nil {
|
||||
log.Printf("list: %v", err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
@@ -94,7 +92,7 @@ func (h *Handler) Put(w http.ResponseWriter, r *http.Request) {
|
||||
// reading progress actually moved. Any client value is ignored.
|
||||
b.UpdatedAt = time.Now().UnixMilli()
|
||||
|
||||
stored, err := h.Store.Upsert(h.ReaderID, b)
|
||||
stored, err := h.Store.Upsert(httpmw.ReaderID(r), b)
|
||||
if err != nil {
|
||||
log.Printf("upsert: %v", err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
@@ -112,7 +110,7 @@ func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "missing key", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := h.Store.Delete(h.ReaderID, key); err != nil {
|
||||
if err := h.Store.Delete(httpmw.ReaderID(r), key); err != nil {
|
||||
log.Printf("delete: %v", err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
|
||||
@@ -2,28 +2,68 @@ package httpmw
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"bookmarkmanager/backend/internal/store"
|
||||
"bookmarkmanager/backend/internal/token"
|
||||
)
|
||||
|
||||
const bearerPrefix = "Bearer "
|
||||
|
||||
// Auth guards a handler with a constant-time bearer-token check.
|
||||
func Auth(token string, next http.Handler) http.Handler {
|
||||
want := []byte(token)
|
||||
type ctxKey int
|
||||
|
||||
// readerCtxKey is where Auth stashes the authenticated Reader id.
|
||||
const readerCtxKey ctxKey = iota
|
||||
|
||||
// ReaderID returns the Reader id Auth authenticated, for handlers that take
|
||||
// the acting Reader from the request rather than from a fixed field.
|
||||
func ReaderID(r *http.Request) int64 { return r.Context().Value(readerCtxKey).(int64) }
|
||||
|
||||
// ResolveReader maps a presented credential to a Reader. The credential is
|
||||
// hashed and matched against readers.token_sha256 — an equality on 32-byte
|
||||
// values, never a comparison of the credential itself — and, during the
|
||||
// cutover window, the retired global token resolves to the owner. Every
|
||||
// legacy acceptance is logged so the window can be confirmed empty before
|
||||
// the token is removed. The same resolution backs the API bearer header and
|
||||
// the userscript download path, so the window covers both.
|
||||
func ResolveReader(s *store.Store, legacy string, graceUntil time.Time, cred string) (int64, bool) {
|
||||
if readerID, ok, err := s.ReaderIDForTokenHash(token.Hash(cred)); err != nil {
|
||||
log.Printf("auth: reader lookup: %v", err)
|
||||
return 0, false
|
||||
} else if ok {
|
||||
return readerID, true
|
||||
}
|
||||
|
||||
if legacy != "" && time.Now().Before(graceUntil) &&
|
||||
subtle.ConstantTimeCompare([]byte(cred), []byte(legacy)) == 1 {
|
||||
log.Printf("auth: retired global token accepted for owner reader %d (grace until %s)",
|
||||
s.OwnerID(), graceUntil.Format(time.RFC3339))
|
||||
return s.OwnerID(), true
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// Auth guards a handler with a per-Reader bearer credential. The acting
|
||||
// Reader travels in the request context, so a handler scopes every store call
|
||||
// to exactly the Reader that authenticated.
|
||||
func Auth(s *store.Store, legacy string, graceUntil time.Time, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(h, bearerPrefix) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
got := []byte(strings.TrimPrefix(h, bearerPrefix))
|
||||
if subtle.ConstantTimeCompare(got, want) != 1 {
|
||||
readerID, ok := ResolveReader(s, legacy, graceUntil, strings.TrimPrefix(h, bearerPrefix))
|
||||
if !ok {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), readerCtxKey, readerID)))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Rotation is an epoch bump: a Reader's credential is derived from the
|
||||
-- deployment secret, their Discord id and this epoch, so bumping it issues a
|
||||
-- new credential and the rewritten token_sha256 invalidates the old one the
|
||||
-- moment the transaction commits. The seed's ON CONFLICT refresh (Store.Open)
|
||||
-- is gated on this being 0, so a restart can never undo a rotation by
|
||||
-- restoring the epoch-0 hash.
|
||||
ALTER TABLE readers ADD COLUMN token_epoch bigint NOT NULL DEFAULT 0;
|
||||
@@ -171,12 +171,12 @@ const seriesColumns = `s.site, s.series_id, s.title, s.series_url, s.cover,
|
||||
|
||||
// Owner is the person running the service: the first Reader, and the only one
|
||||
// until registration exists. The seed makes sure exactly one readers row
|
||||
// matches their Discord ID, carrying the SHA-256 of their userscript token —
|
||||
// which today is the global API token.
|
||||
// matches their Discord ID, carrying the SHA-256 of their epoch-0 userscript
|
||||
// credential (derived by internal/token, not the retired global token).
|
||||
type Owner struct {
|
||||
DiscordID string
|
||||
// TokenHash is the SHA-256 of the userscript token; the array shape makes
|
||||
// it a compile error to store anything that is not a hash.
|
||||
// TokenHash is the SHA-256 of the epoch-0 credential; the array shape
|
||||
// makes it a compile error to store anything that is not a hash.
|
||||
TokenHash [32]byte
|
||||
}
|
||||
|
||||
@@ -189,10 +189,69 @@ type Store struct {
|
||||
ownerID int64
|
||||
}
|
||||
|
||||
// OwnerID returns the seeded owner Reader's id — the Reader every request
|
||||
// acts as while the global token is still the only credential.
|
||||
// OwnerID returns the seeded owner Reader's id — the Reader the retired
|
||||
// global token resolves to during the grace window, and the only Reader while
|
||||
// registration is closed.
|
||||
func (s *Store) OwnerID() int64 { return s.ownerID }
|
||||
|
||||
// ReaderIDForTokenHash resolves the Reader whose stored credential hash
|
||||
// matches, reporting absence with ok=false. The comparison is an equality on
|
||||
// the 32-byte SHA-256 of the presented credential — never on the credential
|
||||
// itself — and the indexed lookup reveals only whether some Reader matches,
|
||||
// which the 401/200 split has to reveal anyway. An attacker's probe is the
|
||||
// hash of their guess, so even the index's prefix comparisons leak nothing
|
||||
// about the real credential.
|
||||
func (s *Store) ReaderIDForTokenHash(hash [32]byte) (int64, bool, error) {
|
||||
var id int64
|
||||
err := s.db.QueryRow(
|
||||
`SELECT id FROM readers WHERE token_sha256 = $1`, hash[:]).Scan(&id)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return 0, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return 0, false, fmt.Errorf("reader by token hash: %w", err)
|
||||
}
|
||||
return id, true, nil
|
||||
}
|
||||
|
||||
// ReaderTokenInfo returns the identity halves a Reader's credential is
|
||||
// derived from (internal/token.Token): their Discord id and token epoch. The
|
||||
// web UI needs these to rebuild the install URL — the only place a credential
|
||||
// is ever produced in plaintext.
|
||||
func (s *Store) ReaderTokenInfo(readerID int64) (string, int64, error) {
|
||||
var (
|
||||
discordID string
|
||||
epoch int64
|
||||
)
|
||||
err := s.db.QueryRow(
|
||||
`SELECT discord_id, token_epoch FROM readers WHERE id = $1`, readerID).
|
||||
Scan(&discordID, &epoch)
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("reader %d token info: %w", readerID, err)
|
||||
}
|
||||
return discordID, epoch, nil
|
||||
}
|
||||
|
||||
// RotateToken bumps a Reader's token epoch and rewrites the stored hash in
|
||||
// one statement, so the new hash always matches the new epoch. expectedEpoch
|
||||
// is the epoch the caller derived newHash for (ReaderTokenInfo + 1); a
|
||||
// concurrent rotation — or an unknown reader — leaves the row untouched and
|
||||
// is reported as an error rather than silently succeeding.
|
||||
func (s *Store) RotateToken(readerID, expectedEpoch int64, newHash [32]byte) error {
|
||||
var epoch int64
|
||||
err := s.db.QueryRow(`
|
||||
UPDATE readers SET token_epoch = token_epoch + 1, token_sha256 = $3
|
||||
WHERE id = $1 AND token_epoch = $2
|
||||
RETURNING token_epoch`, readerID, expectedEpoch, newHash[:]).Scan(&epoch)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return fmt.Errorf("rotate token for reader %d: concurrent rotation or unknown reader", readerID)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("rotate token for reader %d: %w", readerID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// readersMigration is the version that creates the readers table. The owner
|
||||
// seed runs between two migrate passes, so that the run-once migration which
|
||||
// attaches existing bookmarks (0004) finds the owner row.
|
||||
@@ -217,6 +276,10 @@ func Open(url string, owner Owner) (*Store, error) {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("migrate schema: %w", err)
|
||||
}
|
||||
// The owner row must exist before 0004 attaches the existing bookmarks to
|
||||
// it. The hash refresh is a separate statement after all migrations: the
|
||||
// token_epoch column 0006 adds does not exist yet at this point, and the
|
||||
// refresh only ever concerns rows that have never been rotated.
|
||||
if err := seedOwner(db, owner); err != nil {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("seed owner: %w", err)
|
||||
@@ -225,6 +288,10 @@ func Open(url string, owner Owner) (*Store, error) {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("migrate: %w", err)
|
||||
}
|
||||
if err := refreshOwnerToken(db, owner); err != nil {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("refresh owner token: %w", err)
|
||||
}
|
||||
var ownerID int64
|
||||
if err := db.QueryRow(
|
||||
`SELECT id FROM readers WHERE discord_id = $1`, owner.DiscordID).Scan(&ownerID); err != nil {
|
||||
@@ -234,19 +301,36 @@ func Open(url string, owner Owner) (*Store, error) {
|
||||
return &Store{db: db, ownerID: ownerID}, nil
|
||||
}
|
||||
|
||||
// seedOwner makes sure the configured owner exists as exactly one readers row,
|
||||
// and keeps its token hash current on every start: rotating the userscript
|
||||
// token must refresh the hash, or the stored credential goes stale.
|
||||
// seedOwner makes sure the configured owner exists as exactly one readers row.
|
||||
// The hash is only ever written here for a brand-new row; existing rows keep
|
||||
// what they have until refreshOwnerToken decides otherwise, so the seed can
|
||||
// never clobber a rotation.
|
||||
func seedOwner(db *sql.DB, o Owner) error {
|
||||
if _, err := db.Exec(`
|
||||
INSERT INTO readers (discord_id, token_sha256) VALUES ($1, $2)
|
||||
ON CONFLICT (discord_id) DO UPDATE SET token_sha256 = EXCLUDED.token_sha256`,
|
||||
ON CONFLICT (discord_id) DO NOTHING`,
|
||||
o.DiscordID, o.TokenHash[:]); err != nil {
|
||||
return fmt.Errorf("seed owner: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// refreshOwnerToken brings a never-rotated owner row's hash current with the
|
||||
// configured credential. That is the cutover path: a database seeded under
|
||||
// the retired global token still carries its hash at epoch 0, and the
|
||||
// epoch-0 derivation is the caller's TokenHash. A rotated row (epoch > 0) is
|
||||
// left alone — a restart must not resurrect the old credential by
|
||||
// overwriting the hash a rotation wrote.
|
||||
func refreshOwnerToken(db *sql.DB, o Owner) error {
|
||||
if _, err := db.Exec(`
|
||||
UPDATE readers SET token_sha256 = $2
|
||||
WHERE discord_id = $1 AND token_epoch = 0`,
|
||||
o.DiscordID, o.TokenHash[:]); err != nil {
|
||||
return fmt.Errorf("refresh owner token: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// migrate applies every embedded migration this database has not recorded, in
|
||||
// filename order, each in its own transaction. upto caps the highest version
|
||||
// applied; 0 means all. Files are named "<version>_<name>.sql" and are
|
||||
|
||||
@@ -75,6 +75,92 @@ func TestOpenIsIdempotent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The hash lookup is the whole authentication path: the store resolves a
|
||||
// Reader from the SHA-256 of their presented credential, and nothing else.
|
||||
func TestReaderIDForTokenHash(t *testing.T) {
|
||||
store := newTestStore(t)
|
||||
ownerHash := sha256.Sum256([]byte("owner-token-hash"))
|
||||
|
||||
id, ok, err := store.ReaderIDForTokenHash(ownerHash)
|
||||
if err != nil {
|
||||
t.Fatalf("ReaderIDForTokenHash: %v", err)
|
||||
}
|
||||
if !ok || id != store.OwnerID() {
|
||||
t.Fatalf("owner lookup = (%d, %v), want (%d, true)", id, ok, store.OwnerID())
|
||||
}
|
||||
|
||||
if _, ok, err := store.ReaderIDForTokenHash(sha256.Sum256([]byte("nope"))); err != nil {
|
||||
t.Fatalf("miss: %v", err)
|
||||
} else if ok {
|
||||
t.Fatal("unknown hash resolved to a Reader")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReaderTokenInfo(t *testing.T) {
|
||||
store := newTestStore(t)
|
||||
discordID, epoch, err := store.ReaderTokenInfo(store.OwnerID())
|
||||
if err != nil {
|
||||
t.Fatalf("ReaderTokenInfo: %v", err)
|
||||
}
|
||||
if discordID != testOwner.DiscordID || epoch != 0 {
|
||||
t.Fatalf("ReaderTokenInfo = (%q, %d), want (%q, 0)", discordID, epoch, testOwner.DiscordID)
|
||||
}
|
||||
}
|
||||
|
||||
// Rotation swaps the stored hash and bumps the epoch in one step, and the
|
||||
// seed must not undo it: a restart re-runs seedOwner, which refreshes the
|
||||
// epoch-0 hash only while the row has never been rotated.
|
||||
func TestRotateTokenInvalidatesOldAndSurvivesRestart(t *testing.T) {
|
||||
url := pgtest.URL(t)
|
||||
store, err := Open(url, testOwner)
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
|
||||
oldHash := sha256.Sum256([]byte("owner-token-hash"))
|
||||
newHash := sha256.Sum256([]byte("rotated-token-hash"))
|
||||
if err := store.RotateToken(store.OwnerID(), 0, newHash); err != nil {
|
||||
t.Fatalf("RotateToken: %v", err)
|
||||
}
|
||||
// A second rotation against the stale epoch is refused: the stored hash
|
||||
// must never describe a different epoch than the column says.
|
||||
if err := store.RotateToken(store.OwnerID(), 0, sha256.Sum256([]byte("third-hash"))); err == nil {
|
||||
t.Fatal("stale-epoch rotation succeeded, want error")
|
||||
}
|
||||
if _, ok, err := store.ReaderIDForTokenHash(oldHash); err != nil {
|
||||
t.Fatalf("old lookup: %v", err)
|
||||
} else if ok {
|
||||
t.Fatal("old hash still resolves after rotation")
|
||||
}
|
||||
if id, ok, err := store.ReaderIDForTokenHash(newHash); err != nil {
|
||||
t.Fatalf("new lookup: %v", err)
|
||||
} else if !ok || id != store.OwnerID() {
|
||||
t.Fatalf("new hash resolved to (%d, %v), want owner", id, ok)
|
||||
}
|
||||
if _, epoch, err := store.ReaderTokenInfo(store.OwnerID()); err != nil {
|
||||
t.Fatalf("ReaderTokenInfo: %v", err)
|
||||
} else if epoch != 1 {
|
||||
t.Fatalf("epoch = %d after rotation, want 1", epoch)
|
||||
}
|
||||
store.Close()
|
||||
|
||||
reopened, err := Open(url, testOwner)
|
||||
if err != nil {
|
||||
t.Fatalf("reopen: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { reopened.Close() })
|
||||
if _, ok, err := reopened.ReaderIDForTokenHash(oldHash); err != nil {
|
||||
t.Fatalf("old lookup after reopen: %v", err)
|
||||
} else if ok {
|
||||
t.Fatal("restart resurrected the pre-rotation hash")
|
||||
}
|
||||
if _, ok, err := reopened.ReaderIDForTokenHash(newHash); err != nil {
|
||||
t.Fatalf("new lookup after reopen: %v", err)
|
||||
} else if !ok {
|
||||
t.Fatal("restart dropped the rotated hash")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreGet(t *testing.T) {
|
||||
store := newTestStore(t)
|
||||
if _, err := store.Upsert(store.OwnerID(), Bookmark{
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Token derives one Reader's userscript credential from the deployment
|
||||
// secret, the Reader's Discord id and their token epoch.
|
||||
//
|
||||
// The credential is deterministic rather than stored random because the
|
||||
// server must be able to rebuild the install URL after a restart while the
|
||||
// database holds only hashes: a random token with no plaintext copy anywhere
|
||||
// would be unreconstructible, and keeping plaintext in memory would break
|
||||
// every install link on restart. HMAC output is high-entropy, indistinguishable
|
||||
// from random to anyone without the secret, and changes whenever the epoch
|
||||
// does — which is what rotation is. The stored form is Hash of this value,
|
||||
// so a database leak yields nothing but hashes of unguessable strings.
|
||||
func Token(key []byte, discordID string, epoch int64) string {
|
||||
mac := hmac.New(sha256.New, key)
|
||||
// The separator is unambiguous: discord ids are decimal snowflakes and
|
||||
// epochs are plain integers, so no two (id, epoch) pairs can collide.
|
||||
mac.Write([]byte(discordID))
|
||||
mac.Write([]byte{0})
|
||||
mac.Write([]byte(strconv.FormatInt(epoch, 10)))
|
||||
return hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// Hash is the SHA-256 of a credential — the only form that ever touches the
|
||||
// database (readers.token_sha256). SHA-256 rather than a password hash is
|
||||
// deliberate: these are unguessable values with nothing to brute-force, so a
|
||||
// slow hash would only add per-request cost.
|
||||
func Hash(cred string) [32]byte {
|
||||
return sha256.Sum256([]byte(cred))
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTokenDeterministicPerReaderAndEpoch(t *testing.T) {
|
||||
key := []byte("deployment-secret")
|
||||
a := Token(key, "reader-1", 0)
|
||||
b := Token(key, "reader-1", 0)
|
||||
if a != b {
|
||||
t.Fatal("same (reader, epoch) derived different credentials")
|
||||
}
|
||||
if a == Token(key, "reader-2", 0) {
|
||||
t.Fatal("different readers derived the same credential")
|
||||
}
|
||||
if a == Token(key, "reader-1", 1) {
|
||||
t.Fatal("rotation epoch derived the same credential")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenChangesWithSecret(t *testing.T) {
|
||||
a := Token([]byte("key-1"), "reader-1", 0)
|
||||
b := Token([]byte("key-2"), "reader-1", 0)
|
||||
if a == b {
|
||||
t.Fatal("different secrets derived the same credential")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenFormat(t *testing.T) {
|
||||
cred := Token([]byte("key"), "reader-1", 0)
|
||||
// 32 bytes of HMAC-SHA256, hex-encoded: the length the install URL and
|
||||
// the committed placeholder both assume.
|
||||
if len(cred) != 64 {
|
||||
t.Fatalf("credential length = %d, want 64", len(cred))
|
||||
}
|
||||
for _, c := range cred {
|
||||
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
|
||||
t.Fatalf("credential contains non-hex byte %q", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashIsSha256OfCredential(t *testing.T) {
|
||||
cred := Token([]byte("key"), "reader-1", 0)
|
||||
got := Hash(cred)
|
||||
want := sha256.Sum256([]byte(cred))
|
||||
if !bytes.Equal(got[:], want[:]) {
|
||||
t.Fatal("Hash is not the SHA-256 of the credential")
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,25 @@
|
||||
package userscript
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"bytes"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"bookmarkmanager/backend/internal/httpmw"
|
||||
"bookmarkmanager/backend/internal/store"
|
||||
"bookmarkmanager/backend/internal/token"
|
||||
)
|
||||
|
||||
// tokenPlaceholder is what the bindmounted userscript carries where the
|
||||
// Reader's credential goes: in the API_TOKEN constant and in the @downloadURL
|
||||
// and @updateURL metadata lines. The handler substitutes the requesting
|
||||
// Reader's credential for it at serve time, so no credential literal is ever
|
||||
// committed or deployed, and each Reader's copy carries exactly their own.
|
||||
var tokenPlaceholder = []byte("__API_TOKEN__")
|
||||
|
||||
// versionLine matches the userscript metadata block's @version directive.
|
||||
var versionLine = regexp.MustCompile(`(?m)^// @version[ \t]+.*$`)
|
||||
|
||||
@@ -26,35 +37,76 @@ func stampVersion(src []byte, mod time.Time) []byte {
|
||||
return versionLine.ReplaceAll(src, []byte("// @version "+mod.UTC().Format("2006.01.02.1504")))
|
||||
}
|
||||
|
||||
// userscriptHandler serves the userscript to Violentmonkey's updater.
|
||||
// substituteToken replaces every tokenPlaceholder with the Reader's
|
||||
// credential. A file without the placeholder is returned unchanged so Render
|
||||
// can warn about it rather than silently serving a credential-less script.
|
||||
func substituteToken(src []byte, credential string) []byte {
|
||||
return bytes.ReplaceAll(src, tokenPlaceholder, []byte(credential))
|
||||
}
|
||||
|
||||
// Render writes one userscript file with the credential substituted and the
|
||||
// mtime-derived version stamped. Shared by the download path (Handler) and
|
||||
// the web UI's install endpoints, so both serve byte-identical scripts.
|
||||
//
|
||||
// The token lives in the path because the update poll sends no Authorization
|
||||
// header, and the file embeds API_TOKEN in plain text, so an open path would
|
||||
// hand that token to anyone who guessed the URL. A mismatch answers 404 rather
|
||||
// than 401: a prober learns nothing about whether the route exists.
|
||||
// The file is read per request — that is what lets a bindmounted copy be
|
||||
// edited on the host without a restart. It is ~50 KB and polled about once a
|
||||
// day.
|
||||
func Render(w http.ResponseWriter, r *http.Request, path, credential string) {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
log.Printf("userscript: stat %s: %v", path, err)
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
src, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
log.Printf("userscript: read %s: %v", path, err)
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
rendered := substituteToken(src, credential)
|
||||
if bytes.Equal(rendered, src) {
|
||||
// The bindmounted file was not built for per-Reader rendering. Serving
|
||||
// it as written is the operator's freedom, but a credential-less copy
|
||||
// is a deployment bug worth one log line — the symptom (silent 401s on
|
||||
// every device) is otherwise indistinguishable from a network fault.
|
||||
log.Printf("userscript: %s has no %s placeholder; serving as written", path, tokenPlaceholder)
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Write(stampVersion(rendered, info.ModTime()))
|
||||
}
|
||||
|
||||
// Handler serves the userscript to Violentmonkey's updater, rendered for the
|
||||
// Reader whose credential is in the path.
|
||||
//
|
||||
// The file is read per request — that is what lets a bindmounted copy be edited
|
||||
// on the host without a restart. It is ~50 KB and polled about once a day.
|
||||
func Handler(token, path string) http.HandlerFunc {
|
||||
// The credential lives in the path because the update poll sends no
|
||||
// Authorization header, and the rendered file embeds the credential in
|
||||
// plaintext, so an open path would hand it to anyone who guessed the URL. A
|
||||
// mismatch answers 404 rather than 401: a prober learns nothing about whether
|
||||
// the route exists. The same credential authenticates the API bearer header,
|
||||
// so the two are one secret with one blast radius.
|
||||
//
|
||||
// The credential substituted is the resolved Reader's derived one, not the
|
||||
// raw path segment: while the retired global token is still accepted during
|
||||
// the grace window (httpmw.ResolveReader), an already-installed script
|
||||
// polling its legacy URL is served a copy carrying the Reader's own
|
||||
// credential, so the next update poll migrates the device onto its per-Reader
|
||||
// path — the window empties itself instead of ending in a silent 401 for
|
||||
// every device that never visited the web UI.
|
||||
func Handler(s *store.Store, tokenKey []byte, legacy string, graceUntil time.Time, path string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if subtle.ConstantTimeCompare([]byte(r.PathValue("token")), []byte(token)) != 1 {
|
||||
readerID, ok := httpmw.ResolveReader(s, legacy, graceUntil, r.PathValue("token"))
|
||||
if !ok {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
discordID, epoch, err := s.ReaderTokenInfo(readerID)
|
||||
if err != nil {
|
||||
log.Printf("userscript: stat %s: %v", path, err)
|
||||
log.Printf("userscript: reader %d token info: %v", readerID, err)
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
src, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
log.Printf("userscript: read %s: %v", path, err)
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Write(stampVersion(src, info.ModTime()))
|
||||
Render(w, r, path, token.Token(tokenKey, discordID, epoch))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,115 +1,67 @@
|
||||
package userscript
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const testToken = "s3cret-token"
|
||||
|
||||
// sampleScript is a stand-in for the real userscript: a metadata block with a
|
||||
// @version line, plus a body that must survive the rewrite untouched.
|
||||
// @version line, the credential placeholder in its metadata and body, plus
|
||||
// content that must survive the rewrites untouched.
|
||||
const sampleScript = `// ==UserScript==
|
||||
// @name Manga Bookmark Sync
|
||||
// @version 1.5.0
|
||||
// @downloadURL https://api.example/u/__API_TOKEN__/manga-bookmark.user.js
|
||||
// @match https://asurascans.com/*
|
||||
// ==/UserScript==
|
||||
(function () { "use strict"; })();
|
||||
(function () { "use strict";
|
||||
const API_TOKEN = "__API_TOKEN__";
|
||||
})();
|
||||
`
|
||||
|
||||
// writeScript drops a userscript in a temp dir with a known mtime and returns
|
||||
// its path plus the version string the handler is expected to stamp.
|
||||
func writeScript(t *testing.T, body string) (path, wantVersion string) {
|
||||
t.Helper()
|
||||
path = filepath.Join(t.TempDir(), "manga-bookmark.user.js")
|
||||
if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
|
||||
t.Fatalf("write script: %v", err)
|
||||
}
|
||||
func TestStampVersionReplacesVersionLineOnly(t *testing.T) {
|
||||
mod := time.Date(2026, 7, 28, 16, 42, 0, 0, time.UTC)
|
||||
if err := os.Chtimes(path, mod, mod); err != nil {
|
||||
t.Fatalf("chtimes: %v", err)
|
||||
}
|
||||
return path, "2026.07.28.1642"
|
||||
}
|
||||
got := string(stampVersion([]byte(sampleScript), mod))
|
||||
|
||||
// newTestMux registers Handler the same way main.go's router does, without
|
||||
// pulling in the store or the rest of the app.
|
||||
func newTestMux(token, path string) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /u/{token}/manga-bookmark.user.js", Handler(token, path))
|
||||
return mux
|
||||
}
|
||||
|
||||
func getScript(t *testing.T, srv http.Handler, token string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
rr := httptest.NewRecorder()
|
||||
srv.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/u/"+token+"/manga-bookmark.user.js", nil))
|
||||
return rr
|
||||
}
|
||||
|
||||
func TestUserscriptServedWithStampedVersion(t *testing.T) {
|
||||
path, wantVersion := writeScript(t, sampleScript)
|
||||
rr := getScript(t, newTestMux(testToken, path), testToken)
|
||||
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rr.Code)
|
||||
if !strings.Contains(got, "// @version "+mod.UTC().Format("2006.01.02.1504")) {
|
||||
t.Errorf("body has no stamped version:\n%s", got)
|
||||
}
|
||||
if ct := rr.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/javascript") {
|
||||
t.Errorf("Content-Type = %q, want text/javascript", ct)
|
||||
if strings.Contains(got, "1.5.0") {
|
||||
t.Errorf("body still carries the file's own version:\n%s", got)
|
||||
}
|
||||
if cc := rr.Header().Get("Cache-Control"); cc != "no-cache" {
|
||||
t.Errorf("Cache-Control = %q, want no-cache", cc)
|
||||
}
|
||||
body := rr.Body.String()
|
||||
if !strings.Contains(body, "// @version "+wantVersion) {
|
||||
t.Errorf("body has no stamped version %q:\n%s", wantVersion, body)
|
||||
}
|
||||
if strings.Contains(body, "1.5.0") {
|
||||
t.Errorf("body still carries the file's own version:\n%s", body)
|
||||
}
|
||||
// Everything outside the @version line is served verbatim.
|
||||
if !strings.Contains(body, `(function () { "use strict"; })();`) {
|
||||
t.Errorf("body was altered beyond the version line:\n%s", body)
|
||||
}
|
||||
if !strings.Contains(body, "// @name Manga Bookmark Sync") {
|
||||
t.Errorf("metadata block was altered:\n%s", body)
|
||||
// Everything outside the @version line is served verbatim, including the
|
||||
// placeholder — stamping must not do the substitution's job.
|
||||
if !strings.Contains(got, `const API_TOKEN = "__API_TOKEN__";`) {
|
||||
t.Errorf("body was altered beyond the version line:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The empty-token case ("/u//manga-bookmark.user.js") is covered at the
|
||||
// router level (see backend's guardEmptyUserscriptToken): ServeMux 307s it to
|
||||
// "/u/manga-bookmark.user.js" before this handler's own token check ever runs.
|
||||
func TestUserscriptWrongTokenIs404(t *testing.T) {
|
||||
path, _ := writeScript(t, sampleScript)
|
||||
srv := newTestMux(testToken, path)
|
||||
for _, tok := range []string{"wrong", testToken + "x", testToken[:3]} {
|
||||
if got := getScript(t, srv, tok).Code; got != http.StatusNotFound {
|
||||
t.Errorf("token %q: status = %d, want 404", tok, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserscriptMissingFileIs404(t *testing.T) {
|
||||
srv := newTestMux(testToken, filepath.Join(t.TempDir(), "absent.user.js"))
|
||||
if got := getScript(t, srv, testToken).Code; got != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want 404", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserscriptWithoutVersionLineServedUnmodified(t *testing.T) {
|
||||
func TestStampVersionWithoutVersionLineServedUnmodified(t *testing.T) {
|
||||
const noVersion = "// ==UserScript==\n// @name x\n// ==/UserScript==\nconsole.log(1);\n"
|
||||
path, _ := writeScript(t, noVersion)
|
||||
rr := getScript(t, newTestMux(testToken, path), testToken)
|
||||
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rr.Code)
|
||||
}
|
||||
if rr.Body.String() != noVersion {
|
||||
t.Fatalf("body = %q, want it unmodified", rr.Body.String())
|
||||
if got := string(stampVersion([]byte(noVersion), time.Now())); got != noVersion {
|
||||
t.Errorf("stampVersion altered a file with no @version line:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubstituteTokenReplacesEveryPlaceholder(t *testing.T) {
|
||||
got := string(substituteToken([]byte(sampleScript), "abc123"))
|
||||
|
||||
if strings.Contains(got, "__API_TOKEN__") {
|
||||
t.Errorf("placeholder survived substitution:\n%s", got)
|
||||
}
|
||||
// The credential lands in the constant and in both metadata lines.
|
||||
if want := `const API_TOKEN = "abc123";`; !strings.Contains(got, want) {
|
||||
t.Errorf("no substituted constant %q:\n%s", want, got)
|
||||
}
|
||||
if want := "https://api.example/u/abc123/manga-bookmark.user.js"; !strings.Contains(got, want) {
|
||||
t.Errorf("no substituted download URL %q:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubstituteTokenWithoutPlaceholderServedUnmodified(t *testing.T) {
|
||||
const noPlaceholder = "// ==UserScript==\n// @name x\n// ==/UserScript==\n"
|
||||
if got := string(substituteToken([]byte(noPlaceholder), "abc123")); got != noPlaceholder {
|
||||
t.Errorf("substituteToken altered a file without the placeholder:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -243,6 +243,53 @@ button { cursor: pointer; }
|
||||
/* The label is 15px tall by design; the thumb gets 44 without moving it. */
|
||||
.ghost::after { content: ""; position: absolute; inset: -15px -12px; }
|
||||
|
||||
/* ---- userscript setup: collapsed by default, one hairline, no card ---- */
|
||||
.setup {
|
||||
margin: 0 20px;
|
||||
padding: 12px 0 0;
|
||||
border-bottom: 1px solid var(--rule);
|
||||
color: var(--mute);
|
||||
}
|
||||
.setup summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-height: 44px;
|
||||
padding: 0;
|
||||
font: 500 10px/1 var(--font-mono);
|
||||
letter-spacing: .2em;
|
||||
text-transform: uppercase;
|
||||
color: var(--mute-2);
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
}
|
||||
.setup summary::-webkit-details-marker { display: none; }
|
||||
.setup summary:hover { color: var(--paper); }
|
||||
.setup[open] { padding-bottom: 16px; }
|
||||
.setup-copy {
|
||||
margin: 0;
|
||||
padding: 4px 0 12px;
|
||||
font: 14px/1.55 var(--font-body);
|
||||
color: var(--mute);
|
||||
}
|
||||
.setup-links {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 20px;
|
||||
margin: 0 0 14px;
|
||||
}
|
||||
.setup-links .ghost { font-size: 11px; }
|
||||
.setup-rotate { margin: 0; }
|
||||
/* Rotation confirmation: the one hot state the panel wears, and it is
|
||||
destruction, not new-chapter signal — danger, never ember. */
|
||||
.setup-warn {
|
||||
margin: 0;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--danger);
|
||||
color: var(--danger);
|
||||
font: 500 12px/1.5 var(--font-mono);
|
||||
letter-spacing: .04em;
|
||||
}
|
||||
|
||||
.chrome { display: flex; flex-direction: column; }
|
||||
|
||||
.searchbar {
|
||||
|
||||
@@ -74,6 +74,8 @@
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{{template "setup" .}}
|
||||
|
||||
{{template "keyrow" .}}
|
||||
|
||||
{{template "recent" .}}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
{{/* The userscript install panel. Each link serves the script rendered
|
||||
with the acting Reader's credential inside it, so the credential never
|
||||
appears in this page's markup, the address bar, or a redirect. Rotation
|
||||
is confirm-gated because it invalidates every installed copy at once;
|
||||
the response swaps this same panel open with the reinstall warning. */}}
|
||||
{{define "setup"}}
|
||||
<details class="setup" id="setup"{{if .Rotated}} open{{end}}>
|
||||
<summary>Userscripts</summary>
|
||||
<p class="setup-copy">Install each script once per device. They keep your
|
||||
bookmarks in sync across every site and update themselves from here.</p>
|
||||
<p class="setup-links">
|
||||
<a class="ghost" href="/install/manga-bookmark.user.js">Install Manga script</a>
|
||||
<a class="ghost" href="/install/novel-bookmark.user.js">Install Novels script</a>
|
||||
</p>
|
||||
{{if .Rotated}}
|
||||
<p class="setup-warn" role="status">Credential rotated — the old one no
|
||||
longer works. Reinstall both scripts on every device now, or they will
|
||||
silently stop syncing.</p>
|
||||
{{else}}
|
||||
<form class="setup-rotate" hx-post="/rotate-token" hx-target="#setup"
|
||||
hx-swap="outerHTML"
|
||||
hx-confirm="Rotation invalidates the current credential on every device immediately. You will have to reinstall both scripts everywhere. Rotate?">
|
||||
<button type="submit" class="ghost">Rotate credential</button>
|
||||
</form>
|
||||
{{end}}
|
||||
</details>
|
||||
{{end}}
|
||||
+82
-12
@@ -16,6 +16,8 @@ import (
|
||||
|
||||
"bookmarkmanager/backend/internal/session"
|
||||
"bookmarkmanager/backend/internal/store"
|
||||
"bookmarkmanager/backend/internal/token"
|
||||
"bookmarkmanager/backend/internal/userscript"
|
||||
)
|
||||
|
||||
//go:embed templates
|
||||
@@ -36,10 +38,19 @@ type Handler struct {
|
||||
// while registration is closed (issue #23). Every session row points at
|
||||
// it, so it is also the Reader the UI acts as.
|
||||
readerID int64
|
||||
tmpl *template.Template
|
||||
discord DiscordConfig
|
||||
states *oauthStates
|
||||
limiter *session.LoginLimiter
|
||||
// tokenKey derives Readers' userscript credentials (internal/token): the
|
||||
// install endpoints render the scripts with the credential inside, which
|
||||
// is the one place the UI needs the secret.
|
||||
tokenKey []byte
|
||||
// mangaUserscriptPath / novelUserscriptPath are the bindmounted script
|
||||
// files the install endpoints render — the same files the /u/ download
|
||||
// paths serve.
|
||||
mangaUserscriptPath string
|
||||
novelUserscriptPath string
|
||||
tmpl *template.Template
|
||||
discord DiscordConfig
|
||||
states *oauthStates
|
||||
limiter *session.LoginLimiter
|
||||
// httpClient is the plain stdlib client that talks to Discord. It is not
|
||||
// an injected interface: tests point APIBase at a stub server instead.
|
||||
httpClient *http.Client
|
||||
@@ -62,6 +73,9 @@ type listView struct {
|
||||
// OOB marks a render of the chrome partials as an out-of-band swap rather
|
||||
// than the inline copy app.html lays out.
|
||||
OOB bool
|
||||
// Rotated marks the setup panel as having just rotated the credential:
|
||||
// it swaps the reinstall warning in over the button row.
|
||||
Rotated bool
|
||||
}
|
||||
|
||||
// PageURL and ListURL are the two link shapes every tab needs. Building them
|
||||
@@ -88,19 +102,22 @@ type loginView struct {
|
||||
|
||||
// New parses every template up front so a broken one kills the process at
|
||||
// startup rather than the first request that touches it.
|
||||
func New(s *store.Store, readerID int64, discord DiscordConfig) (*Handler, error) {
|
||||
func New(s *store.Store, readerID int64, discord DiscordConfig, tokenKey []byte, mangaPath, novelPath string) (*Handler, error) {
|
||||
tmpl, err := template.ParseFS(templateFS, "templates/*.html")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Handler{
|
||||
store: s,
|
||||
readerID: readerID,
|
||||
tmpl: tmpl,
|
||||
discord: discord,
|
||||
states: newOAuthStates(),
|
||||
limiter: session.NewLoginLimiter(),
|
||||
httpClient: &http.Client{Timeout: discordTimeout},
|
||||
store: s,
|
||||
readerID: readerID,
|
||||
tokenKey: tokenKey,
|
||||
mangaUserscriptPath: mangaPath,
|
||||
novelUserscriptPath: novelPath,
|
||||
tmpl: tmpl,
|
||||
discord: discord,
|
||||
states: newOAuthStates(),
|
||||
limiter: session.NewLoginLimiter(),
|
||||
httpClient: &http.Client{Timeout: discordTimeout},
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -116,6 +133,14 @@ func (h *Handler) Register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("POST /ui/bookmarks/{key}/status", h.requireSession(h.uiStatus))
|
||||
mux.HandleFunc("POST /ui/bookmarks/{key}/chapter", h.requireSession(h.uiChapter))
|
||||
mux.HandleFunc("DELETE /ui/bookmarks/{key}", h.requireSession(h.uiDelete))
|
||||
|
||||
// Install endpoints render the script directly under the session: the
|
||||
// credential travels inside the served bytes, never in the address bar or
|
||||
// the page markup. Updates after install use the credential-bearing /u/
|
||||
// path the script embeds, which needs no session.
|
||||
mux.HandleFunc("GET /install/manga-bookmark.user.js", h.requireSession(h.installUserscript("manga-bookmark.user.js")))
|
||||
mux.HandleFunc("GET /install/novel-bookmark.user.js", h.requireSession(h.installUserscript("novel-bookmark.user.js")))
|
||||
mux.HandleFunc("POST /rotate-token", h.requireSession(h.rotateToken))
|
||||
}
|
||||
|
||||
// staticHandler serves the embedded assets. An hour, not longer: assets are
|
||||
@@ -517,3 +542,48 @@ func (h *Handler) uiDelete(w http.ResponseWriter, r *http.Request) {
|
||||
// the library got smaller.
|
||||
h.refreshChrome(w, r)
|
||||
}
|
||||
|
||||
// installUserscript renders the bindmounted script with the acting Reader's
|
||||
// derived credential substituted in. The credential is derived, not stored,
|
||||
// so installs work after any restart; the Reader never types or copies it —
|
||||
// clicking Install is the whole setup.
|
||||
func (h *Handler) installUserscript(name string) http.HandlerFunc {
|
||||
path := h.mangaUserscriptPath
|
||||
if name == "novel-bookmark.user.js" {
|
||||
path = h.novelUserscriptPath
|
||||
}
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
discordID, epoch, err := h.store.ReaderTokenInfo(readerOf(r))
|
||||
if err != nil {
|
||||
log.Printf("install %s: %v", name, err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
userscript.Render(w, r, path, token.Token(h.tokenKey, discordID, epoch))
|
||||
}
|
||||
}
|
||||
|
||||
// rotateToken issues the acting Reader a new credential: the epoch bumps and
|
||||
// the stored hash is rewritten, so the old credential stops authenticating
|
||||
// the moment the statement commits. Every device must reinstall, or its
|
||||
// script keeps failing silently — the setup panel states that warning next
|
||||
// to the button, and the response repeats it as confirmation.
|
||||
func (h *Handler) rotateToken(w http.ResponseWriter, r *http.Request) {
|
||||
readerID := readerOf(r)
|
||||
discordID, epoch, err := h.store.ReaderTokenInfo(readerID)
|
||||
if err != nil {
|
||||
log.Printf("rotate token: %v", err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// The hash is computed for epoch+1 and guarded by it in the store, so a
|
||||
// concurrent rotation cannot leave the stored hash describing another
|
||||
// epoch.
|
||||
if err := h.store.RotateToken(readerID, epoch, token.Hash(token.Token(h.tokenKey, discordID, epoch+1))); err != nil {
|
||||
log.Printf("rotate token: %v", err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
view := listView{Lib: store.KindManga, Rotated: true}
|
||||
h.render(w, http.StatusOK, "setup", view)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user