GitHubLoslegen

Die API-Referenz stammt aus den Go-Doc-Kommentaren im Quellcode und ist auf Englisch verfasst.

package accounts

import "github.com/nsgo-dev/game/pkg/accounts"

Übersicht

Package accounts is a self-hostable player account service: guest accounts that upgrade to email sign-in or to a linked OAuth or platform identity (Game Center, Play Games, Steam), and short-lived tokens a game server verifies offline.

Accounts, sessions and tokens

An account is an ID. A game keys everything it keeps for a player (saves, progress, purchases) by that ID, so upgrading a guest by linking an email address or an identity keeps the player's data: the ID does not change.

Every sign-in (CreateGuest, Register, SignInEmail, SignInIdentity) opens a session on the device and returns Credentials:

  • Session is a long-lived secret the device stores to get new tokens with Refresh, revoked by SignOut. It is the only credential a guest has.
  • Token is a short-lived signed token (package token) the game sends to its server, which verifies it with a token.Verifier and no network call. It expires after the configured TTL.

Identities

A provider such as "gamecenter", "playgames", "steam" or "google" is an IdentityVerifier the service is given: it turns a credential from the device (a signed Game Center identity, a Play Games server auth code, a Steam session ticket, an OpenID Connect ID token) into the provider's stable subject for the player. Linking an identity to an account lets a second device sign in to the same account with SignInIdentity.

Secrets

Passwords are stored only as argon2id hashes (a memory-hard hash). Session secrets are stored only as SHA-256 hashes. Credentials hold their secrets as Secret values, which print, log and marshal as "[redacted]"; the service never logs a password, a session secret, a token or an identity credential.

Storage

The service keeps its records in a Store: NewMemoryStore for tests and prototypes, or the SQL stores of the sqlitestore and pgstore packages, which share sqlstore. Package storetest checks any Store against the contract.

Configuration

Config is a versioned YAML file (ParseConfig, Config.Marshal); Service.Handler serves the service over HTTP with JSON bodies.

Index

Konstanten

const ConfigVersion = 1

ConfigVersion is the configuration file schema version this package reads and writes.

const MaxPasswordBytes = 1024

MaxPasswordBytes is the longest password, in bytes, the service hashes.

Variablen

var (
	// ErrNotFound reports an account, session or identity that does not exist.
	ErrNotFound = errors.New("accounts: not found")
	// ErrTaken reports an email address or identity that belongs to another account.
	ErrTaken = errors.New("accounts: already belongs to another account")
	// ErrAlreadyLinked reports an account that already has an email address, or already has an identity of the provider.
	ErrAlreadyLinked = errors.New("accounts: account already linked")
	// ErrInvalidCredentials reports a wrong email address or password, an unknown or revoked session, or an identity credential its verifier refused. It never says which.
	ErrInvalidCredentials = errors.New("accounts: invalid credentials")
	// ErrInvalidEmail reports an email address that is not a plain address.
	ErrInvalidEmail = errors.New("accounts: invalid email address")
	// ErrWeakPassword reports a password shorter than the configured minimum or longer than MaxPasswordBytes.
	ErrWeakPassword = errors.New("accounts: password too short or too long")
	// ErrUnknownProvider reports an identity provider the service has no verifier for.
	ErrUnknownProvider = errors.New("accounts: unknown identity provider")
	// ErrGuestsDisabled reports CreateGuest on a service configured with DisableGuests.
	ErrGuestsDisabled = errors.New("accounts: guest accounts are disabled")
)

Funktionen

func HashPassword(password string, p Argon2Params, r io.Reader) (string, error)

HashPassword returns the argon2id hash of password with a random salt from r, in the PHC string format "$argon2id$v=19$m=...,t=...,p=...$salt$hash".

func NormalizeEmail(email string) (string, error)

NormalizeEmail trims and lowercases a plain email address ("ada@example.com"), refusing display names, angle brackets and addresses longer than 254 bytes with ErrInvalidEmail.

Typen

