authkit

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 16 Imported by: ? 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.

README

authkit

authkit is a transport-agnostic Go library for passwordless auth driven by messenger identity.

Design goals:

  • no HTTP framework dependency
  • no Telegram/Discord coupling in core
  • works in monoliths and microservices
  • explicit interfaces for persistence/session issuance

Who This README Is For

If you are an AI agent (or a developer) integrating this package, this file is intended to be enough to implement a working auth flow without reading package internals.

Import Path

import authkit "github.com/supercakecrumb/msgr-authkit"

Fast Mental Model

authkit has two primary flows:

  1. Intent flow (code-first)
  • create auth intent (CreateIntent)
  • deliver intent code by any channel
  • redeem code (RedeemIntent)
  • get WebSession
  1. Bot-first login-link flow
  • user starts in messenger (/start, /login)
  • app creates signed login link (CreateLoginLink)
  • user opens link in browser
  • backend redeems token (RedeemLoginLink)
  • get WebSession

Core Types You Need

  • Messenger: normalized messenger identifier
  • Identity: messenger user profile data
  • AuthIntent: challenge/token state with redemption policy
  • AccountLink: mapping messenger identity -> internal app user id
  • WebSession: result returned by your SessionIssuer

Required Interfaces (Production)

You must provide:

  • IntentStore
  • SessionIssuer

You usually provide:

  • LinkStore (needed when subject is not known at create time)

Optional for bot-first:

  • LoginTokenCodec, LoginLinkBuilder (or just use WithSignedQueryLoginLinks)
  • AudienceResolver
  • LinkProvisioner

What authkit Guarantees

  • input normalization/validation
  • one-time or reusable intent policy enforcement
  • expiration checks (intent + login-link token)
  • deterministic behavior via injectable clock/code/id generators
  • security-first redeem ordering (consume intent before issuing session)

Integration Protocol (Agent Checklist)

  1. Choose flow:
  • CreateIntent/RedeemIntent if your UI starts in web.
  • CreateLoginLink/RedeemLoginLink if your UI starts in messenger.
  1. Decide subject resolution strategy:
  • known SubjectID at create time, or
  • resolve via LinkStore, or
  • auto-provision via WithMissingIdentityLinkMode(MissingIdentityLinkAutoProvision) + WithLinkProvisioner.
  1. Wire service:
  • instantiate stores + session issuer
  • call NewAuthService(...)
  • apply WithConfig(...)
  • for bot-first add WithSignedQueryLoginLinks(...)
  1. Implement error mapping:
  • map sentinel errors to HTTP statuses / user-visible messages with errors.Is.
  1. Add tests:
  • intent create/redeem happy path
  • replay and expiration cases
  • missing link behavior by mode

Minimal In-Memory Example

package main

import (
	"context"
	"fmt"
	"time"

	authkit "github.com/supercakecrumb/msgr-authkit"
)

func main() {
	ctx := context.Background()

	intentStore := authkit.NewInMemoryIntentStore()
	linkStore := authkit.NewInMemoryLinkStore()
	sessionIssuer, _ := authkit.NewInMemorySessionIssuer(24 * time.Hour)

	service, _ := authkit.NewAuthService(intentStore, linkStore, sessionIssuer)

	_ = linkStore.Upsert(ctx, authkit.AccountLink{
		AppUserID: "user-42",
		Identity: authkit.Identity{
			Messenger:       authkit.NewMessenger("telegram"),
			MessengerUserID: "123456",
		},
		LinkedAt: time.Now().UTC(),
	})

	intent, _ := service.CreateIntent(ctx, authkit.CreateIntentInput{
		Messenger: authkit.NewMessenger("telegram"),
		Audience:  "web",
	})

	session, _ := service.RedeemIntent(ctx, authkit.RedeemIntentInput{
		Code:      intent.Code,
		Messenger: authkit.NewMessenger("telegram"),
		Identity:  &authkit.Identity{MessengerUserID: "123456"},
	})

	fmt.Println(session.Token)
}
service, _ := authkit.NewAuthService(
	intentStore,
	linkStore,
	sessionIssuer,
	authkit.WithSignedQueryLoginLinks(
		"https://app.example/auth/redeem", // public URL
		[]byte("replace-with-long-random-secret"),
		"auth_token",
	),
	authkit.WithMissingIdentityLinkMode(authkit.MissingIdentityLinkAutoProvision),
	authkit.WithLinkProvisioner(authkit.LinkProvisionerFunc(
		func(ctx context.Context, identity authkit.Identity) (authkit.AccountLink, error) {
			return authkit.AccountLink{
				AppUserID: "tg:" + identity.MessengerUserID,
				Identity:  identity,
				LinkedAt:  time.Now().UTC(),
			}, nil
		},
	)),
)

