GitHubGet started
Multiplayer & Modding

accounts

github.com/nsgo-dev/game/pkg/online/accounts is a self-hostable player account service. A player starts as a guest, upgrades to an email address or links an OAuth or platform identity (Game Center, Play Games, Steam) without losing their data, and every device gets short-lived tokens a game server verifies offline.

The service is server-side code in its own packages. A game client or game server that does not import them links none of their dependencies (argon2id from golang.org/x/crypto, the SQLite and Postgres drivers); a game server that verifies tokens imports only accounts/authtoken, which needs the standard library and the YAML package.

Package What it holds
accounts Service, Config, the Store interface, MemoryStore, argon2id password hashing and the HTTP Handler
accounts/authtoken Ed25519 token Signer and offline Verifier, the KeySet YAML file and PEM signing keys
accounts/sqlitestore A Store in a SQLite file (pure Go, no cgo); every target but the web
accounts/pgstore A Store in Postgres, shared by several service processes
accounts/sqlstore The SQL schema and queries both stores share
accounts/storetest The Store contract tests, for a store of your own
accounts/identity OIDC and Sign in with Apple JWT verification, plus redacted exchange adapters for Steam and mini-program providers
cmd/accountsd A standalone HTTP server for guests and email accounts

Accounts, sessions and tokens

An account is a permanent random ID. Key everything the game keeps for a player (saves, progress, purchases) by that ID: linking an email address or an identity never changes it, so a guest who upgrades keeps their data.

Every sign-in returns Credentials:

  • Session is a long-lived secret the device stores. It gets new tokens with Refresh and is revoked by SignOut. For a guest it is the only way back into the account.
  • Token is a short-lived signed token the game sends its server. It expires after the configured tokenTTL, and it is good only for game servers: see Token audiences.
  • Created reports whether the sign-in created the account.
svc, err := accounts.New(cfg, accounts.Options{
	Store:      store,
	Key:        key, // from authtoken.ParsePrivateKey
	Identities: map[string]accounts.IdentityVerifier{"gamecenter": gameCenter, "steam": steam},
	Logger:     slog.Default(),
})

guest, _ := svc.CreateGuest(ctx)                                  // play at once
_ = svc.LinkEmail(ctx, guest.AccountID, "ada@example.com", pass)  // upgrade, same ID
again, _ := svc.SignInEmail(ctx, "ada@example.com", pass)         // a second device
fresh, _ := svc.Refresh(ctx, again.Session)                       // a new token
saves, _ := svc.RefreshFor(ctx, again.Session, "cloudsave")       // a token for cloud save
Method What it does
CreateGuest A new account with neither an email address nor an identity (ErrGuestsDisabled with disableGuests)
Register A new account with an email address and password
LinkEmail Gives an account without one an email address and password
SignInEmail Signs in with an email address and password
SignInIdentity Signs in with a provider credential, creating the account when the identity is new
LinkIdentity Links a provider identity to an account
ChangePassword Replaces an email account's password after checking the old one, and signs out every other device
UnlinkIdentity Removes a provider identity unless it is the account's last way to sign in
Refresh / SignOut A new game server token for a session / revokes the session
RefreshFor A new token for a session meant for another audience: ServiceAudience or one of audiences
Profile The account, its email address and its identities; Profile.Guest reports a guest

Errors are ErrNotFound, ErrTaken (the address or identity belongs to another account), ErrAlreadyLinked, ErrLastCredential, ErrInvalidCredentials (never saying whether the address, the password or the session was wrong), ErrInvalidEmail, ErrWeakPassword, ErrUnknownProvider and ErrUnknownAudience (a RefreshFor audience the configuration does not offer).

Identities

An IdentityVerifier turns a credential from the device into the provider's stable subject for the player:

steam := identity.Steam(func(ctx context.Context, ticket string) (string, error) {
	return steamWebAPI.AuthenticateUserTicket(ctx, ticket) // the SteamID
})

apple := identity.Apple("com.example.game")

accounts/identity verifies OIDC ID tokens and Apple's signed identity tokens (RS256, ES256 or EdDSA) against a JWKS endpoint, checking issuer, audience, expiry, not-before and the signature; a token it refuses is an error wrapping identity.ErrInvalidToken. It does not check a nonce: a game that sends one must compare the token's nonce claim itself. identity.Steam and identity.MiniProgram wrap a game's server-side exchange callback and redact provider errors. Game Center and Play Games credentials still need the corresponding NSGo APIs before a built-in verifier can be added. The game supplies verifiers under provider names of its choosing (a-z, 0-9, ., _, -, up to 32 characters).

Linking an identity lets a second device sign in to the same account with SignInIdentity. An account has at most one identity per provider, and an identity belongs to one account: linking one that another account has returns ErrTaken. Two devices signing in with a new identity at the same time get one account between them.

The service never shows a verifier's error to the caller or logs it, since it may quote the credential; the caller gets ErrInvalidCredentials.

Token audiences

A token names the one consumer it is for in its audience, and each consumer accepts only its own:

Audience Who accepts it How a device gets one
audience of the configuration (my-game) the game's servers, with authtoken.NewVerifier every sign-in, Refresh
accounts (ServiceAudience) the service's own GET /v1/me, POST /v1/link/*, password and identity management endpoints RefreshFor(session, "accounts")
an entry of audiences (cloudsave, leaderboard) that service, with authtoken.NewVerifierFor RefreshFor(session, "cloudsave")

A player sends the game server token to every server it joins, and whoever runs that server can replay it until it expires. Because cloud save, the leaderboard and the account service refuse it, a game server learns who the player is and nothing more: it cannot read, overwrite or purge the player's saves, submit scores for them, or link an email address or identity to their account. A device keeps its session to itself and sends each service only a token for that service.

Verifying tokens on a game server

A token is a compact JWT signed with Ed25519 ("alg": "EdDSA") holding the issuer, the account ID as subject, the audience, the issue and expiry times and a random ID. The game server loads the service's public keys from a key set file and verifies each token without a network call:

data, _ := os.ReadFile("keys.yaml")
ks, err := authtoken.ParseKeySet(data)
v, err := authtoken.NewVerifier(ks)
v.Leeway = 5 * time.Second // clock skew between the two machines

claims, err := v.Verify(tok)
if err != nil { /* refuse the player */ }
player := claims.Subject // the account ID

NewVerifier accepts the key set's audience, the game server one. A service that acts for the player verifies its own audience instead, with authtoken.NewVerifierFor(ks, "cloudsave"). Verify checks the signature, the issuer, the audience and the expiry, and its errors wrap ErrMalformed, ErrUnknownKey, ErrSignature, ErrIssuer, ErrAudience, ErrExpired or ErrNotYetValid. Tokens longer than MaxLength are refused before any work. A revoked session stops getting new tokens, but tokens already issued stay valid until they expire, so keep tokenTTL short.

The key set file:

version: 1
issuer: https://accounts.example.com
audience: my-game
keys:
  - id: 2317febd373fcbcd
    key: hze+0cYruVRddgjkbHzgCeWWJbEsBkn6K8JNHRDf6Wg=

Each id is the first 8 bytes of the key's SHA-256 in hex and must match its key. To rotate the signing key, add the new key beside the old one, give game servers the new file, switch the service to the new key, and drop the old key once its last tokens have expired. Give the service the old keys too, as Options.KeySet (or accountsd serve -keyset keys.yaml): it then accepts bearer tokens signed with any key in the set, and GET /v1/keys serves the signing key followed by those keys, so tokens issued before the restart keep working on the service and on game servers until the old key is removed from the file.

Configuration