type Account struct {
	// ID is the account's permanent random ID, the key of everything the game keeps for the player.
	ID string
	// Email is the account's normalized email address, empty for none.
	Email string
	// Created is when the account was created, to the millisecond.
	Created time.Time
}

Account is one player's account.

type Argon2Params struct {
	// Time is the number of passes over memory, 1 to 16.
	Time uint32 `yaml:"time"`
	// MemoryKiB is the memory one hash uses, in KiB, from 8*Threads to 4 GiB.
	MemoryKiB uint32 `yaml:"memoryKiB"`
	// Threads is the parallelism (lanes), 1 to 16.
	Threads uint8 `yaml:"threads"`
}

Argon2Params is the cost of an argon2id password hash.

func DefaultArgon2Params() Argon2Params

DefaultArgon2Params returns OWASP's recommended argon2id cost: 19 MiB of memory, 2 passes, 1 lane.

func VerifyPassword(password, encoded string) (bool, Argon2Params, error)

VerifyPassword reports whether password matches the PHC-format argon2id hash encoded, comparing in constant time, and returns the cost the hash was made with so a caller can rehash a password made with an outdated cost.

func (p Argon2Params) Validate() error

Validate checks that p is within argon2id's limits and this package's bounds.

type Config struct {
	// Version is the schema version; it must be ConfigVersion.
	Version int `yaml:"version"`
	// Issuer names the service in its tokens, usually its URL.
	Issuer string `yaml:"issuer"`
	// Audience names the game the tokens are for.
	Audience string `yaml:"audience"`
	// TokenTTL is how long a token stays valid, in whole seconds from 1s to 24h.
	TokenTTL Duration `yaml:"tokenTTL"`
	// DisableGuests refuses CreateGuest, so every account starts with an email address or an identity.
	DisableGuests bool `yaml:"disableGuests,omitempty"`
	// Password sets the password rules and hash cost.
	Password PasswordConfig `yaml:"password"`
}

Config is the account service's settings, kept in a YAML file:

version: 1
issuer: https://accounts.example.com
audience: my-game
tokenTTL: 15m
password:
  minLength: 10
  argon2id:
    time: 2
    memoryKiB: 19456
    threads: 1

Unknown fields are refused. Marshal writes the canonical form: the fields in this order, durations in their shortest text and disableGuests only when true. A file in that form, such as one Marshal wrote, reads back and writes again unchanged; a hand-written file in another order or spelling is normalized.

func DefaultConfig(issuer, audience string) Config

DefaultConfig returns a configuration for issuer and audience with a 15-minute token TTL, guests allowed, passwords of at least 10 characters and OWASP's recommended argon2id cost (19 MiB, 2 passes, 1 lane).

func ParseConfig(data []byte) (Config, error)

ParseConfig decodes and validates a YAML configuration. Unknown fields and trailing documents are refused.

func (c Config) Marshal() ([]byte, error)

Marshal validates c and encodes it as deterministic 2-space YAML.

func (c Config) Validate() error

Validate checks that c is a complete version 1 configuration.

type Credentials struct {
	// AccountID is the account signed in to.
	AccountID string
	// Session is the device's long-lived secret for Refresh and SignOut. Store it on the device: for a guest it is the only way back into the account.
	Session Secret
	// Token is the short-lived token the game sends its server.
	Token Secret
	// Expires is when Token expires.
	Expires time.Time
	// Created reports whether the sign-in created the account.
	Created bool
}

Credentials are what a sign-in gives a device.

type Duration time.Duration

Duration is a time.Duration written in YAML as Go duration text ("15m", "1h30m").

func (d Duration) MarshalYAML() (any, error)

MarshalYAML writes d as its shortest Go duration text: "15m" rather than "15m0s".

func (d *Duration) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML reads Go duration text.

type Identity struct {
	// Provider names the provider, such as "gamecenter", "playgames", "steam" or "google".
	Provider string
	// Subject is the provider's stable ID for the player.
	Subject string
}

