GitHubComeçar

A referência da API é gerada a partir dos comentários de documentação Go no código-fonte e está escrita em inglês.

package accounts

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

Visão geral

Package accounts is experimental: its API and documented formats may change in a minor release. See the API stability policy. 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 authtoken) the game sends to its server, which verifies it with an authtoken.Verifier and no network call. It expires after the configured TTL. A token is good only for the audience it names: sign-ins return one for the game's servers, and RefreshFor returns one for the service itself (ServiceAudience) or for another service in Config.Audiences, such as cloud save, so a game server cannot replay a player's token against those.

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.

Índice

Constantes

const (
	// PermRead lets an operator search accounts and view one with its identities, sessions and suspension.
	PermRead = "accounts.read"
	// PermSuspend lets an operator suspend an account and lift its suspension.
	PermSuspend = "accounts.suspend"
	// PermUnlink lets an operator remove an identity from an account.
	PermUnlink = "accounts.unlink"
	// PermRevoke lets an operator end every session of an account.
	PermRevoke = "accounts.revoke"
	// PermExport lets an operator download an account's data export.
	PermExport = "accounts.export"
	// PermDelete lets an operator delete an account.
	PermDelete = "accounts.delete"
)

Permissions of the account service's operator routes.

const ActionUnsuspend = "accounts.unsuspend"

ActionUnsuspend is the audit action of lifting a suspension, which needs PermSuspend.

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.

const MaxSearchLimit = 1000

MaxSearchLimit is the largest page SearchAccounts returns, so one call cannot read a whole table into memory.

const MaxSuspensionReasonBytes = 500

MaxSuspensionReasonBytes bounds a suspension's public reason.

const ServiceAudience = authtoken.AccountServiceAudience

ServiceAudience is the audience of tokens for the account service itself: GET /v1/me and the link endpoints accept only these, so a game server that holds a player's game token cannot read or change the account. A device gets one with RefreshFor.

Variáveis

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")
	// ErrUnknownAudience reports a token request for an audience that is neither the game's, ServiceAudience nor one of Config.Audiences.
	ErrUnknownAudience = errors.New("accounts: unknown token audience")
	// ErrGuestsDisabled reports CreateGuest on a service configured with DisableGuests.
	ErrGuestsDisabled = errors.New("accounts: guest accounts are disabled")
	// ErrLastCredential reports an attempt to remove the account's last way to sign in.
	ErrLastCredential = errors.New("accounts: cannot remove the last sign-in method")
	// ErrSuspended reports a sign-in or refresh of a suspended account. The service returns it as a *SuspendedError, which carries the suspension's end and public reason.
	ErrSuspended = errors.New("accounts: account suspended")
	// ErrInvalidSearchLimit reports a SearchAccounts limit outside 1 to MaxSearchLimit.
	ErrInvalidSearchLimit = errors.New("accounts: search limit must be from 1 to 1000")
)
var ErrInvalidUsername = errors.New("accounts: invalid username")

ErrInvalidUsername reports a username that is not 3 to 20 lowercase letters, digits, underscores or hyphens after normalization.

var ErrSessionExpired = errors.New("accounts: session expired")

ErrSessionExpired reports a device session that was idle for longer than SessionPolicy.IdleTTL or opened longer than SessionPolicy.AbsoluteTTL ago.

var ErrSessionReuse = errors.New("accounts: session secret reused")

ErrSessionReuse reports a secret that is neither the session's current secret nor its previous one within the rotation overlap; the session is revoked as stolen.

var ErrUsernameCooldown = errors.New("accounts: username change cooldown")

ErrUsernameCooldown reports a username change sooner than PublicDirectory.UsernameCooldown after the last one.

Funções

func AppAccountToken(accountID string) string

AppAccountToken returns the stable UUID that StoreKit associates with an account. Account IDs are 32 hexadecimal characters. Invalid IDs return an empty string.

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.

func ValidatePassword(password string, min int) error

ValidatePassword applies the service's length policy without hashing: at least min characters (Unicode code points, at least 1) and at most MaxPasswordBytes bytes, else ErrWeakPassword.

Tipos

