token

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package token 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 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

Examples

Constants

View Source
const KeySetVersion = 1

KeySetVersion is the key set file schema version this package reads and writes.

View Source
const MaxLength = 4096

MaxLength is the longest token Verify decodes; a longer string is refused before any work.

Variables

View Source
var (
	// ErrMalformed reports a token that is not a well-formed token of this package.
	ErrMalformed = errors.New("token: malformed")
	// ErrUnknownKey reports a token signed with a key ID the verifier does not hold.
	ErrUnknownKey = errors.New("token: unknown signing key")
	// ErrSignature reports a token whose signature does not match its contents.
	ErrSignature = errors.New("token: bad signature")
	// ErrIssuer reports a token from another issuer.
	ErrIssuer = errors.New("token: wrong issuer")
	// ErrAudience reports a token meant for another audience.
	ErrAudience = errors.New("token: wrong audience")
	// ErrExpired reports a token past its expiry.
	ErrExpired = errors.New("token: expired")
	// ErrNotYetValid reports a token issued after the verifier's current time.
	ErrNotYetValid = errors.New("token: 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

func KeyID(pub ed25519.PublicKey) string

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/accounts/token"
)

func main() {
	key := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, ed25519.SeedSize))
	pem, err := token.MarshalPrivateKey(key)
	if err != nil {
		fmt.Println(err)
		return
	}
	back, err := token.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 game the token is meant for.
	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

func ParseKeySet(data []byte) (*KeySet, error)

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/accounts/token"
)

func main() {
	key := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, ed25519.SeedSize))
	signer, _ := token.NewSigner(key, "https://accounts.example.com", "my-game", time.Minute)
	data, err := signer.KeySet().Marshal()
	if err != nil {
		fmt.Println(err)
		return
	}
	ks, err := token.ParseKeySet(data)
	fmt.Println(err, ks.Issuer, len(ks.Keys), ks.Keys[0].ID == token.KeyID(key.Public().(ed25519.PublicKey)))

	_, err = token.ParseKeySet(append(data, "extra: 1\n"...))
	fmt.Println(err != nil)
}
Output:
<nil> https://accounts.example.com 1 true
true

func (*KeySet) Marshal

func (ks *KeySet) Marshal() ([]byte, error)

Marshal validates ks and encodes it as deterministic 2-space YAML, keys in their order.

func (*KeySet) Merge

func (ks *KeySet) Merge(other *KeySet) (*KeySet, error)

Merge returns a key set with the keys of ks followed by those of other it lacks. Both must have the same issuer and audience.

func (*KeySet) Validate

func (ks *KeySet) Validate() error

Validate checks that ks is a version 1 key set with an issuer, an audience and at least one well-formed key, each under its own KeyID once.

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/accounts/token"
)

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 := token.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, _ := token.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, token.ErrExpired))
}
Output:
<nil> player-42 my-game 2026-11-23T12:15:00Z
true

func NewSigner

func NewSigner(key ed25519.PrivateKey, issuer, audience string, ttl time.Duration) (*Signer, error)

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

func (s *Signer) Issue(subject string) (string, Claims, error)

Issue returns a token for subject, valid from now for the signer's TTL, and its claims.

func (*Signer) KeyID

func (s *Signer) KeyID() string

KeyID is the ID of the signer's key.

func (*Signer) KeySet

func (s *Signer) KeySet() *KeySet

KeySet returns the public key set that verifies the signer's tokens.

func (*Signer) TTL

func (s *Signer) TTL() time.Duration

TTL is how long the signer's tokens stay valid.

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

func NewVerifier(ks *KeySet) (*Verifier, error)

NewVerifier returns a verifier for the keys, issuer and audience of ks.

func (*Verifier) Verify

func (v *Verifier) Verify(tok string) (Claims, error)

Verify checks tok and returns its claims. Errors wrap ErrMalformed, ErrUnknownKey, ErrSignature, ErrIssuer, ErrAudience, ErrExpired or ErrNotYetValid.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL