nwt

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2026 License: MIT Imports: 10 Imported by: 0

README

nwt

A golang library implementing Nostr Web Tokens.

Installation

go get github.com/pippellia-btc/nwt

Usage

Parsing a token from the Authorization header of an http.Request

token, err := nwt.Parse(request)
if err != nil {
    slog.Info("failed to parse token", "error", err)
}

Validating the token using the default StrictValidator

validator := nwt.StrictValidator{
    Identifier: "example.com"   // domain to be present in the audience claim
    ClockSkew: time.Minute      // tolerance for clock differences
}

if err := validator.Validate(token); err != nil {
    slog.Info("token is invalid", "reason", err)
}

Or create a custom validator by satisfying the Validator interface

// Validator wraps the Validate method for validating Tokens.
// The token is considered valid iff Validate returns nil.
//
// Implementations may enforce different policies for what constitutes a valid token,
// but are generally expected to at least validate the time-based claims with [ValidateTimeBounds].
//
// As an example, check out [StrictValidator].
type Validator interface {
	Validate(Token) error
}

Documentation

Index

Constants

View Source
const (
	ClaimIssuer     = "iss"
	ClaimSubject    = "sub"
	ClaimAudience   = "aud"
	ClaimIssuedAt   = "iat"
	ClaimExpiration = "exp"
	ClaimNotBefore  = "nbf"
)

Registered claim names as per NWT specification.

View Source
const Kind = 27519

Kind is the Nostr event kind for Nostr Web Tokens (NWT).

View Source
const MaxClaims = 512

MaxClaims defines the maximum number of claims allowed in a NWT, to prevent abuse.

Variables

View Source
var (
	ErrMissingHeader    = errors.New("missing Authorization header")
	ErrInvalidHeader    = errors.New("invalid Authorization header format")
	ErrInvalidEventJSON = errors.New("invalid event JSON")
)

Parsing errors

View Source
var (
	ErrInvalidEventKind      = fmt.Errorf("event kind must be %d", Kind)
	ErrInvalidEventCreatedAt = errors.New("invalid event created at")
	ErrInvalidEventID        = errors.New("invalid event ID")
	ErrInvalidEventSignature = errors.New("invalid event signature")
)

Event validation errors

View Source
var (
	// MinTime represents the minimum valid time for NWT claims, corresponding to the 0 Unix epoch.
	MinTime = time.Unix(0, 0).UTC()

	// MaxTime represents the maximum valid time for NWT claims, set to December 31, 9999.
	MaxTime = time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC)
)
View Source
var (
	ErrEmptyID           = errors.New("token ID is empty")
	ErrInvalidIssuedAt   = errors.New("issued at claim is invalid")
	ErrInvalidExpiration = errors.New("expiration claim is invalid")
	ErrInvalidNotBefore  = errors.New("not before claim is invalid")
	ErrInvalidTimeWindow = errors.New("not before is after expiration")
	ErrInvalidAudience   = errors.New("audience claim is invalid")
	ErrNotYetValid       = errors.New("token not yet valid (before NotBefore)")
	ErrExpired           = errors.New("token expired (after Expiration)")
)

Token validation errors

Functions

func ExtractEventHTTP

func ExtractEventHTTP(r *http.Request) (*nostr.Event, error)

ExtractEventHTTP extracts the Nostr event from the Authorization header of the HTTP request without performing any validation.

func SetAuth added in v0.4.1

func SetAuth(r *http.Request, event *nostr.Event) error

SetAuth validates the Nostr event and sets the Authorization header on the request.

func ValidateEvent

func ValidateEvent(e *nostr.Event) error

ValidateEvent checks whether the given Nostr event is a valid NWT event. It verifies the event kind, created at, ID, and signature but doesn't validate the token claims themselves.

func ValidateTimeClaims added in v0.4.0

func ValidateTimeClaims(t Token, skew time.Duration) error

ValidateTimeClaims checks that the Token's time-based claims are within valid bounds.

Types

type StrictValidator

type StrictValidator struct {
	Identifier string
	ClockSkew  time.Duration
}

StrictValidator performs validation on the Token claims. It checks time-based claims with a configurable clock skew tolerance and verifies that the Audience claim contains an exact match of the specified identifier.

func (StrictValidator) Validate

func (v StrictValidator) Validate(t Token) error

type Token

type Token struct {
	ID     string // The ID of the Nostr event
	Signer string // The pubkey that signed the Nostr event

	Issuer     string
	Subject    string
	Audience   []string
	IssuedAt   time.Time
	Expiration time.Time
	NotBefore  time.Time

	// Additional custom claims, preserved as raw tags for roundtrip compatibility.
	Extra nostr.Tags
}

Token represents a parsed Nostr Web Token (NWT) from a Nostr event. It includes registered claims as well as any additional claims found in the event tags. Learn more about NWTs at: https://github.com/pippellia-btc/nostr-web-tokens

func Parse added in v0.2.0

func Parse(r *http.Request) (Token, error)

Parse a Token from the event found in the Authorization header of the request. It validates the event, but doesn't validate the token's claims. To validate the token, use a Validator.

func ParseToken

func ParseToken(event *nostr.Event) (Token, error)

ParseToken parses the Nostr event into a Token struct, without performing any validation. To validate the token, use a Validator.

func (Token) IsActive

func (t Token) IsActive(skew time.Duration) bool

IsActive checks whether the token is currently active. It's a shorthand for Token.IsActiveAt(time.Now(), skew).

func (Token) IsActiveAt

func (t Token) IsActiveAt(now time.Time, skew time.Duration) bool

IsActiveAt checks whether the token is active at the specified time, which happens iff

NotBefore - skew <= now <= Expiration + skew

Skew is used to account for clock differences between systems, and is typically a small duration like 60s.

func (Token) String

func (t Token) String() string

func (Token) ToTags

func (t Token) ToTags() nostr.Tags

ToTags converts the Token into a list of nostr tags suitable for inclusion in a Nostr event.

type Validator

type Validator interface {
	Validate(Token) error
}

Validator wraps the Validate method for validating Tokens. The token is considered valid iff Validate returns nil.

Implementations may enforce different policies for what constitutes a valid token, but are generally expected to at least validate the time-based claims with ValidateTimeClaims.

As an example, check out StrictValidator.

Jump to

Keyboard shortcuts

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