Documentation
¶
Overview ¶
Package authtoken issues and verifies the short-lived player tokens of the accounts service.
A token is a compact JWT (RFC 7519) signed with Ed25519 ("alg": "EdDSA"). The account service holds the private key and issues tokens with a Signer; a game server holds only the public keys, as a KeySet loaded from a YAML file, and checks tokens with a Verifier. Verifying makes no network call: it decodes the token, checks the signature against a known key, then the issuer, audience and expiry.
The audience names the one consumer a token is for. A key set's audience is the game's servers, which a player sends a token to when joining a match; a service that acts on the player's behalf, such as cloud save or a leaderboard, verifies tokens for its own audience with NewVerifierFor, so a token handed to a game server cannot be replayed against it.
The package depends on the standard library and go.yaml.in/yaml/v3 only, so a game server that verifies tokens links none of the account service's password hashing or database drivers.
Index ¶
- Constants
- Variables
- func GenerateKey(r io.Reader) (ed25519.PrivateKey, error)
- func KeyID(pub ed25519.PublicKey) string
- func MarshalPrivateKey(key ed25519.PrivateKey) ([]byte, error)
- func ParsePrivateKey(data []byte) (ed25519.PrivateKey, error)
- type Claims
- type KeySet
- type PublicKey
- type Signer
- type Verifier
Examples ¶
Constants ¶
const AccountServiceAudience = "accounts"
AccountServiceAudience is the audience of tokens for the account service's own bearer endpoints (accounts.ServiceAudience). Another service must not accept it, or whoever runs that service could replay a player's token to read or link the player's account.
const KeySetVersion = 1
KeySetVersion is the key set file schema version this package reads and writes.
const MaxLength = 4096
MaxLength is the longest token Verify decodes; a longer string is refused before any work.
Variables ¶
var ( // ErrMalformed reports a token that is not a well-formed token of this package. ErrMalformed = errors.New("authtoken: malformed") // ErrUnknownKey reports a token signed with a key ID the verifier does not hold. ErrUnknownKey = errors.New("authtoken: unknown signing key") // ErrSignature reports a token whose signature does not match its contents. ErrSignature = errors.New("authtoken: bad signature") // ErrIssuer reports a token from another issuer. ErrIssuer = errors.New("authtoken: wrong issuer") // ErrAudience reports a token meant for another audience. ErrAudience = errors.New("authtoken: wrong audience") // ErrExpired reports a token past its expiry. ErrExpired = errors.New("authtoken: expired") // ErrNotYetValid reports a token issued after the verifier's current time. ErrNotYetValid = errors.New("authtoken: not yet valid") )
Functions ¶
func GenerateKey ¶
func GenerateKey(r io.Reader) (ed25519.PrivateKey, error)
GenerateKey returns a new Ed25519 signing key read from r, or crypto/rand when r is nil.
func KeyID ¶
KeyID returns the ID of a public key: the first 8 bytes of its SHA-256 in hex. Signers and key sets derive IDs this way, so an ID always names one key.
func MarshalPrivateKey ¶
func MarshalPrivateKey(key ed25519.PrivateKey) ([]byte, error)
MarshalPrivateKey encodes key as a PKCS #8 "PRIVATE KEY" PEM block, the text form the account service keeps its signing key in.
Example ¶
The service keeps its signing key as a PKCS #8 PEM block.
package main
import (
"bytes"
"crypto/ed25519"
"fmt"
"github.com/nsgo-dev/game/pkg/online/accounts/authtoken"
)
func main() {
key := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, ed25519.SeedSize))
pem, err := authtoken.MarshalPrivateKey(key)
if err != nil {
fmt.Println(err)
return
}
back, err := authtoken.ParsePrivateKey(pem)
fmt.Println(err, bytes.HasPrefix(pem, []byte("-----BEGIN PRIVATE KEY-----")), back.Equal(key))
}
Output: <nil> true true
func ParsePrivateKey ¶
func ParsePrivateKey(data []byte) (ed25519.PrivateKey, error)
ParsePrivateKey decodes a PKCS #8 PEM block holding an Ed25519 private key. Errors never include the key material.
Types ¶
type Claims ¶
type Claims struct {
// Issuer is the account service that issued the token.
Issuer string
// Subject is the account ID the token stands for.
Subject string
// Audience is the consumer the token is meant for: the game's servers (the key set's audience) or a service such as cloud save.
Audience string
// IssuedAt is when the token was issued, to the second.
IssuedAt time.Time
// Expires is when the token stops being valid, to the second.
Expires time.Time
// ID is the token's unique random ID.
ID string
// KeyID is the ID of the key that signed the token.
KeyID string
}
Claims are what a verified token says.
type KeySet ¶
type KeySet struct {
// Version is the schema version; it must be KeySetVersion.
Version int `yaml:"version"`
// Issuer is the issuer the verifier accepts.
Issuer string `yaml:"issuer"`
// Audience is the audience the verifier accepts.
Audience string `yaml:"audience"`
// Keys are the public keys tokens may be signed with.
Keys []PublicKey `yaml:"keys"`
}
KeySet is the public half of an account service's signing keys, kept in a YAML file a game server loads to verify tokens offline:
version: 1
issuer: https://accounts.example.com
audience: my-game
keys:
- id: 2317febd373fcbcd
key: hze+0cYruVRddgjkbHzgCeWWJbEsBkn6K8JNHRDf6Wg=
Several keys let a service rotate its signing key: publish the new key beside the old one, switch the service to it, and drop the old key once its last tokens have expired.
func ParseKeySet ¶
ParseKeySet decodes and validates a YAML key set. Unknown fields and trailing documents are refused.
Example ¶
A key set is the YAML file of public keys a game server loads; unknown fields are refused.
package main
import (
"bytes"
"crypto/ed25519"
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/online/accounts/authtoken"
)
func main() {
key := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, ed25519.SeedSize))
signer, _ := authtoken.NewSigner(key, "https://accounts.example.com", "my-game", time.Minute)
data, err := signer.KeySet().Marshal()
if err != nil {
fmt.Println(err)
return
}
ks, err := authtoken.ParseKeySet(data)
fmt.Println(err, ks.Issuer, len(ks.Keys), ks.Keys[0].ID == authtoken.KeyID(key.Public().(ed25519.PublicKey)))
_, err = authtoken.ParseKeySet(append(data, "extra: 1\n"...))
fmt.Println(err != nil)
}
Output: <nil> https://accounts.example.com 1 true true
func (*KeySet) Marshal ¶
Marshal validates ks and encodes it as deterministic 2-space YAML, keys in their order.
type PublicKey ¶
type PublicKey struct {
// ID is KeyID of the key; it must match the key.
ID string `yaml:"id"`
// Key is the 32-byte public key in standard base64.
Key string `yaml:"key"`
}
PublicKey is one Ed25519 public key of a key set.
type Signer ¶
type Signer struct {
// Now is the clock tokens are issued by; nil uses time.Now.
Now func() time.Time
// Rand fills token IDs; nil uses crypto/rand. Issue reads it without a lock, so a signer used from several goroutines needs a reader that is safe for concurrent use.
Rand io.Reader
// contains filtered or unexported fields
}
Signer issues tokens with one private key. Its fields other than Now are fixed by NewSigner.
Example ¶
The account service issues tokens with a Signer; a game server checks them with a Verifier built from the public key set alone, with no network call.
package main
import (
"bytes"
"crypto/ed25519"
"errors"
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/online/accounts/authtoken"
)
func main() {
key := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, ed25519.SeedSize))
now := time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)
signer, err := authtoken.NewSigner(key, "https://accounts.example.com", "my-game", 15*time.Minute)
if err != nil {
fmt.Println(err)
return
}
signer.Now = func() time.Time { return now }
tok, _, err := signer.Issue("player-42")
if err != nil {
fmt.Println(err)
return
}
v, _ := authtoken.NewVerifier(signer.KeySet())
v.Now = func() time.Time { return now.Add(10 * time.Minute) }
claims, err := v.Verify(tok)
fmt.Println(err, claims.Subject, claims.Audience, claims.Expires.Format(time.RFC3339))
v.Now = func() time.Time { return now.Add(15 * time.Minute) }
_, err = v.Verify(tok)
fmt.Println(errors.Is(err, authtoken.ErrExpired))
}
Output: <nil> player-42 my-game 2026-11-23T12:15:00Z true
func NewSigner ¶
NewSigner returns a signer that issues tokens for audience from issuer, each valid for ttl (at least one second, in whole seconds).
func (*Signer) Issue ¶
Issue returns a token for subject and the signer's audience, valid from now for the signer's TTL, and its claims.
func (*Signer) IssueFor ¶
IssueFor returns a token for subject meant for audience instead of the signer's own, valid from now for the signer's TTL, and its claims. Only a verifier built for that audience (NewVerifierFor) accepts it.
type Verifier ¶
type Verifier struct {
// Leeway tolerates clock skew between the account service and the verifier: a token stays valid until Leeway past its expiry and is accepted up to Leeway before its issue time.
Leeway time.Duration
// Now is the clock tokens are checked against; nil uses time.Now.
Now func() time.Time
// contains filtered or unexported fields
}
Verifier checks tokens offline against a key set. Build one with NewVerifier; it is safe for concurrent use.
func NewVerifier ¶
NewVerifier returns a verifier for the keys, issuer and audience of ks: the one a game server uses.
func NewVerifierFor ¶
NewVerifierFor returns a verifier for the keys and issuer of ks that accepts only tokens for audience, such as the one a cloud save service verifies. It refuses tokens for the key set's own audience unless audience is that one.
func (*Verifier) AcceptsGameServerTokens ¶
AcceptsGameServerTokens reports whether the verifier accepts tokens for the audience of the key set it was built from: the tokens sign-in returns and a player sends every game server it joins. A service that acts on a player's own data, such as cloud save, must refuse such a verifier, however its audience was named.