type Account struct {
	// ID is the account's permanent random ID, the key of everything the game keeps for the player.
	ID string `json:"id"`
	// Email is the account's normalized email address, empty for none.
	Email string `json:"email,omitempty"`
	// Created is when the account was created, to the millisecond.
	Created time.Time `json:"created"`
	// Suspension is the account's suspension, nil for none. It is left out of the account's JSON, and so out of the player's data export.
	Suspension *Suspension `json:"-"`
}

Account is one player's account.

type AccountPage struct {
	// Accounts are the matching accounts, in ascending order of ID.
	Accounts []Account
	// Next is the cursor of the next page, empty when this is the last one.
	Next string
}

AccountPage is one page of SearchAccounts.

type AccountQuery struct {
	// IDPrefix matches accounts whose ID starts with it.
	IDPrefix string
	// EmailPrefix matches accounts whose normalized email address starts with it.
	EmailPrefix string
	// Provider matches accounts with an identity of the provider.
	Provider string
	// Subject matches accounts with an identity whose subject is exactly it, of Provider when that is set.
	Subject string
	// CreatedFrom, when set, matches accounts created at or after it.
	CreatedFrom time.Time
	// CreatedBefore, when set, matches accounts created before it.
	CreatedBefore time.Time
}

AccountQuery selects the accounts SearchAccounts returns. Every field set must match; a zero query matches every 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's servers, the audience of the tokens sign-in and Refresh return and of the key set. A player sends these tokens to every game server it joins, so they reach no other service.
	Audience string `yaml:"audience"`
	// Audiences are the other services a device may get tokens for with RefreshFor, such as "cloudsave" and "leaderboard"; each such service accepts only tokens for its own audience. Tokens for ServiceAudience, which the service's own bearer endpoints accept, are always available and not listed.
	Audiences []string `yaml:"audiences,omitempty"`
	// 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"`
	// AllowedOrigins lists the web origins ("https://play.example.com") whose pages may call the service from a browser. The handler answers their CORS preflight requests; other origins get no CORS headers, so browsers refuse their requests. Native clients send no origin and need no entry.
	AllowedOrigins []string `yaml:"allowedOrigins,omitempty"`
	// Metrics, when set, is the TCP address the service's daemon (accountsd serve) serves GET /healthz, /readyz and /metrics on, such as 127.0.0.1:9101, on a listener of its own apart from the one players reach. The endpoints have no authentication, so keep a non-loopback address such as :9101 on a private network the public proxy does not forward to; the daemon logs a warning for one. Empty serves none of them. Service ignores it: a program that builds its own server mounts a servicehealth.Health itself.
	Metrics string `yaml:"metrics,omitempty"`
	// Admin, when set, gives the daemon an admin listener of its own for operators (package admin); without it the daemon serves no admin route.
	Admin *admin.Config `yaml:"admin,omitempty"`
}

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

version: 1
issuer: https://accounts.example.com
audience: my-game
audiences:
  - cloudsave
  - leaderboard
tokenTTL: 15m
password:
  minLength: 10
  argon2id:
    time: 2
    memoryKiB: 19456
    threads: 1
allowedOrigins:
  - https://play.example.com
metrics: 127.0.0.1:9101

An optional admin: block (admin.Config) at the end gives the daemon an admin listener for operators.

Unknown fields are refused. Marshal writes the canonical form: the fields in this order, durations in their shortest text, disableGuests only when true, audiences and allowedOrigins only when they have entries and metrics only when set. 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 tokens also available for the "cloudsave" and "leaderboard" audiences the cloud save and leaderboard services accept by default, 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, for Config.Audience, or the token for the audience RefreshFor was asked for. A game server can replay a token it is sent until it expires, so a device sends each service only a token for that service.
	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 DeviceSession struct {
	ID, AccountID, Device      string
	Created, LastUsed, Expires time.Time
	Generation                 uint64
	SecretHash                 string
}

DeviceSession is one signed-in device of an account: its IDs and device name, when it opened, was last used and expires, how many times its secret was rotated, and the hash of its current secret.

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 Export struct {
	Account    Account    `json:"account"`
	Identities []Identity `json:"identities"`
}