Identity is an account's identity at a provider, such as a Game Center player or a Steam user.

type IdentityVerifier interface {
	VerifyIdentity(ctx context.Context, credential string) (subject string, err error)
}

IdentityVerifier checks a credential a device got from an identity provider and returns the provider's stable subject for the player. A verifier for Game Center checks the signed identity against Apple's certificate, one for Play Games exchanges the server auth code, one for Steam authenticates the session ticket with the Steam Web API, and one for an OAuth provider verifies the OpenID Connect ID token.

The credential is a secret: a verifier must not log it or put it in its errors. The service never shows a verifier's error to the caller; it returns ErrInvalidCredentials.

type IdentityVerifierFunc func(ctx context.Context, credential string) (string, error)

IdentityVerifierFunc adapts a function to IdentityVerifier.

func (f IdentityVerifierFunc) VerifyIdentity(ctx context.Context, credential string) (string, error)

VerifyIdentity calls f.

type MemoryStore struct {
	// contains filtered or unexported fields
}

MemoryStore is a Store held in memory, for tests and single-process prototypes. Its records are lost when the process ends.

func NewMemoryStore() *MemoryStore

NewMemoryStore returns an empty MemoryStore.

func (m *MemoryStore) Account(_ context.Context, id string) (Account, error)

Account implements Store.

func (m *MemoryStore) AccountByEmail(_ context.Context, email string) (Account, string, error)

AccountByEmail implements Store.

func (m *MemoryStore) AccountByIdentity(_ context.Context, identity Identity) (Account, error)

AccountByIdentity implements Store.

func (m *MemoryStore) CreateAccount(_ context.Context, a Account, passwordHash string, identities ...Identity) error

CreateAccount implements Store.

func (m *MemoryStore) CreateSession(_ context.Context, s Session) error

CreateSession implements Store.

func (m *MemoryStore) DeleteSession(_ context.Context, id string) error

DeleteSession implements Store.

func (m *MemoryStore) Identities(_ context.Context, id string) ([]Identity, error)

Identities implements Store.

func (m *MemoryStore) LinkIdentity(_ context.Context, id string, identity Identity, _ time.Time) error

LinkIdentity implements Store.

func (m *MemoryStore) Session(_ context.Context, id string) (Session, error)

Session implements Store.

func (m *MemoryStore) SetEmail(_ context.Context, id, email, passwordHash string) error

SetEmail implements Store.

func (m *MemoryStore) SetPasswordHash(_ context.Context, id, passwordHash string) error

SetPasswordHash implements Store.

type Options struct {
	// Store keeps the records; required.
	Store Store
	// Key signs tokens; required. Keep it in a PEM file read with token.ParsePrivateKey.
	Key ed25519.PrivateKey
	// KeySet holds public keys the service still accepts besides Key's, such as the key it signed with before a rotation; nil accepts only Key's. Its issuer and audience must match the configuration. The service verifies bearer tokens with Key's public key and these, and serves them all at GET /v1/keys, so tokens signed with an old key keep working until the key is removed from the set.
	KeySet *token.KeySet
	// Identities are the identity providers by name, such as "gamecenter" or "steam". A name is 1 to 32 characters of a-z, 0-9, '.', '_' and '-', starting with a letter or digit.
	Identities map[string]IdentityVerifier
	// Logger receives account events and store errors, never secrets; nil discards them.
	Logger *slog.Logger
	// Now is the service's clock; nil uses time.Now.
	Now func() time.Time
	// Rand fills IDs, secrets and salts; nil uses crypto/rand. The service serializes its reads, so a reader that is not safe for concurrent use, such as a deterministic one in a test, may be given.
	Rand io.Reader
	// MaxConcurrentHashes bounds how many password hashes run at once, each using the configured argon2id memory; 0 uses GOMAXPROCS.
	MaxConcurrentHashes int
}

Options are what a Service needs besides its Config.