login, _ := service.CreateLoginLink(ctx, authkit.CreateLoginLinkInput{
	Messenger: authkit.NewMessenger("telegram"),
	Identity: &authkit.Identity{
		Messenger:       authkit.NewMessenger("telegram"),
		MessengerUserID: "123456",
	},
})

// send login.LoginURL via bot
session, _ := service.RedeemLoginLink(ctx, authkit.RedeemLoginLinkInput{LinkToken: login.LinkToken})
_ = session

Config Defaults

DefaultConfig() currently means:

  • DefaultIntentTTL = 15m
  • DefaultRedemptionMode = IntentOneTime
  • DefaultReusableMaxRedemptions = 0 (unlimited if reusable)
  • DefaultLoginLinkTTL = 5m

Override with WithConfig(...).

When creating login links with identity but no existing LinkStore mapping:

  • MissingIdentityLinkDeferred
    • allow create now, resolve subject later during redeem
  • MissingIdentityLinkStrict
    • fail immediately with ErrIdentityLinkNotFound
  • MissingIdentityLinkAutoProvision
    • call LinkProvisioner, optional LinkStore.Upsert

Error Handling Contract

Use errors.Is(err, ...) with sentinels:

  • ErrInvalidInput
  • ErrIntentNotFound
  • ErrIntentNotActive
  • ErrIntentExpired
  • ErrIntentAlreadyRedeemed
  • ErrIntentRedemptionLimitReached
  • ErrSubjectUnresolved
  • ErrIdentityLinkNotFound
  • ErrCodeGenerationFailed
  • ErrIDGenerationFailed
  • ErrSessionNotFound
  • ErrSessionExpired
  • ErrLoginLinkNotConfigured
  • ErrLoginLinkInvalid
  • ErrLoginLinkExpired

Suggested HTTP mapping:

  • invalid input: 400
  • not found/invalid token: 404/401
  • expired/redeemed: 409 or 401 depending on UX
  • unresolved subject/link missing: 422 or 401

Production Implementation Notes

  • IntentStore.RecordRedemption should be atomic (transaction/compare-and-swap) to prevent replay races.
  • Normalize messenger IDs with NewMessenger everywhere.
  • Keep login-link signing key long/random and rotated.
  • Keep login-link TTL short.
  • Prefer one-time intents for auth links.
  • Ensure bot-to-web internal endpoint is authenticated.
  • For Telegram URL buttons, prefer public https URLs.

Testing Matrix (Minimum)

  1. one-time intent can be redeemed once
  2. second redeem returns ErrIntentAlreadyRedeemed
  3. expired intent returns ErrIntentExpired
  4. missing subject and missing link returns ErrSubjectUnresolved/ErrIdentityLinkNotFound
  5. bot-first invalid token returns ErrLoginLinkInvalid
  6. bot-first expired token returns ErrLoginLinkExpired

Package Map

  • types.go: domain models + interfaces
  • service.go: AuthService + options + bot-first helpers
  • inmemory.go: in-memory adapters for demos/tests
  • errors.go: sentinel errors for errors.Is

Quick FAQ

Do I need to use Telegram? No. Messenger is just a normalized string ID.

Can I use JWT sessions? Yes. Implement SessionIssuer with JWT issuance/validation.

Can I skip LinkStore? Yes if you always pass SubjectID during create.