Export is the portable account data document returned by DataExport and GET /v1/me/export: {"account": {"id", "email", "created"}, "identities": [{"provider", "subject"}]}, email omitted for none and identities sorted by provider. It intentionally excludes session secrets and password hashes.

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

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) ChangePasswordHash(_ context.Context, id, passwordHash, keepSession string) error

ChangePasswordHash 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) DeleteAccount(_ context.Context, id string) error

DeleteAccount implements Store.

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

DeleteSession implements Store.

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

DeleteSessions 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) RemoveIdentity(_ context.Context, id, provider string) error

RemoveIdentity implements Store.

func (m *MemoryStore) SearchAccounts(_ context.Context, q AccountQuery, cursor string, limit int) (AccountPage, error)

SearchAccounts implements Store.

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

Session implements Store.

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

Sessions implements Store.

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

SetEmail implements Store.

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

SetPasswordHash implements Store.

func (m *MemoryStore) SetSuspension(_ context.Context, id string, s *Suspension) error

SetSuspension implements Store.

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

UnlinkIdentity implements Store.

type Options struct {
	// Store keeps the records; required.
	Store Store
	// Key signs tokens; required. Keep it in a PEM file read with authtoken.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 *authtoken.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 ProfileUpdate struct {
	Username, DisplayName, AvatarURL, Lang, TimeZone string
	Metadata                                         map[string]any
}

ProfileUpdate is the public profile an account sets with PublicDirectory.Set: its username, display name, avatar URL, language, time zone and free-form metadata.

type PublicDirectory struct {
	Now              func() time.Time
	UsernameCooldown time.Duration
	NameFilter       func(string) error
	// contains filtered or unexported fields
}

PublicDirectory stores public profiles and supports atomic username claims.

func NewPublicDirectory() *PublicDirectory

NewPublicDirectory returns an empty in-memory directory with no username cooldown or name filter.

func (d *PublicDirectory) Set(ctx context.Context, id string, u ProfileUpdate) (PublicProfile, error)

Set replaces the public profile of account id with u and returns it. The username is normalized (NFKC, case folded) and must be 3 to 20 lowercase letters, digits, underscores or hyphens, else ErrInvalidUsername; NameFilter may refuse it; a username another account holds is ErrTaken; and a change of username within UsernameCooldown of the last one is ErrUsernameCooldown. Claiming a name and releasing the old one is atomic.

func (d *PublicDirectory) Users(ctx context.Context, ids []string, usernames []string) ([]PublicProfile, error)

Users returns the public profiles of the accounts with the given IDs and usernames, each once and sorted by account ID. It never returns an email address or a linked identity.

type PublicProfile struct {
	AccountID   string
	Username    string
	DisplayName string
	AvatarURL   string
	Lang        string
	TimeZone    string
	Metadata    map[string]any
	Updated     time.Time
}

PublicProfile is the safe subset of account data shown to other players.

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) AdminRoutes() []admin.Route

AdminRoutes returns the service's operator routes, for admin.ListenOptions.Routes. Each requires one permission, and the admin listener writes an audit record of every call, reads included since they return personal data, naming the operator and "account:<id>" (a search names "accounts" and records its query and how many accounts it returned):

GET    /admin/v1/accounts?q=&id=&email=&provider=&subject=&from=&to=&cursor=&limit=  accounts.read    -> {"accounts", "next"}
GET    /admin/v1/accounts/{id}                    accounts.read    -> the account with its identities, sessions and suspension
POST   /admin/v1/accounts/{id}/suspend            accounts.suspend {"until", "reason"} -> the suspension
DELETE /admin/v1/accounts/{id}/suspend            accounts.suspend -> 204 (audited as accounts.unsuspend)
POST   /admin/v1/accounts/{id}/unlink             accounts.unlink  {"provider", "force"} -> 204
POST   /admin/v1/accounts/{id}/sessions/revoke    accounts.revoke  -> {"revoked"}
GET    /admin/v1/accounts/{id}/export             accounts.export  -> the account's data export
DELETE /admin/v1/accounts/{id}                    accounts.delete  -> 204