The service reads a versioned 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
Field Meaning
version Schema version, 1
issuer / audience Written into every token and checked by verifiers; audience names the game's servers and the key set, and may not be accounts
audiences The other services a device may get tokens for with RefreshFor, such as cloudsave and leaderboard; never the game's audience or accounts, which is always available; omitted when empty
tokenTTL Token lifetime, whole seconds from 1s to 24h
disableGuests Refuses CreateGuest, so every account starts with an email address or an identity
password.minLength Fewest characters in a password, at least 8; passwords are at most 1024 bytes
password.argon2id The argon2id cost: passes, memory in KiB and lanes
allowedOrigins Web origins whose pages may call the service; omitted when empty
metrics The address accountsd serve serves /healthz, /readyz and /metrics on, such as 127.0.0.1:9101, a listener of its own (see Health and metrics); omitted when unset, and then none of them is served

ParseConfig refuses unknown fields, trailing documents, out-of-range values, a metrics address without a port and an origin that is duplicated or has a path, query, fragment, user, wildcard, port outside 1 to 65535 or scheme other than http and https. Config.Marshal writes the canonical form: the fields in the order above, durations in their shortest text (15m, not 15m0s), disableGuests only when it is true, audiences and allowedOrigins only when they have entries and metrics only when set. A file in that form, such as one Marshal or accountsd init wrote, reads back and writes again unchanged; a hand-written file in another order or spelling is normalized. DefaultConfig returns the settings shown, without origins. A version 1 file without audiences still reads, but its service then issues tokens only for game servers and for itself, so add the audiences of the cloud save and leaderboard services it serves.

Passwords and secrets

  • Passwords are stored only as argon2id hashes in the PHC format ($argon2id$v=19$m=19456,t=2,p=1$salt$hash), OWASP's recommended cost by default. A sign-in with a password hashed at an older cost rehashes it at the configured one. Options.MaxConcurrentHashes bounds how many hashes run at once, so a burst of sign-ins cannot take all the server's memory.
  • An unknown email address takes as long to refuse as a wrong password, so sign-in does not reveal whether an address has an account. Register and LinkEmail do: they answer ErrTaken (409 taken) for an address that belongs to an account, so anyone can test an address there without its password. Rate-limit those requests per client.
  • Register, LinkEmail and ChangePassword refuse a password with fewer characters than password.minLength or more than MaxPasswordBytes bytes with ErrWeakPassword. accounts.ValidatePassword applies the same rule without hashing, so a client form can check a password before it submits it.
  • Session secrets are 256 random bits; the store keeps only their SHA-256.
  • ChangePassword(ctx, account, keep, old, new) ends every session of the account except keep, the session of the device that asks, so a device that signed in with a leaked password can no longer refresh. With a zero keep every session ends, the caller's too; a keep of another account is ErrInvalidCredentials. A sign-in that checked the old password a moment before the change gets ErrInvalidCredentials rather than a session that outlives it, and rehashing an old password at a new cost cannot undo a change. Tokens already issued stay valid until they expire.
  • UnlinkIdentity refuses to remove the last way to sign in (ErrLastCredential): the store checks and removes in one step, so two devices unlinking an account's two identities at once cannot both succeed.
  • Credentials.Session and Credentials.Token are Secret values, which print, log and marshal as [redacted]; Reveal returns the value for the one place that sends it. The service logs account events (created, signed in, linked) with account IDs and provider names, never a password, session secret, token or identity credential.
  • Signing keys are PKCS #8 PEM files written with mode 0600; a Postgres DSN is read from the environment, not the command line.

Storage

Store is the interface the service keeps its records in. Implementations enforce uniqueness atomically, so two devices racing to claim one email address or identity cannot both succeed. They also make UnlinkIdentity's last-credential check, ChangePasswordHash's revocation of the other sessions and CreateSession's password and suspension checks each atomic with the change they guard.

For operators, a store also searches accounts (SearchAccounts by ID or email prefix, identity and creation time, in pages ordered by ID), sets and lifts a suspension (SetSuspension), removes an identity without the last-credential check (RemoveIdentity), and lists and deletes an account's sessions (Sessions, DeleteSessions). Account, AccountByEmail, AccountByIdentity and SearchAccounts return the account's Suspension, which the account's JSON and its data export leave out.