Can I keep intents reusable? Yes via IntentReusable, but one-time is safer for login.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidInput indicates caller-provided data failed validation.
	ErrInvalidInput = errors.New("authkit: invalid input")
	// ErrIntentNotFound indicates the requested intent does not exist.
	ErrIntentNotFound = errors.New("authkit: intent not found")
	// ErrIntentNotActive indicates intent state is not redeemable.
	ErrIntentNotActive = errors.New("authkit: intent is not active")
	// ErrIntentExpired indicates intent expiration has passed.
	ErrIntentExpired = errors.New("authkit: intent expired")
	// ErrIntentAlreadyRedeemed indicates one-time intent was already used.
	ErrIntentAlreadyRedeemed = errors.New("authkit: intent already redeemed")
	// ErrIntentRedemptionLimitReached indicates reusable intent hit max count.
	ErrIntentRedemptionLimitReached = errors.New("authkit: intent redemption limit reached")
	// ErrSubjectUnresolved indicates authkit could not determine internal user id.
	ErrSubjectUnresolved = errors.New("authkit: subject unresolved")
	// ErrIdentityLinkNotFound indicates no identity->user mapping exists.
	ErrIdentityLinkNotFound = errors.New("authkit: identity link not found")
	// ErrCodeGenerationFailed indicates code/token generator failure.
	ErrCodeGenerationFailed = errors.New("authkit: code generation failed")
	// ErrIDGenerationFailed indicates ID generator failure.
	ErrIDGenerationFailed = errors.New("authkit: id generation failed")
	// ErrSessionNotFound indicates provided session token is unknown.
	ErrSessionNotFound = errors.New("authkit: session not found")
	// ErrSessionExpired indicates session token exists but is expired.
	ErrSessionExpired = errors.New("authkit: session expired")
	// ErrLoginLinkNotConfigured indicates bot-first login-link dependencies are
	// not configured on AuthService.
	ErrLoginLinkNotConfigured = errors.New("authkit: login link is not configured")
	// ErrLoginLinkInvalid indicates login-link token or URL payload is malformed
	// or failed signature verification.
	ErrLoginLinkInvalid = errors.New("authkit: login link is invalid")
	// ErrLoginLinkExpired indicates login-link token is no longer valid by time.
	ErrLoginLinkExpired = errors.New("authkit: login link expired")
)

Package-level sentinel errors returned by authkit public APIs.

Functions

This section is empty.

Types

type AccountLink struct {
	// AppUserID is the internal application user id.
	AppUserID string
	// Identity is the linked external messenger identity.
	Identity Identity
	// LinkedAt records when the mapping was created or last refreshed.
	LinkedAt time.Time
}

AccountLink maps external identity to an internal app user.

type AudienceResolver

type AudienceResolver interface {
	// ResolveAudience derives audience when CreateLoginLinkInput.Audience is
	// empty. Empty resolver output is allowed.
	ResolveAudience(ctx context.Context, messenger Messenger, identity *Identity) (string, error)
}

AudienceResolver derives audience/context when caller omitted it in CreateLoginLinkInput.

type AudienceResolverFunc

type AudienceResolverFunc func(ctx context.Context, messenger Messenger, identity *Identity) (string, error)

AudienceResolverFunc adapts a function to AudienceResolver.

func (AudienceResolverFunc) ResolveAudience

func (f AudienceResolverFunc) ResolveAudience(ctx context.Context, messenger Messenger, identity *Identity) (string, error)

ResolveAudience calls f(ctx, messenger, identity).

type AuthIntent

type AuthIntent struct {
	// ID is an internal unique identifier for persistence.
	ID string
	// Code is the user-facing (or transport-facing) redemption code.
	Code string
	// Messenger scopes the code to a specific external channel.
	Messenger Messenger
	// Audience is optional context such as "web", "mobile", or "admin".
	// Applications may use it to route auth completion behavior.
	Audience string
	// SubjectID is the internal user id if already known at create time.
	// When empty, subject can be resolved from LinkStore during redemption.
	SubjectID string
	// State tracks whether the intent can still be redeemed.
	State IntentState
	// Identity is optional profile data captured at intent creation.
	// It can help resolve SubjectID later.
	Identity *Identity
	// Metadata stores application-defined key-value context.
	// Authkit stores and returns it but does not interpret values.
	Metadata map[string]string
	// RedemptionMode controls one-time vs reusable redemption behavior.
	RedemptionMode IntentRedemptionMode
	// MaxRedemptions is used for reusable intents.
	// Zero means unlimited redemptions.
	MaxRedemptions int
	// RedemptionCount is incremented after each successful redemption.
	RedemptionCount int
	// ExpiresAt is optional absolute expiration time (UTC).
	// Nil means no expiration.
	ExpiresAt *time.Time
	// CreatedAt is intent creation timestamp (UTC).
	CreatedAt time.Time
	// ConsumedAt is timestamp of the latest successful redemption.
	// For one-time intents this is the single redemption timestamp.
	ConsumedAt *time.Time
}

AuthIntent is an auth challenge that can be one-time or reusable/static.

type AuthService

type AuthService struct {
	// contains filtered or unexported fields
}

AuthService is the default implementation of Service and BotFirstService.

func NewAuthService

func NewAuthService(
	intentStore IntentStore,
	linkStore LinkStore,
	sessionIssuer SessionIssuer,
	opts ...Option,
) (*AuthService, error)

NewAuthService creates an AuthService with required dependencies and options.

Required dependencies:

  1. IntentStore
  2. SessionIssuer

LinkStore is optional, but required for identity->subject resolution when SubjectID is not provided.

func (*AuthService) CreateIntent