Search takes either q, which is an email prefix when it contains "@", "provider:subject" when it contains ":", and an ID prefix otherwise, or the fields id (ID prefix), email (email prefix), provider and subject; from and to bound the creation time (RFC 3339, from inclusive, to exclusive), and limit is 1 to 100 (default 50). Pages are ordered by ID and next continues after the last account of a page, so accounts created while an operator pages neither repeat nor push others out. Unlinking an account's last way to sign in needs "force": true, else 409 last_credential.

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

Authenticate verifies a token the service issued for the game's servers (Config.Audience) and returns its claims. It refuses tokens for any other audience.

func (s *Service) ChangePassword(ctx context.Context, accountID string, keep Secret, oldPassword, newPassword string) error

ChangePassword replaces an account's password after checking the current one, and signs out every other device: every session of the account except keep stops refreshing. keep is the session of the device that asks, and must be the account's (ErrInvalidCredentials otherwise); with a zero keep every session ends, that device's too. Tokens already issued stay valid until they expire. It refuses accounts without an email credential, and a new password outside the configured length with ErrWeakPassword.

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) DataExport(ctx context.Context, accountID string) (Export, error)

DataExport returns the account profile and linked provider identities. The document contains no credentials, password hashes or session secrets.

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

DeleteAccount permanently removes the account, its identities and all sessions, so its sessions no longer refresh; tokens already issued stay valid until they expire. Callers must authenticate the request with a service-audience bearer token before invoking 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", "audience"}     -> credentials
POST /v1/signout           {"session"}                 -> 204
POST /v1/link/email        {"email", "password"}       -> 204, with a bearer token for "accounts"
POST /v1/link/identity     {"provider", "credential"}  -> 204, with a bearer token for "accounts"
POST /v1/password          {"oldPassword", "newPassword", "session"} -> 204, with a bearer token for "accounts"
POST /v1/unlink/identity   {"provider"}                 -> 204, with a bearer token for "accounts"
GET  /v1/me                                            -> profile, with a bearer token for "accounts"
GET  /v1/me/export                                     -> the account's data export, with a bearer token for "accounts"
DELETE /v1/me                                          -> 204, deletes the account, with a bearer token for "accounts"
GET  /v1/keys                                          -> the key set as YAML

Credentials are {"account", "session", "token", "expires", "created"}, expires in RFC 3339. The token of a sign-in is for the game's servers (Config.Audience); refresh's optional "audience" asks for one for another audience instead, ServiceAudience ("accounts") or one of Config.Audiences. A bearer token goes in "Authorization: Bearer <token>"; the endpoints that take one accept only a token for ServiceAudience, so the token a game server receives cannot read or change the account. Errors are {"error": code} with the status the code implies: invalid_credentials and invalid_token 401, guests_disabled 403, suspended 403 for a sign-in, refresh or change of a suspended account (with "until" in RFC 3339, absent when the suspension has no end, and "reason", absent for none), not_found 404, taken, already_linked and last_credential 409, request_too_large 413, bad_request, invalid_email, weak_password, unknown_provider and unknown_audience 400, unavailable 503 when the request was cancelled or timed out (for example waiting for a password hash slot under load), and internal 500.

A suspended account's token still reads it (GET /v1/me and /v1/me/export), but its changes (linking, unlinking, a password change and DELETE /v1/me) are refused with 403 suspended until the suspension ends or is lifted, so a suspended player cannot free their identities or email address to sign up again unsuspended; an operator can still delete the account.

A password change signs out every other device: every session of the account except the request's "session" stops refreshing, and without "session" every session ends, the caller's too. The session must be the bearer token's account's (invalid_credentials otherwise). Tokens already issued stay valid until they expire.

Browsers may call the handler from Config.AllowedOrigins: it answers their CORS preflight requests and allows Authorization and Content-Type.

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

func (s *Service) KeySet() *authtoken.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 the game's servers for a device's session. The session stays the same. A suspended account's session is refused with a *SuspendedError until the suspension ends or is lifted.

func (s *Service) RefreshFor(ctx context.Context, session Secret, audience string) (Credentials, error)