store, err := sqlitestore.Open(ctx, "accounts.db")                  // one service process
store, err := pgstore.Open(ctx, os.Getenv("ACCOUNTS_POSTGRES_DSN")) // several processes

sqlitestore uses the pure-Go modernc.org/sqlite driver with write-ahead logging and one connection; pgstore uses github.com/jackc/pgx/v5, takes an advisory lock while it creates the schema, and locks an account's row (Dialect.RowLock) while it changes the account's credentials or opens a session of it. Both create their tables when missing and refuse a database whose schema is newer than they know. The schema is at version 2, which added the suspension columns of accounts; opening a version 1 database adds them in the same transaction that records the new version. NewMemoryStore keeps everything in memory for tests and prototypes.

A store of your own passes storetest.Run:

func TestContract(t *testing.T) {
	storetest.Run(t, func(t *testing.T) accounts.Store { return openEmptyStore(t) })
}

HTTP

Service.Handler serves the service with JSON bodies; every response carries Cache-Control: no-store:

Request Body Answer
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"}, audience optional credentials
POST /v1/signout {"session"} 204
POST /v1/link/email {"email", "password"}, with an accounts bearer token 204
POST /v1/link/identity {"provider", "credential"}, with an accounts bearer token 204
POST /v1/password {"oldPassword", "newPassword", "session"}, with an accounts bearer token; ends every other session of the account 204
POST /v1/unlink/identity {"provider"}, with an accounts bearer token 204
GET /v1/me accounts bearer token profile
GET /v1/me/export accounts bearer token the account's data export
DELETE /v1/me accounts bearer token 204
GET /v1/keys the key set as YAML

Credentials are {"account", "session", "token", "expires", "created"}, with status 201 when the account is new. A sign-in's token is for game servers; refresh with audience returns one for that audience instead. The bearer endpoints accept only a token for accounts and answer invalid_token to any other. Errors are {"error": code}: invalid_credentials and invalid_token 401, guests_disabled 403, suspended 403 (see Suspensions), 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 while waiting for a password hash slot under load), and internal 500. POST /v1/password keeps only the request's session, which must belong to the bearer token's account (invalid_credentials otherwise); without session every session of the account ends, the caller's too. Request bodies are limited to 32 KiB and unknown fields are refused. For allowedOrigins the handler answers CORS preflight requests and allows Authorization and Content-Type; other origins receive no CORS headers. The handler does not limit request rates: run it behind TLS and a rate limiter.

GET /v1/me/export returns the account's data as {"account": {"id", "email", "created"}, "identities": [{"provider", "subject"}]} (accounts.Export), without passwords, password hashes, session secrets or tokens. DELETE /v1/me permanently deletes the account with its email address, identities and sessions, so no device can refresh or sign in to it again; tokens already issued stay valid until they expire. Deleting the account does not erase the player's cloud saves or leaderboard scores: the deployment has to remove those from its other services before it offers full account erasure.

accountsd

cmd/accountsd runs the service for guests and email accounts:

accountsd init   -config accounts.yaml -issuer https://accounts.example.com -audience my-game
accountsd genkey -config accounts.yaml -key key.pem -keyset keys.yaml
accountsd serve  -config accounts.yaml -key key.pem -keyset keys.yaml -sqlite accounts.db -addr :8080
ACCOUNTS_POSTGRES_DSN=postgres://... accountsd serve -config accounts.yaml -key key.pem -keyset keys.yaml -postgres