type PasswordConfig struct {
	// MinLength is the fewest characters a password may have, at least 8.
	MinLength int `yaml:"minLength"`
	// Argon2id is the hash cost of new and rehashed passwords.
	Argon2id Argon2Params `yaml:"argon2id"`
}

PasswordConfig is the password rules and the argon2id cost.

type Profile struct {
	Account
	// Identities are the account's linked identities, sorted by provider.
	Identities []Identity
}

Profile is an account with its linked identities.

func (p Profile) Guest() bool

Guest reports whether the account has neither an email address nor an identity, so only its sessions can sign in to it.

type Secret struct {
	// contains filtered or unexported fields
}

Secret holds a credential (a session secret or a token) so that it cannot reach a log by accident: fmt, log/slog, encoding/json and encoding.TextMarshaler users see "[redacted]". Reveal returns the value for the one place that must send it.

func NewSecret(s string) Secret

NewSecret wraps s.

func (s Secret) Format(f fmt.State, _ rune)

Format writes "[redacted]" for every verb, so %x or %q cannot reveal the value either.

func (s Secret) GoString() string

GoString returns "[redacted]", for %#v.

func (s Secret) IsZero() bool

IsZero reports whether the secret is empty.

func (s Secret) LogValue() slog.Value

LogValue returns "[redacted]" for log/slog.

func (s Secret) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON string "[redacted]".

func (s Secret) MarshalText() ([]byte, error)

MarshalText returns "[redacted]".

func (s Secret) Reveal() string

Reveal returns the secret's value.

func (s Secret) String() string

String returns "[redacted]".

type Service struct {
	// contains filtered or unexported fields
}

Service is the account service. It is safe for concurrent use.

func New(cfg Config, opts Options) (*Service, error)

New returns a service with the configuration and options. The token signer is built from cfg's issuer, audience and TTL and opts.Key.

func (s *Service) Authenticate(tok string) (token.Claims, error)

Authenticate verifies a token the service issued and returns its claims.

func (s *Service) Config() Config

Config returns the service's configuration.

func (s *Service) CreateGuest(ctx context.Context) (Credentials, error)

CreateGuest creates an account with no email address or identity and signs the device in to it.

func (s *Service) Handler() http.Handler

Handler serves the service over HTTP. Requests and responses are JSON; every response carries Cache-Control: no-store.

POST /v1/guest                                         -> credentials
POST /v1/register          {"email", "password"}       -> credentials
POST /v1/signin/email      {"email", "password"}       -> credentials
POST /v1/signin/identity   {"provider", "credential"}  -> credentials
POST /v1/refresh           {"session"}                 -> credentials
POST /v1/signout           {"session"}                 -> 204
POST /v1/link/email        {"email", "password"}       -> 204, with a bearer token
POST /v1/link/identity     {"provider", "credential"}  -> 204, with a bearer token
GET  /v1/me                                            -> profile, with a bearer token
GET  /v1/keys                                          -> the key set as YAML

Credentials are {"account", "session", "token", "expires", "created"}, expires in RFC 3339. A bearer token goes in "Authorization: Bearer <token>". Errors are {"error": code} with the status the code implies: invalid_credentials and invalid_token 401, guests_disabled 403, not_found 404, taken and already_linked 409, request_too_large 413, bad_request, invalid_email, weak_password and unknown_provider 400, unavailable 503 when the request was cancelled or timed out (for example waiting for a password hash slot under load), and internal 500.

The handler does not limit request rates; put it behind a rate limiter, and behind TLS.

func (s *Service) KeySet() *token.KeySet

KeySet returns the public key set a game server verifies the service's tokens with: the signing key's public half first, then the keys of Options.KeySet.

func (s *Service) LinkEmail(ctx context.Context, accountID, email, password string) error

LinkEmail gives an account (a guest, or one signed in with an identity) an email address and password, keeping its ID and so its data. It returns ErrAlreadyLinked when the account has an address and ErrTaken when another account has this one.

func (s *Service) LinkIdentity(ctx context.Context, accountID, provider, credential string) error