RefreshFor returns a new token for a device's session meant for audience: Config.Audience (or "") for game servers, ServiceAudience for the service's own bearer endpoints, or one of Config.Audiences, such as the cloud save service's. Any other audience is ErrUnknownAudience. 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) RemoveIdentity(ctx context.Context, accountID, provider string) error

RemoveIdentity removes the account's identity of provider even when it is the account's last way to sign in, which leaves the account reachable only through its open sessions. UnlinkIdentity is the checked form. It returns ErrNotFound when the account has no identity of the provider.

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

RevokeSessions ends every session of an account, so no device of it can refresh, and returns how many there were. Tokens already issued stay valid until they expire. It returns ErrNotFound for no such account.

func (s *Service) SearchAccounts(ctx context.Context, q AccountQuery, cursor string, limit int) (AccountPage, error)

SearchAccounts returns a page of up to limit accounts matching q after cursor, in ascending order of ID; see Store.SearchAccounts.

func (s *Service) Sessions(ctx context.Context, accountID string) ([]Session, error)

Sessions returns the open sessions of an account, oldest first.

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. The session is opened only while the password checked is still the account's, so a sign-in racing ChangePassword with the old password gets ErrInvalidCredentials rather than a session that outlives the change.

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.

func (s *Service) Suspend(ctx context.Context, accountID string, until time.Time, reason, actor string) (Suspension, error)

Suspend suspends an account until until (zero for until it is lifted) with a reason shown to the player, recording actor, such as "op:ada", as who set it. It replaces a suspension the account has. The account's sign-ins and refreshes, and the changes its player makes over HTTP, are refused with a *SuspendedError while it is in force; its sessions are kept, and tokens already issued still read the account until they expire. It returns ErrNotFound for no such account.

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

UnlinkIdentity removes the account's identity of provider unless it is the account's last way to sign in: ErrNotFound when the account has none, ErrLastCredential when it has no email address and no other identity. The store checks and removes in one step, so concurrent unlinks cannot leave the account without a credential.

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

Unsuspend lifts an account's suspension, if it has one, so it signs in and refreshes again. It returns ErrNotFound for no such account.

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
	// PasswordHash, set for a session opened with the account's password, is the password hash the password was checked against. CreateSession then stores the session only while that is still the account's password hash, so a sign-in that checked the old password just before ChangePasswordHash replaced it cannot open a session that outlives the change. The store does not keep it, and Session returns it empty.
	PasswordHash string
}

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

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

SessionDirectory keeps the device sessions of accounts under a SessionPolicy, detecting a reused secret after rotation. It is safe for concurrent use.

func NewSessionDirectory(policy SessionPolicy, now func() time.Time) *SessionDirectory

NewSessionDirectory returns an empty directory applying policy, reading the time from now (time.Now when nil).

func (d *SessionDirectory) Check(id, secretHash string) (DeviceSession, error)

Check returns session id when secretHash is its current secret, or its previous secret within the rotation overlap, and marks it used. An unknown session is ErrInvalidCredentials, an idle or too old one is removed and ErrSessionExpired, and any other secret revokes the session as stolen and returns ErrSessionReuse.

func (d *SessionDirectory) List(account string) []DeviceSession

List returns the sessions of account, most recently used first.

func (d *SessionDirectory) Open(s DeviceSession, secretHash string)

Open records session s with the secret whose hash is secretHash, as generation 1, setting its creation time to now when zero and its expiry from the policy's AbsoluteTTL.

func (d *SessionDirectory) Refresh(id, secretHash, newSecretHash string) (DeviceSession, error)

Refresh checks session id as Check does and, when the policy rotates secrets, replaces its secret with newSecretHash, keeping the old one valid for the policy's Overlap.

func (d *SessionDirectory) RevokeAll(account, except string) int

RevokeAll removes every session of account except the one whose ID is except, and returns how many it removed.

func (d *SessionDirectory) Sweep() int

Sweep removes the sessions that are idle or too old under the policy and returns how many it removed.

type SessionPolicy struct {
	IdleTTL, AbsoluteTTL time.Duration
	Rotate               bool
	Overlap              time.Duration
}

SessionPolicy decides how long a device session lasts: it expires after IdleTTL without use and AbsoluteTTL after it opened (zero disables either), and when Rotate is set each refresh replaces its secret, the old secret staying valid for Overlap.

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 while it is still oldHash, as rehashing a password at a new cost does, so a rehash cannot undo a password change that happened since the password was checked. It returns ErrNotFound for no such account, an account without an email address, or a hash other than oldHash, and leaves the account's sessions alone.
	SetPasswordHash(ctx context.Context, id, oldHash, newHash string) error
	// ChangePasswordHash replaces the password hash of an account with an email address and deletes every session of the account except keepSession (none when empty or not the account's), all or nothing. It is atomic with CreateSession: a session of the account is either created before the change and deleted by it, or created after it. It returns ErrNotFound for no such account or an account without an email address.
	ChangePasswordHash(ctx context.Context, id, passwordHash, keepSession 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
	// UnlinkIdentity removes the account's identity for provider unless it is the account's last way to sign in. It returns ErrNotFound for no such account or no identity of the provider, and ErrLastCredential when the account has no email address and no other identity. The check and the removal are atomic, so two devices unlinking an account's two identities at once cannot both succeed.
	UnlinkIdentity(ctx context.Context, id, provider string) 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, ErrTaken when the session ID exists, ErrInvalidCredentials when s.PasswordHash is set and is no longer the account's password hash, and ErrSuspended when the account's suspension is in force at s.Created.
	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
	// DeleteAccount removes an account and all linked identities and sessions.
	DeleteAccount(ctx context.Context, id string) error
	// SearchAccounts returns up to limit (1 to MaxSearchLimit, else ErrInvalidSearchLimit) accounts matching q with IDs after cursor ("" for the first page), in ascending order of ID, and the cursor of the next page. Paging by ID keeps the pages stable while accounts are created: an account that existed when the search began appears exactly once, wherever new ones land.
	SearchAccounts(ctx context.Context, q AccountQuery, cursor string, limit int) (AccountPage, error)
	// SetSuspension sets the suspension of an account, replacing any it has, or lifts it when s is nil. It returns ErrNotFound for no such account. It is atomic with CreateSession: a session of the account is created either before the suspension or after it, and CreateSession refuses one while it is in force.
	SetSuspension(ctx context.Context, id string, s *Suspension) error
	// RemoveIdentity removes the account's identity for provider even when it is the account's last way to sign in, for an operator who means to. It returns ErrNotFound for no such account or no identity of the provider.
	RemoveIdentity(ctx context.Context, id, provider string) error
	// Sessions returns the sessions of an account, in order of creation and then of ID; none for an unknown account.
	Sessions(ctx context.Context, id string) ([]Session, error)
	// DeleteSessions deletes every session of an account and returns how many there were. It returns ErrNotFound for no such account.
	DeleteSessions(ctx context.Context, id string) (int, 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.

type SuspendedError struct {
	// Until is when the suspension ends; zero means it lasts until an operator lifts it.
	Until time.Time
	// Reason is the reason shown to the player, empty for none.
	Reason string
}

SuspendedError is the error a sign-in or refresh of a suspended account returns. errors.Is(err, ErrSuspended) reports it.

func (e *SuspendedError) Error() string

Error implements error.

func (e *SuspendedError) Is(target error) bool

Is reports whether target is ErrSuspended.

type Suspension struct {
	// Since is when the suspension was set, to the millisecond.
	Since time.Time
	// Until is when the suspension ends, to the millisecond; zero means it lasts until an operator lifts it.
	Until time.Time
	// Reason is the reason shown to the player, empty for none.
	Reason string
	// Actor names who set the suspension, such as "op:ada".
	Actor string
}

Suspension keeps an account from signing in and refreshing its sessions until it ends. Its sessions are kept, so they refresh again once it is lifted or over; tokens issued before it began stay valid until they expire.

func (s *Suspension) ActiveAt(t time.Time) bool

ActiveAt reports whether the suspension is in force at t: it has no end or ends after t. A nil suspension is never active.