init never overwrites a configuration and writes no allowedOrigins; if a web build calls the service from another origin, add the game page's origin to allowedOrigins in accounts.yaml before serve. genkey never overwrites a key and adds the new public key to the key set file, the first step of a rotation; it replaces the file through a temporary file and a rename, so a game server reading it never sees half of it, and it removes the new key again when the key set cannot be written. serve -keyset accepts and serves every key in the key set, so tokens signed with an old key keep working on the service after a rotation. serve logs JSON to stderr and stops on SIGINT or SIGTERM. With metrics set, serve also answers /healthz, /readyz and /metrics on that address, exporting requests, sign-ins and their failures, accounts and open sessions (see Health and metrics). A game that links platform identities builds its own command around accounts.New with its verifiers.

Operator access

An optional admin: block at the end of accounts.yaml makes serve run an admin listener on an address of its own, for the operators in its operators file; without it no admin route exists. accountsd admin-token -config accounts.yaml -key key.pem -operator ci -ttl 24h prints a bearer token for an operator of the operators file the admin: block names (or -operators names, without the block), signed with the service's key for the admin audience, which every service's admin listener accepts. The configuration refuses admin as audience or in audiences, so no player can get such a token.

Operator routes

serve adds the service's operator routes (Service.AdminRoutes) to the admin listener. Each requires one permission, and the listener writes one audit record of every call, reads included since they return personal data, with the operator, the action and account:<id>; a search's record names accounts and holds its query and how many accounts it returned:

Request Permission Answer
GET /admin/v1/accounts?q=&cursor= accounts.read {"accounts": [...], "next"}
GET /admin/v1/accounts/{id} accounts.read the account with guest, identities, sessions and suspension
POST /admin/v1/accounts/{id}/suspend {"until", "reason"} accounts.suspend the suspension
DELETE /admin/v1/accounts/{id}/suspend accounts.suspend (audited as accounts.unsuspend) 204
POST /admin/v1/accounts/{id}/unlink {"provider", "force"} accounts.unlink 204
POST /admin/v1/accounts/{id}/sessions/revoke accounts.revoke {"revoked": n}
GET /admin/v1/accounts/{id}/export accounts.export the account's data export
DELETE /admin/v1/accounts/{id} accounts.delete 204