func (s *AuthService) CreateIntent(ctx context.Context, in CreateIntentInput) (AuthIntent, error)

CreateIntent validates input, normalizes identity/messenger, applies default policy values, and persists an auth intent.

CreateLoginLink creates an underlying intent and returns a signed short-lived login URL for bot-initiated flows.

Requires both LoginTokenCodec and LoginLinkBuilder to be configured.

func (*AuthService) RedeemIntent

func (s *AuthService) RedeemIntent(ctx context.Context, in RedeemIntentInput) (WebSession, error)

RedeemIntent validates an existing intent, resolves subject id (direct or via LinkStore), records redemption, and issues a web session.

Redemptions are consumed before session issuance to prioritize replay safety.

func (s *AuthService) RedeemLoginLink(ctx context.Context, in RedeemLoginLinkInput) (WebSession, error)

RedeemLoginLink verifies the signed login-link token and then delegates to RedeemIntent to issue a web session.

type BotFirstService

type BotFirstService interface {
	Service
	// CreateLoginLink creates an intent, signs a short-lived token, and returns
	// a user-facing URL for bot-initiated login flows.
	CreateLoginLink(ctx context.Context, in CreateLoginLinkInput) (CreateLoginLinkOutput, error)
	// RedeemLoginLink verifies the login-link token and performs standard intent
	// redemption to issue a web session.
	RedeemLoginLink(ctx context.Context, in RedeemLoginLinkInput) (WebSession, error)
}

BotFirstService extends Service with bot-first login-link methods.

AuthService implements this interface.

type ChannelAdapter

type ChannelAdapter interface {
	// DeliverIntent sends intent details to an external channel/user.
	// This abstraction is optional and app-specific.
	DeliverIntent(ctx context.Context, identity Identity, intent AuthIntent) error
}

ChannelAdapter abstracts delivery/verification for any external channel.

type Clock

type Clock interface {
	// Now returns current time.
	Now() time.Time
}

Clock abstracts time source for deterministic tests.

type CodeGenerator

type CodeGenerator interface {
	// NewCode returns a new non-empty code string.
	NewCode() (string, error)
}

CodeGenerator creates auth intent codes.

type Config

type Config struct {
	// DefaultIntentTTL is applied when CreateIntentInput.ExpiresAt is nil.
	// Zero or negative means "no default expiration".
	DefaultIntentTTL time.Duration
	// DefaultRedemptionMode is used when input redemption mode is empty.
	DefaultRedemptionMode IntentRedemptionMode
	// DefaultReusableMaxRedemptions is used when reusable mode is requested
	// with MaxRedemptions == 0. Zero means unlimited.
	DefaultReusableMaxRedemptions int
	// DefaultLoginLinkTTL is applied when CreateLoginLinkInput.LinkExpiresAt is
	// nil. Zero means use intent expiration (if any).
	DefaultLoginLinkTTL time.Duration
}

Config controls default authkit behavior.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns practical secure defaults:

  1. intents expire in 15 minutes,
  2. intents are one-time by default,
  3. reusable intents are unlimited unless explicitly capped,
  4. login-link tokens expire in 5 minutes.

type CreateIntentInput

type CreateIntentInput struct {
	// Messenger identifies the external channel.
	// Required, unless Identity.Messenger is provided.
	Messenger Messenger
	// Audience optionally labels intended consumer/context for this intent.
	Audience string
	// SubjectID optionally prebinds the intent to a known internal user id.
	SubjectID string
	// Metadata stores application-defined key-value context.
	Metadata map[string]string
	// Identity is optional external profile data captured at creation time.
	Identity *Identity
	// RedemptionMode chooses one-time vs reusable behavior.
	// Empty value uses Config.DefaultRedemptionMode.
	RedemptionMode IntentRedemptionMode
	// MaxRedemptions applies only to IntentReusable.
	// Zero uses Config.DefaultReusableMaxRedemptions.
	MaxRedemptions int
	// ExpiresAt overrides expiration for this intent.
	// Nil uses Config.DefaultIntentTTL (or no expiration when default TTL is 0).
	ExpiresAt *time.Time
}

CreateIntentInput configures creation of an auth intent.

This is the baseline (non bot-first) entrypoint used by Service.CreateIntent.

type CreateLoginLinkInput

