token

package
v1.33.1 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package token generates and checks opaque bearer tokens.

A token has the shape "<prefix>_<body>": prefix is 2 to 12 characters from [a-z0-9] and body is 43 base62 characters drawn uniformly with crypto/rand, which carries 256 bits of entropy. Applications store only the SHA-256 Hash of a token and look it up by that digest.

The prefix tells token kinds apart. With an application prefix such as "app":

  • API key: "app_"
  • OAuth access token: "appat_"
  • OAuth refresh token: "apprt_"
  • session: "apps_"

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Check

func Check(prefix, value string) bool

Check reports whether value has the given prefix and a well-formed body: the separator, exactly 43 base62 characters, nothing else. Use it before hashing so garbage never reaches the database.

func Equal

func Equal(a, b []byte) bool

Equal compares two hashes in constant time.

func Hash

func Hash(value string) []byte

Hash returns the SHA-256 digest of value. It is deterministic and unsalted: values carry 256 bits of entropy so neither brute force nor precomputation applies, and the digest is what the store looks up by.

func Hint

func Hint(value string) string

Hint returns the last four characters of value, or "" when it is shorter.

func Prefix

func Prefix(value string) (string, bool)

Prefix returns the part before the first "_", and false when value has no "_" or the prefix is empty.

func ValidPrefix

func ValidPrefix(prefix string) bool

ValidPrefix reports whether prefix matches ^[a-z0-9]{2,12}$. Packages that derive token prefixes from configuration validate them with this rule.

Types

type Token

type Token struct {
	Value string
	Hash  []byte
	Hint  string
}

Token is a freshly generated credential. Value is shown to the user once. Hash is what the application stores. Hint is the last four characters of Value, safe to show in lists.

func Generate

func Generate(prefix string) (Token, error)

Generate returns a token "<prefix>_<body>". body is 43 characters from the base62 alphabet [0-9A-Za-z], drawn uniformly with crypto/rand, so it holds 256 bits of entropy. prefix must match ^[a-z0-9]{2,12}$ and may itself contain no "_". Returns ez.EINVALID for a bad prefix, ez.EINTERNAL when the random source fails.

Jump to

Keyboard shortcuts

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