Files
scrabble-game/backend/internal/session/store.go
T
Ilia Denisov 92633f935e
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 18s
CI / ui (pull_request) Successful in 1m7s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m42s
feat(payments): trusted platform signal on the session
Record the execution platform (kind vk|telegram|direct + device subtype
ios|android|web) on each session, captured at creation and carried
gateway->backend as a trusted X-Platform header, so the upcoming
store-compliance gate has an unforgeable execution context.

- backend.sessions gains nullable platform_kind/platform_subtype columns
  (migration 00011, CHECK-constrained, jet regenerated); session.Platform
  captures them at mint, resolve returns them, middleware exposes platform(c).
  kind is derived from the establish endpoint, never a client field; the
  account-merge session mint inherits the caller's platform.
- gateway derives the platform (VK subtype from the signed vk_platform via
  vkauth, Telegram/direct best-effort from the client) and injects X-Platform
  on every authenticated backend call through the request context.
- ui submits a best-effort device subtype on the telegram/guest/email login
  requests (new FBS subtype field); VK is server-derived from the signed params.
- an unattributed session is untrusted (view-only); VK/TG self-heal on the next
  cold-start re-mint, direct/email on re-login.

Signal plumbing only, no user-visible change; X-Platform is inert until the
gate consumes it.
2026-07-08 03:31:51 +02:00

198 lines
6.2 KiB
Go