type CreateLoginLinkInput struct {
	// Messenger identifies the external channel for the created intent.
	// Required, unless Identity.Messenger is provided.
	Messenger Messenger
	// Audience optionally tags the created intent with app-specific context
	// (for example "web", "mobile", "admin"). If empty and AudienceResolver
	// is configured, resolver output is used.
	Audience string
	// SubjectID is the known internal app user id. When empty, authkit can
	// resolve it from LinkStore depending on MissingIdentityLinkMode.
	SubjectID string
	// Metadata stores optional caller-defined key-value context on the intent.
	Metadata map[string]string
	// Identity is optional user profile from messenger. When SubjectID is empty,
	// identity can be used to resolve or provision an account link.
	Identity *Identity
	// RedemptionMode controls one-time vs reusable behavior of the underlying
	// intent. Empty means Config.DefaultRedemptionMode.
	RedemptionMode IntentRedemptionMode
	// MaxRedemptions applies only to reusable intents. Zero means
	// Config.DefaultReusableMaxRedemptions.
	MaxRedemptions int
	// IntentExpiresAt overrides the intent expiration timestamp.
	// If nil, intent expiration is derived from Config.DefaultIntentTTL.
	IntentExpiresAt *time.Time
	// LinkExpiresAt overrides login-link token expiration timestamp.
	// If nil, token expiration is derived from Config.DefaultLoginLinkTTL and
	// clamped to IntentExpiresAt when needed.
	LinkExpiresAt *time.Time
}

CreateLoginLinkInput controls bot-first login-link creation.

The typical flow is:

  1. user starts auth in messenger (for example /start in Telegram),
  2. application calls CreateLoginLink,
  3. application sends returned LoginURL back to messenger,
  4. user opens link in browser and backend calls RedeemLoginLink.

CreateLoginLinkInput mirrors CreateIntentInput, but also allows configuring login-link token expiration independently from intent expiration.

type CreateLoginLinkOutput

type CreateLoginLinkOutput struct {
	// Intent is the persisted auth intent used during final redemption.
	Intent AuthIntent
	// LoginURL is the final user-facing URL built by LoginLinkBuilder.
	LoginURL string
	// LinkToken is the signed token built by LoginTokenCodec.
	// Applications may store/log this carefully as a short-lived secret.
	LinkToken string
	// ExpiresAt is the token expiration instant (UTC).
	ExpiresAt time.Time
}

CreateLoginLinkOutput contains the created intent and login-link artifacts.

type HMACLoginTokenCodec

type HMACLoginTokenCodec struct {
	// SigningKey is the shared secret used for HMAC signing.
	// The key must be non-empty.
	SigningKey []byte
}

HMACLoginTokenCodec signs/verifies login-link tokens with HMAC-SHA256.

func (HMACLoginTokenCodec) Decode

Decode verifies token signature and returns parsed claims. Returns ErrLoginLinkInvalid when token cannot be trusted.

func (HMACLoginTokenCodec) Encode

Encode serializes claims and returns signed compact token in "<payload>.<signature>" format (both base64url without padding).

type IDGenerator

type IDGenerator interface {
	// NewID returns a new non-empty identifier string.
	NewID() string
}

IDGenerator creates stable unique identifiers for entities.

type Identity

type Identity struct {
	// Messenger identifies where this identity came from.
	Messenger Messenger
	// MessengerUserID is a stable external user identifier in the messenger.
	// Example: Telegram numeric user id.
	MessengerUserID string
	// Username is the messenger handle when available.
	Username string
	// Name is given/first name.
	Name string
	// Surname is family/last name.
	Surname string
	// BirthDate is optional and messenger-dependent.
	BirthDate *time.Time
	// Attributes stores additional messenger-specific key-value data.
	// Callers should keep keys stable for easier downstream processing.
	Attributes map[string]string
}

Identity carries user details from an external channel. All fields are optional; callers may pass nil identity.

type InMemoryIntentStore

type InMemoryIntentStore struct {
	// contains filtered or unexported fields
}

InMemoryIntentStore is a concurrency-safe intent store for local/dev use.

func NewInMemoryIntentStore

func NewInMemoryIntentStore() *InMemoryIntentStore

NewInMemoryIntentStore returns an empty in-memory intent store. It is intended for tests and local development, not distributed production.

func (*InMemoryIntentStore) Create

func (s *InMemoryIntentStore) Create(ctx context.Context, intent AuthIntent) error

Create stores a new intent and rejects duplicate id or messenger+code pairs.

func (*InMemoryIntentStore) DeleteExpired

func (s *InMemoryIntentStore) DeleteExpired(ctx context.Context, now time.Time) error

DeleteExpired removes all intents whose ExpiresAt is before now.

func (*InMemoryIntentStore) FindByCode

func (s *InMemoryIntentStore) FindByCode(ctx context.Context, messenger Messenger, code string) (AuthIntent, error)

FindByCode returns intent by messenger+code pair.

func (*InMemoryIntentStore) RecordRedemption

func (s *InMemoryIntentStore) RecordRedemption(ctx context.Context, intentID string, redeemedAt time.Time) error

RecordRedemption validates current state and applies redemption mutation. It updates IntentExpired/IntentRevoked state where appropriate.

type InMemoryLinkStore

type InMemoryLinkStore struct {
	// contains filtered or unexported fields
}

InMemoryLinkStore is a concurrency-safe identity link store.

func NewInMemoryLinkStore

func NewInMemoryLinkStore() *InMemoryLinkStore

NewInMemoryLinkStore returns an empty in-memory link store.

func (*InMemoryLinkStore) FindByIdentity

func (s *InMemoryLinkStore) FindByIdentity(ctx context.Context, identity Identity) (AccountLink, error)

FindByIdentity returns linked internal account for a messenger identity.

func (*InMemoryLinkStore) Upsert

func (s *InMemoryLinkStore) Upsert(ctx context.Context, link AccountLink) error

Upsert creates or updates an identity mapping. If LinkedAt is zero, current UTC time is assigned.

type InMemorySessionIssuer

type InMemorySessionIssuer struct {
	// contains filtered or unexported fields
}

InMemorySessionIssuer issues opaque sessions and validates them in-memory.

func NewInMemorySessionIssuer

func NewInMemorySessionIssuer(ttl time.Duration, opts ...SessionIssuerOption) (*InMemorySessionIssuer, error)

NewInMemorySessionIssuer returns an in-memory session issuer with given TTL. It is suitable for tests and local environments.

func (*InMemorySessionIssuer) Issue

func (s *InMemorySessionIssuer) Issue(ctx context.Context, appUserID string) (WebSession, error)

Issue creates a new opaque session for app user id.

func (*InMemorySessionIssuer) Validate

func (s *InMemorySessionIssuer) Validate(ctx context.Context, token string) (WebSession, error)

Validate returns session for token if it exists and is not expired. Expired sessions are removed from in-memory state.

type IntentRedemptionMode

type IntentRedemptionMode string

IntentRedemptionMode controls whether an intent is single-use or reusable.

const (
	// IntentOneTime allows exactly one successful redemption.
	IntentOneTime IntentRedemptionMode = "one_time"
	// IntentReusable allows multiple redemptions until MaxRedemptions is hit.
	// When MaxRedemptions is zero, redemptions are unlimited.
	IntentReusable IntentRedemptionMode = "reusable"
)

type IntentState

type IntentState string

IntentState describes the lifecycle of an auth intent.

const (
	// IntentActive means the intent can still be redeemed.
	IntentActive IntentState = "active"
	// IntentExpired means the intent passed its expiration time and can no
	// longer be redeemed.
	IntentExpired IntentState = "expired"
	// IntentRevoked means the intent was explicitly consumed/closed before
	// natural expiration (for example after one-time redemption).
	IntentRevoked IntentState = "revoked"
)

type IntentStore

type IntentStore interface {
	// Create inserts a new intent.
	Create(ctx context.Context, intent AuthIntent) error
	// FindByCode returns intent by messenger+code pair.
	FindByCode(ctx context.Context, messenger Messenger, code string) (AuthIntent, error)
	// RecordRedemption applies redemption state transition atomically.
	// Implementations should enforce mode limits and return ErrIntent* values.
	RecordRedemption(ctx context.Context, intentID string, redeemedAt time.Time) error
	// DeleteExpired removes intents expired before the provided time.
	DeleteExpired(ctx context.Context, now time.Time) error
}

IntentStore persists auth intents.

type LinkProvisioner

type LinkProvisioner interface {
	// ProvisionLink creates or fetches an account link for the given identity.
	// The returned AccountLink.AppUserID must be non-empty.
	ProvisionLink(ctx context.Context, identity Identity) (AccountLink, error)
}

LinkProvisioner creates or fetches an account link when LinkStore lookup misses and mode is MissingIdentityLinkAutoProvision.

type LinkProvisionerFunc

type LinkProvisionerFunc func(ctx context.Context, identity Identity) (AccountLink, error)

LinkProvisionerFunc adapts a function to LinkProvisioner.

func (f LinkProvisionerFunc) ProvisionLink(ctx context.Context, identity Identity) (AccountLink, error)

ProvisionLink calls f(ctx, identity).

type LinkStore

type LinkStore interface {
	// FindByIdentity resolves internal user mapping for external identity.
	FindByIdentity(ctx context.Context, identity Identity) (AccountLink, error)
	// Upsert creates or updates identity mapping.
	Upsert(ctx context.Context, link AccountLink) error
}