LinkIdentity links the identity a credential from provider proves to an account, keeping the account's ID and so its data. Another device then signs in to the account with SignInIdentity. It returns ErrTaken when another account has the identity and ErrAlreadyLinked when the account has another identity of the provider.

func (s *Service) Profile(ctx context.Context, accountID string) (Profile, error)

Profile returns an account and its identities.

func (s *Service) Refresh(ctx context.Context, session Secret) (Credentials, error)

Refresh returns a new token for a device's session. The session stays the same.

func (s *Service) Register(ctx context.Context, email, password string) (Credentials, error)

Register creates an account with an email address and password and signs the device in to it. It returns ErrTaken when the address belongs to an account.

func (s *Service) SignInEmail(ctx context.Context, email, password string) (Credentials, error)

SignInEmail signs a device in with an email address and password. A wrong address or password returns ErrInvalidCredentials and takes as long as a right one. A password hashed with a cost other than the configured one is rehashed.

func (s *Service) SignInIdentity(ctx context.Context, provider, credential string) (Credentials, error)

SignInIdentity signs a device in with a credential from provider. An identity linked to no account gets a new account (Credentials.Created), so a player can start with a platform identity as well as upgrade to one.

func (s *Service) SignOut(ctx context.Context, session Secret) error

SignOut revokes a device's session. Tokens already issued stay valid until they expire.

type Session struct {
	// ID is the session's random ID, the part of the device's credential before the dot.
	ID string
	// AccountID is the account the session signs in to.
	AccountID string
	// SecretHash is the SHA-256 of the session's secret, in hex.
	SecretHash string
	// Created is when the session was opened, to the millisecond.
	Created time.Time
}

Session is one signed-in device. The store keeps only a hash of the session's secret.

type Store interface {
	// CreateAccount stores a new account with the password hash (empty for none; only with an Email) and links the identities to it, all or nothing. It returns ErrTaken when the ID, email address or an identity already exists, or when two identities share a provider.
	CreateAccount(ctx context.Context, a Account, passwordHash string, identities ...Identity) error
	// Account returns the account with id, or ErrNotFound.
	Account(ctx context.Context, id string) (Account, error)
	// AccountByEmail returns the account with the normalized email address and its password hash, or ErrNotFound.
	AccountByEmail(ctx context.Context, email string) (Account, string, error)
	// SetEmail gives an account without an email address one and its password hash. It returns ErrNotFound for no such account, ErrAlreadyLinked when the account has an email address, ErrInvalidEmail for an empty address, and ErrTaken when another account has this one.
	SetEmail(ctx context.Context, id, email, passwordHash string) error
	// SetPasswordHash replaces the password hash of an account with an email address, or returns ErrNotFound.
	SetPasswordHash(ctx context.Context, id, passwordHash string) error
	// LinkIdentity links an identity to an account. It returns nil when the identity is already linked to this account, ErrNotFound for no such account, ErrTaken when another account has the identity, and ErrAlreadyLinked when the account has another identity of the provider.
	LinkIdentity(ctx context.Context, id string, identity Identity, at time.Time) error
	// AccountByIdentity returns the account an identity is linked to, or ErrNotFound.
	AccountByIdentity(ctx context.Context, identity Identity) (Account, error)
	// Identities returns the identities linked to an account, sorted by provider; none for an unknown account.
	Identities(ctx context.Context, id string) ([]Identity, error)
	// CreateSession stores a new session of an existing account. It returns ErrNotFound for no such account and ErrTaken when the session ID exists.
	CreateSession(ctx context.Context, s Session) error
	// Session returns the session with id, or ErrNotFound.
	Session(ctx context.Context, id string) (Session, error)
	// DeleteSession deletes the session with id, or returns ErrNotFound.
	DeleteSession(ctx context.Context, id string) error
}

Store keeps the service's accounts, identities and sessions. Implementations must be safe for concurrent use and enforce the uniqueness the methods state atomically, so that two devices racing to claim one email address or identity cannot both succeed. Package storetest checks a Store against this contract.