package session
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"github.com/go-jet/jet/v2/postgres"
"github.com/go-jet/jet/v2/qrm"
"github.com/google/uuid"
"scrabble/backend/internal/postgres/jet/backend/model"
"scrabble/backend/internal/postgres/jet/backend/table"
)
// Session lifecycle statuses persisted in the status column.
const (
StatusActive = "active"
StatusRevoked = "revoked"
)
// ErrNotFound is returned when no active session matches the lookup.
var ErrNotFound = errors.New("session: not found")
// Session mirrors a row in backend.sessions. TokenHash is the hex-encoded
// SHA-256 of the bearer token. Platform is the trusted execution context captured
// at creation; its zero value marks an untrusted session (see Platform).
type Session struct {
ID uuid.UUID
AccountID uuid.UUID
TokenHash string
Status string
CreatedAt time.Time
LastSeenAt *time.Time
RevokedAt *time.Time
Platform Platform
}
// Store is the Postgres-backed query surface for backend.sessions.
type Store struct {
db *sql.DB
}
// NewStore constructs a Store wrapping db.
func NewStore(db *sql.DB) *Store {
return &Store{db: db}
}
// Insert persists a new active session for accountID carrying tokenHash and the
// captured platform, and returns the persisted row. An empty platform Kind/Subtype
// is written as SQL NULL, so an untrusted session records no platform.
func (s *Store) Insert(ctx context.Context, accountID uuid.UUID, tokenHash string, platform Platform) (Session, error) {
id, err := uuid.NewV7()
if err != nil {
return Session{}, fmt.Errorf("session: new id: %w", err)
}
stmt := table.Sessions.INSERT(
table.Sessions.SessionID,
table.Sessions.AccountID,
table.Sessions.TokenHash,
table.Sessions.PlatformKind,
table.Sessions.PlatformSubtype,
).VALUES(id, accountID, tokenHash, stringOrNull(platform.Kind), stringOrNull(platform.Subtype)).RETURNING(table.Sessions.AllColumns)
var row model.Sessions
if err := stmt.QueryContext(ctx, s.db, &row); err != nil {
return Session{}, fmt.Errorf("session: insert: %w", err)
}
return modelToSession(row), nil
}
// FindActiveByTokenHash returns the active session matching tokenHash, or
// ErrNotFound.
func (s *Store) FindActiveByTokenHash(ctx context.Context, tokenHash string) (Session, error) {
stmt := postgres.SELECT(table.Sessions.AllColumns).
FROM(table.Sessions).
WHERE(
table.Sessions.TokenHash.EQ(postgres.String(tokenHash)).
AND(table.Sessions.Status.EQ(postgres.String(StatusActive))),
).
LIMIT(1)
var row model.Sessions
if err := stmt.QueryContext(ctx, s.db, &row); err != nil {
if errors.Is(err, qrm.ErrNoRows) {
return Session{}, ErrNotFound
}
return Session{}, fmt.Errorf("session: find by token hash: %w", err)
}
return modelToSession(row), nil
}
// RevokeByTokenHash transitions the active session for tokenHash to revoked and
// returns the post-update row. ok is false with a nil error when no active
// session matched, so revocation is idempotent.
func (s *Store) RevokeByTokenHash(ctx context.Context, tokenHash string, at time.Time) (Session, bool, error) {
stmt := table.Sessions.
UPDATE(table.Sessions.Status, table.Sessions.RevokedAt).
SET(postgres.String(StatusRevoked), postgres.TimestampzT(at)).
WHERE(
table.Sessions.TokenHash.EQ(postgres.String(tokenHash)).
AND(table.Sessions.Status.EQ(postgres.String(StatusActive))),
).
RETURNING(table.Sessions.AllColumns)
var row model.Sessions
if err := stmt.QueryContext(ctx, s.db, &row); err != nil {
if errors.Is(err, qrm.ErrNoRows) {
return Session{}, false, nil
}
return Session{}, false, fmt.Errorf("session: revoke by token hash: %w", err)
}
return modelToSession(row), true, nil
}
// RevokeAllForAccount transitions every active session of accountID to revoked
// and returns the post-update rows (so the caller can evict them from the cache).
// It backs the account-merge flow, which retires a secondary account's sessions.
// No matching rows is not an error.
func (s *Store) RevokeAllForAccount(ctx context.Context, accountID uuid.UUID, at time.Time) ([]Session, error) {
stmt := table.Sessions.
UPDATE(table.Sessions.Status, table.Sessions.RevokedAt).
SET(postgres.String(StatusRevoked), postgres.TimestampzT(at)).
WHERE(
table.Sessions.AccountID.EQ(postgres.UUID(accountID)).
AND(table.Sessions.Status.EQ(postgres.String(StatusActive))),
).
RETURNING(table.Sessions.AllColumns)
var rows []model.Sessions
if err := stmt.QueryContext(ctx, s.db, &rows); err != nil {
if errors.Is(err, qrm.ErrNoRows) {
return nil, nil
}
return nil, fmt.Errorf("session: revoke all for account %s: %w", accountID, err)
}
out := make([]Session, 0, len(rows))
for _, row := range rows {
out = append(out, modelToSession(row))
}
return out, nil
}
// ListActive loads every active session. Cache.Warm calls this at boot.
func (s *Store) ListActive(ctx context.Context) ([]Session, error) {
stmt := postgres.SELECT(table.Sessions.AllColumns).
FROM(table.Sessions).
WHERE(table.Sessions.Status.EQ(postgres.String(StatusActive)))
var rows []model.Sessions
if err := stmt.QueryContext(ctx, s.db, &rows); err != nil {
return nil, fmt.Errorf("session: list active: %w", err)
}
out := make([]Session, 0, len(rows))
for _, row := range rows {
out = append(out, modelToSession(row))
}
return out, nil
}
// modelToSession projects a generated model row into the public Session struct,
// copying pointer fields so callers cannot mutate the scan buffer.
func modelToSession(row model.Sessions) Session {
s := Session{
ID: row.SessionID,
AccountID: row.AccountID,
TokenHash: row.TokenHash,
Status: row.Status,
CreatedAt: row.CreatedAt,
}
if row.LastSeenAt != nil {
t := *row.LastSeenAt
s.LastSeenAt = &t
}
if row.RevokedAt != nil {
t := *row.RevokedAt
s.RevokedAt = &t
}
if row.PlatformKind != nil {
s.Platform.Kind = *row.PlatformKind
}
if row.PlatformSubtype != nil {
s.Platform.Subtype = *row.PlatformSubtype
}
return s
}
// stringOrNull maps an empty string to a SQL NULL literal and any other value to a
// string literal, so an untrusted session's absent platform is stored as NULL.
func stringOrNull(s string) postgres.Expression {
if s == "" {
return postgres.NULL
}
return postgres.String(s)
}