Search takes q, which is an email prefix when it contains @, provider:subject when it contains : (such as steam:76561198000000000), and an ID prefix otherwise, or instead of q the fields id (ID prefix), email (email prefix), provider and subject. from and to bound the creation time in RFC 3339 (from inclusive, to exclusive) and limit is 1 to 100, 50 by default (a store's SearchAccounts takes up to MaxSearchLimit, 1000, and refuses more with ErrInvalidSearchLimit); an unknown or repeated parameter is bad_request. Pages are ordered by account ID and next continues after the last account of a page, so accounts created while an operator pages neither repeat nor push others off a page. An account is {"id", "email", "created", "suspension"}, the suspension {"since", "until", "reason", "by", "active"} with until absent for one without an end; a session is {"id", "created"}, never its secret or hash.

Unlinking an account's last way to sign in answers last_credential 409 unless the request sets "force": true; the account is then reachable only through the sessions it still has. Revoking sessions ends every session of the account, as ChangePassword does for the others. Errors are those of the player routes, plus invalid_suspension 400 for an until that is not RFC 3339 or not in the future, or a reason over 500 bytes. Of the built-in roles, viewer reads, support also suspends, revokes and exports, moderator suspends and revokes, and operator and owner may do everything.

Suspensions

Service.Suspend(ctx, id, until, reason, actor) suspends an account until until, or until it is lifted when until is zero, and Unsuspend lifts it. While it is in force, SignInEmail, SignInIdentity, Refresh and RefreshFor return a *SuspendedError (errors.Is(err, ErrSuspended)) carrying Until and the public Reason, and the HTTP routes answer 403 {"error": "suspended", "until", "reason"}, until absent for a suspension without an end and reason absent for none. A sign-in with a wrong password still gets invalid_credentials, so a suspension tells nothing to someone without the password. The store refuses a session of a suspended account in the same step it creates it, so a sign-in that read the account a moment before an operator suspended it opens no session either.

A suspension keeps the account's sessions: they refresh again once it ends or is lifted. Tokens issued before it began stay valid until they expire (tokenTTL, 15 minutes by default); a game server that must drop a player at once does so itself, for example by closing the player's connection. A suspended account's accounts token still reads it (GET /v1/me, GET /v1/me/export), but its changes, POST /v1/link/email, /v1/link/identity, /v1/unlink/identity, /v1/password and DELETE /v1/me, answer 403 suspended, so a player cannot unlink their identity or delete the account to sign up again with it unsuspended. An operator can still delete a suspended account with DELETE /admin/v1/accounts/{id}.

Session lifecycle core

accounts.SessionDirectory keeps device sessions in memory under a SessionPolicy: idle (IdleTTL) and absolute (AbsoluteTTL) expiry, and, with Rotate, a new secret on every Refresh. The previous secret stays valid for Overlap, so a client that retries a refresh whose reply it lost still gets in; any other secret revokes the session and returns ErrSessionReuse. List returns an account's sessions, most recently used first, RevokeAll signs out every session but one, and Sweep removes the expired ones. The service's Store, configuration and HTTP routes do not use the directory yet: their sessions still never expire.

Game-side session client

A game signs in through liveops.Account, which keeps the long-lived session in the platform keychain (cx.Secrets(), the Keychain or Android Keystore) and never in core.Storage. NewAccountForScope(cx, opts) restores a session saved by an earlier launch; SignInEmail and Register replace it, and SignOut deletes it and revokes it on the service. Token(ctx) returns a bearer token for AccountOptions.Audience (the game servers' audience when empty), refreshing it RefreshMargin (30 seconds by default) before it expires; concurrent callers share one refresh. Without a session, or once the service refuses it, Token returns liveops.ErrSignedOut and the saved session is deleted.

account := liveops.NewAccountForScope(cx, liveops.AccountOptions{
	URL:      "https://accounts.example.com",
	Audience: "cloudsave",
})
if _, err := account.Token(ctx); errors.Is(err, liveops.ErrSignedOut) {
	err = account.SignInEmail(ctx, email, password)
}
cloud, err := liveops.NewCloudClient(liveops.CloudClientOptions{
	URL:   "https://saves.example.com",
	Token: account.Token,
})

Use one Account per audience: a token for cloudsave is refused by the game servers, and the other way round (see Token audiences).

Game-side client

liveops.NewAccount keeps the long-lived session in a caller-supplied SecretStore, restores it on start, and hands out short-lived tokens for AccountOptions.Audience from Token, refreshing them before they expire with one request for all concurrent callers. NewAccountForScope adapts core.Secrets, the platform keychain, and keeps the session under session unless SecretsKey says otherwise. Register and SignInEmail save the new session; LinkEmail, LinkIdentity and Profile call the service with a token for its own audience, and LinkIdentity returns an *AccountConflict when the identity belongs to another account. SignOut revokes the session and deletes it from the keychain. A session the service no longer accepts makes Token sign out and return ErrSignedOut. Pass Account.Token to CloudClientOptions.Token or another service client.

Public profiles

accounts.PublicDirectory stores the public fields shown beside an account ID. Set normalizes usernames with NFKC and case folding, enforces the 3–20 character username policy and atomically claims names. Users batches lookups by IDs or usernames, returns each profile once in account ID order, and returns no email or linked identities. Set UsernameCooldown and NameFilter for game policy, and use Now for deterministic tests. The directory is provider-agnostic and can be backed by the account service or a database adapter.

China anti-addiction rules

The core-free online/antiaddiction package evaluates the mainland China minor play window using a server-supplied clock and holiday date set. It also exposes the under-8, 8–15 and 16–17 per-payment and monthly spending caps. Keep the clock and holiday calendar on the server. Client clocks and age flags are not authoritative. Releasing in Mainland China covers the rest of the publishing requirements.

See Deploying backend services for production store and daemon topology.

Edit this page