LinkStore persists external identity <-> app user mappings.

type LoginLinkBuilder

type LoginLinkBuilder interface {
	// BuildURL returns the final user-facing login URL for a signed token.
	BuildURL(ctx context.Context, token string) (string, error)
}

LoginLinkBuilder builds a final user-facing URL from a signed token. Implementations can use query parameters, path segments, or custom transports.

type LoginTokenClaims

type LoginTokenClaims struct {
	// IntentCode points to the underlying auth intent.
	IntentCode string
	// Messenger scopes redemption to a specific messenger id.
	Messenger Messenger
	// ExpiresAt is absolute token expiration (UTC).
	ExpiresAt time.Time
}

LoginTokenClaims are serialized and signed by LoginTokenCodec.

type LoginTokenCodec

type LoginTokenCodec interface {
	// Encode produces a signed/encoded token from claims.
	Encode(ctx context.Context, claims LoginTokenClaims) (string, error)
	// Decode verifies and parses token claims.
	// Implementations should return ErrLoginLinkInvalid for malformed/forged
	// tokens when possible.
	Decode(ctx context.Context, token string) (LoginTokenClaims, error)
}

LoginTokenCodec signs and verifies login-link tokens.

Implementations should treat tokens as short-lived bearer credentials. Decode must reject malformed/forged tokens.

type Messenger

type Messenger struct {
	// ID is a normalized messenger identifier such as "telegram" or "discord".
	// Use NewMessenger to normalize user-provided values.
	ID string
}

Messenger identifies any external messenger/channel type. Examples: "telegram", "discord", "whatsapp", "signal", "slack", "custom-x".

func NewMessenger

func NewMessenger(id string) Messenger

NewMessenger creates a normalized messenger identifier.

type MissingIdentityLinkMode

type MissingIdentityLinkMode string

MissingIdentityLinkMode controls how CreateLoginLink behaves when identity is present but LinkStore has no account mapping for it.

const (
	// MissingIdentityLinkDeferred keeps subject unresolved during create and
	// allows LinkStore resolution later at redeem time.
	MissingIdentityLinkDeferred MissingIdentityLinkMode = "deferred"
	// MissingIdentityLinkStrict fails CreateLoginLink immediately with
	// ErrIdentityLinkNotFound.
	MissingIdentityLinkStrict MissingIdentityLinkMode = "strict"
	// MissingIdentityLinkAutoProvision asks LinkProvisioner to create/fetch the
	// link and optionally persists it via LinkStore.Upsert.
	MissingIdentityLinkAutoProvision MissingIdentityLinkMode = "auto_provision"
)

type Option

type Option func(*AuthService) error

Option configures AuthService behavior.

func WithAudienceResolver

func WithAudienceResolver(resolver AudienceResolver) Option

WithAudienceResolver configures dynamic audience derivation when CreateLoginLinkInput.Audience is empty.

func WithClock

func WithClock(clock Clock) Option

WithClock overrides the time source used by AuthService. Useful for deterministic tests.

func WithCodeGenerator

func WithCodeGenerator(gen CodeGenerator) Option

WithCodeGenerator overrides auth-code generation for intents.

func WithConfig

func WithConfig(cfg Config) Option

WithConfig overrides service defaults.

Validation rules:

  1. TTL values must be >= 0.
  2. reusable max redemptions must be >= 0.
  3. redemption mode must be one of IntentOneTime/IntentReusable.

func WithIDGenerator

func WithIDGenerator(gen IDGenerator) Option

WithIDGenerator overrides internal ID generation for intents.

func WithLinkProvisioner

func WithLinkProvisioner(provisioner LinkProvisioner) Option

WithLinkProvisioner configures auto-provision hook used only when MissingIdentityLinkMode is MissingIdentityLinkAutoProvision.

func WithLoginLinkBuilder

func WithLoginLinkBuilder(builder LoginLinkBuilder) Option

WithLoginLinkBuilder configures URL construction for bot-first login links. Requires WithLoginTokenCodec (or WithSignedQueryLoginLinks) for CreateLoginLink to work.

func WithLoginTokenCodec

func WithLoginTokenCodec(codec LoginTokenCodec) Option

WithLoginTokenCodec configures token signing/parsing for bot-first login links. Requires WithLoginLinkBuilder (or WithSignedQueryLoginLinks) for CreateLoginLink to work.

func WithMissingIdentityLinkMode

func WithMissingIdentityLinkMode(mode MissingIdentityLinkMode) Option

WithMissingIdentityLinkMode configures behavior when CreateLoginLink receives identity data but LinkStore has no mapping for that identity.

Empty mode defaults to MissingIdentityLinkDeferred.

func WithSignedQueryLoginLinks(baseURL string, signingKey []byte, tokenQueryParam string) Option

WithSignedQueryLoginLinks is a convenience option for bot-first flow setup. It configures an HMAC token codec and query-parameter link builder.

type QueryLoginLinkBuilder

type QueryLoginLinkBuilder struct {
	// BaseURL is the destination endpoint that receives token query parameter.
	// Example: https://example.com/auth/complete
	BaseURL string
	// TokenQueryParam is the query parameter name for the token.
	// Empty value defaults to "auth_token".
	TokenQueryParam string
}

QueryLoginLinkBuilder builds URLs by placing token into a query parameter. Example: https://example.com/auth/complete?auth_token=...

func (QueryLoginLinkBuilder) BuildURL

func (b QueryLoginLinkBuilder) BuildURL(ctx context.Context, token string) (string, error)

BuildURL appends token as query parameter to BaseURL and returns final URL.

type RedeemIntentInput

type RedeemIntentInput struct {
	// Code is the intent redemption code.
	Code string
	// Messenger scopes code lookup to a specific channel.
	// Required, unless Identity.Messenger is provided.
	Messenger Messenger
	// Identity optionally provides fresh profile data at redemption time.
	// It is merged with stored intent identity for subject resolution, but cannot
	// change a messenger user ID already bound at creation. Callers must verify
	// any identity supplied for an intent that has no bound identity.
	Identity *Identity
}

RedeemIntentInput contains data required to redeem an existing intent.

type RedeemLoginLinkInput

type RedeemLoginLinkInput struct {
	// LinkToken is the signed token previously returned from CreateLoginLink.
	LinkToken string
	// Identity optionally provides fresh messenger profile data during redeem.
	// It is merged with intent identity when subject resolution needs LinkStore.
	Identity *Identity
}

RedeemLoginLinkInput is used to redeem a signed login-link token.

type SecureCodeGenerator

type SecureCodeGenerator struct {
	// NumBytes is entropy size before hex encoding.
	// If NumBytes <= 0, 16 bytes are used.
	NumBytes int
}

SecureCodeGenerator creates cryptographically secure hex auth codes.

func (SecureCodeGenerator) NewCode

func (g SecureCodeGenerator) NewCode() (string, error)

NewCode returns a cryptographically secure hex string.

type Service

type Service interface {
	// CreateIntent creates and persists a new auth intent.
	CreateIntent(ctx context.Context, in CreateIntentInput) (AuthIntent, error)
	// RedeemIntent validates intent state and returns issued web session.
	RedeemIntent(ctx context.Context, in RedeemIntentInput) (WebSession, error)
}

Service is the high-level authkit contract used by applications.

type SessionIssuer

type SessionIssuer interface {
	// Issue creates a new web session for internal user id.
	Issue(ctx context.Context, appUserID string) (WebSession, error)
	// Validate parses and verifies a previously issued session token.
	Validate(ctx context.Context, token string) (WebSession, error)
}

SessionIssuer abstracts web-session format (JWT, opaque token, etc.).

type SessionIssuerOption

type SessionIssuerOption func(*InMemorySessionIssuer) error

SessionIssuerOption configures InMemorySessionIssuer.

func WithSessionClock

func WithSessionClock(clock Clock) SessionIssuerOption

WithSessionClock overrides session time source.

func WithSessionIDGenerator

func WithSessionIDGenerator(gen IDGenerator) SessionIssuerOption

WithSessionIDGenerator overrides session id generation.

func WithSessionTokenGenerator

func WithSessionTokenGenerator(gen CodeGenerator) SessionIssuerOption

WithSessionTokenGenerator overrides opaque session token generation.

type UUIDGenerator

type UUIDGenerator struct{}

UUIDGenerator is default IDGenerator based on RFC4122 random UUIDs.

func (UUIDGenerator) NewID

func (UUIDGenerator) NewID() string

NewID returns a new UUID string.

type WebSession

type WebSession struct {
	// SessionID is an internal session identifier.
	SessionID string
	// SubjectID is the internal authenticated user id.
	SubjectID string
	// Token is the bearer credential returned to clients.
	Token string
	// IssuedAt is session creation time (UTC).
	IssuedAt time.Time
	// ExpiresAt is session expiration time (UTC).
	ExpiresAt time.Time
}

WebSession is the web auth artifact issued after successful intent redemption.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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