passkey

package module
v2.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 17 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

🔑 passkey

passkey is a Go library for implementing WebAuthn services

Go Reference Go Report Card


passkey handles WebAuthn registration, login ceremonies, and session authentication for Go HTTP services with pluggable storage and context-aware middleware. Built on top of go-webauthn.

Features

  • WebAuthn Ceremonies: Handlers for passkey registration and login flows.
  • Session Management: Isolated, bounded session stores for registration, login, and authenticated user sessions.
  • Authentication Middleware: Standard HTTP middleware to protect routes and inject authenticated user IDs into context.
  • Pluggable Storage: Interfaces for account persistence and session caching.

[!NOTE] In general, this library is built on top of two open-source solutions:

Used in project: Static Badge Static Badge

Actual versions: GitHub Release npm

Installation

Requires Go 1.26 or newer.

go get github.com/egregors/passkey

Usage

1. Implement storage

Implement UserStore, User, and SessionStore[T]. Passkey uses one user store and three typed session stores:

Store Record Type Purpose Methods
UserStore passkey.User Accounts and registered credentials Create, UpdateCredential, Get, GetByName
LoginSessionStore webauthn.SessionData Pending login challenges Create, Delete, Get, Consume
RegistrationSessionStore passkey.RegistrationSessionData Pending registration challenges Create, Delete, Get, Consume
UserSessionStore passkey.UserSessionData Authenticated user sessions Create, Delete, Get, Consume
  • UserStore.Create atomically persists the account and initial credential, returning ErrUserAlreadyExists on conflicts. Lookups return ErrUserNotFound for missing users.
  • UserStore.UpdateCredential atomically updates a credential's authentication state (signature counters, clone warnings).
  • SessionStore.Consume must atomically retrieve and delete a challenge to prevent replay attacks.
  • Registration creates new accounts only; users log in separately after registering.

See ifaces.go for detailed interface contracts and _example/storage.go for an in-memory reference implementation.

2. Configure and mount routes

Using your initialized storage implementations (see _example/main.go for a runnable setup):

package main

import (
	"log"
	"net/http"
	"time"

	"github.com/go-webauthn/webauthn/webauthn"
	"github.com/egregors/passkey/v2"
)

func main() {
	pkey, err := passkey.New(
		passkey.Config{
			WebauthnConfig: &webauthn.Config{
				RPDisplayName: "My App",
				RPID:          "localhost",
				RPOrigins:     []string{"http://localhost:8080"},
			},
			UserStore:                userStore,
			LoginSessionStore:        loginSessionStore,
			RegistrationSessionStore: regSessionStore,
			UserSessionStore:         userSessionStore,
		},
		passkey.WithInsecureCookie(), // Use only for local HTTP development!
		passkey.WithUserSessionMaxAge(60 * time.Minute),
	)
	if err != nil {
		log.Fatal(err)
	}

	mux := http.NewServeMux()

	// Mount ceremony routes under a trailing slash prefix (e.g. /api/)
	pkey.MountRoutes(mux, "/api/")

	// Mount logout separately at your application's logout endpoint
	mux.HandleFunc("/logout", pkey.Logout)

	log.Fatal(http.ListenAndServe(":8080", mux))
}

3. Protect routes with middleware

Use pkey.Auth to protect authenticated endpoints. Pass a typed AuthUserIDKey to retrieve the authenticated user ID from context with passkey.UserIDFromCtx:

const userKey passkey.AuthUserIDKey = "userID"

// Register inside main (before http.ListenAndServe):
mux.Handle("/private", pkey.Auth(userKey, nil, nil)(http.HandlerFunc(privateHandler)))

func privateHandler(w http.ResponseWriter, r *http.Request) {
	userID, ok := passkey.UserIDFromCtx(r.Context(), userKey)
	if !ok {
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}

	// Resolve the account and apply application authorization here...
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "Authenticated user: %x", userID)
}
  • When onFail is nil, unauthenticated requests return 401 Unauthorized.
  • You can provide a custom failure handler or use passkey.RedirectUnauthorized(url.URL{Path: "/login"}).
  • When provided, onSuccess runs before the protected handler.
  • The middleware validates the session; your application handlers remain responsible for verifying account status and application authorization.

4. Client-side integration

Connect any standard WebAuthn browser client:

  1. Registration: POST {"username":"alice"} to /api/passkey/registerBegin, pass the returned options to a WebAuthn client (such as SimpleWebAuthn), and POST its serialized response to /api/passkey/registerFinish.
  2. Login: POST {"username":"alice"} to /api/passkey/loginBegin, pass the returned options to the client, and POST the serialized assertion to /api/passkey/loginFinish.

See _example/web for a complete vanilla frontend implementation.

Endpoints

Ceremony routes use the /api/ prefix below when mounted with pkey.MountRoutes(mux, "/api/"). /logout is mounted separately using pkey.Logout as shown above.

Route Method Request Body Description
/api/passkey/registerBegin POST {"username":"alice"} Begin registration ceremony
/api/passkey/registerFinish POST WebAuthn registration response Complete registration and save account
/api/passkey/loginBegin POST {"username":"alice"} Begin login ceremony
/api/passkey/loginFinish POST WebAuthn assertion response Verify login and set authenticated session
/logout POST Empty Revoke session and clear cookie (returns 204)

[!NOTE] All ceremony endpoints and Logout require POST with an Origin header matching RPOrigins. Challenges are single-use and expire after at most five minutes; if verification fails, restart the ceremony at the begin endpoint.

Options

Pass functional options to passkey.New:

Option Default Description
WithLogger(logger) Built-in logger Provide a custom passkey.Logger
WithInsecureCookie() Disabled Use unprefixed, non-Secure cookies for local HTTP development
WithSessionCookieNamePrefix(prefix) "pk" Set base prefix for session cookies
WithUserSessionMaxAge(duration) 60 minutes Set authenticated-session lifetime and cookie max age

Production cookies default to __Host- prefixed, Secure, HttpOnly, SameSite=Lax cookies served over HTTPS.

Example Application

A complete runnable example is provided in _example:

# Run local HTTP example on http://localhost:8080
make run

# Run HTTPS example with self-signed certificate in Docker on https://localhost
make up

The example uses in-memory storage; restarting it removes accounts and sessions.

Troubleshooting

FAQ

Q: I'm getting an error "named cookie not present" when I try to interact with passkey running on localhost from macOS Safari.

A: For local HTTP development, use WithInsecureCookie() to disable Secure and reserved cookie prefixes. Production requires HTTPS with the default secure cookies.

Q: Why do ceremony requests return 403 or an origin-related verification failure?

A: Configure RPOrigins with the exact browser origin, including its scheme and nondefault port. POST requests must send that Origin header; WebAuthn verification also checks the origin in the signed client data.

Q: I'm getting an error "WebAuthn is not supported in this browser" when I try to interact with passkey on localhost from iOS Safari.

A: WebAuthn needs a browser-trusted secure context. Use HTTPS when testing from another device; make up starts the HTTPS example, whose local certificate must be trusted by the test device.

Development

make test         # Run unit and integration tests
make install-lint # Install pinned golangci-lint
make lint         # Run linter
make gen          # Generate mocks

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNoUsername         = fmt.Errorf("no username provided")
	ErrUsernameTooLong    = fmt.Errorf("username exceeds 256 bytes")
	ErrUserNotFound       = fmt.Errorf("user not found")
	ErrCredentialNotFound = fmt.Errorf("credential not found")
	ErrUserAlreadyExists  = fmt.Errorf("user already exists")
	ErrSessionStoreFull   = fmt.Errorf("session storage is full")
)

Functions

func JSONResponse

func JSONResponse(w http.ResponseWriter, data interface{}, status int)

JSONResponse sends json response

func RedirectUnauthorized

func RedirectUnauthorized(target url.URL) http.HandlerFunc

RedirectUnauthorized returns a 303 redirect to a local target, or Unauthorized for an invalid target.

func Unauthorized

func Unauthorized(w http.ResponseWriter, _ *http.Request)

Unauthorized writes a 401 Unauthorized status code to the response.

func UserIDFromCtx

func UserIDFromCtx(ctx context.Context, pkUserKey AuthUserIDKey) ([]byte, bool)

UserIDFromCtx returns the user ID from the request context. If the userID is not found, it returns nil and false.

Types

type AuthUserIDKey

type AuthUserIDKey string

type Config

type Config struct {
	WebauthnConfig *webauthn.Config
	UserStore
	LoginSessionStore        SessionStore[webauthn.SessionData]
	RegistrationSessionStore SessionStore[RegistrationSessionData]
	UserSessionStore         SessionStore[UserSessionData]
}

type CookieSettings

type CookieSettings struct {
	Path string

	Secure   bool
	HttpOnly bool //nolint:revive // naming from http.Cookie
	SameSite http.SameSite
	// contains filtered or unexported fields
}

type Logger

type Logger interface {
	Errorf(format string, v ...any)
	Debugf(format string, v ...any)
	Infof(format string, v ...any)
	Warnf(format string, v ...any)
}

Logger is a simple logger interface

type MockLogger

type MockLogger struct {
	mock.Mock
}

MockLogger is an autogenerated mock type for the Logger type

func NewMockLogger

func NewMockLogger(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockLogger

NewMockLogger creates a new instance of MockLogger. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockLogger) Debugf

func (_m *MockLogger) Debugf(format string, v ...any)

Debugf provides a mock function with given fields: format, v

func (*MockLogger) EXPECT

func (_m *MockLogger) EXPECT() *MockLogger_Expecter

func (*MockLogger) Errorf

func (_m *MockLogger) Errorf(format string, v ...any)

Errorf provides a mock function with given fields: format, v

func (*MockLogger) Infof

func (_m *MockLogger) Infof(format string, v ...any)

Infof provides a mock function with given fields: format, v

func (*MockLogger) Warnf

func (_m *MockLogger) Warnf(format string, v ...any)

Warnf provides a mock function with given fields: format, v

type MockLogger_Debugf_Call

type MockLogger_Debugf_Call struct {
	*mock.Call
}

MockLogger_Debugf_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Debugf'

func (*MockLogger_Debugf_Call) Return

func (*MockLogger_Debugf_Call) Run

func (_c *MockLogger_Debugf_Call) Run(run func(format string, v ...any)) *MockLogger_Debugf_Call

func (*MockLogger_Debugf_Call) RunAndReturn

func (_c *MockLogger_Debugf_Call) RunAndReturn(run func(string, ...any)) *MockLogger_Debugf_Call

type MockLogger_Errorf_Call

type MockLogger_Errorf_Call struct {
	*mock.Call
}

MockLogger_Errorf_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Errorf'

func (*MockLogger_Errorf_Call) Return

func (*MockLogger_Errorf_Call) Run

func (_c *MockLogger_Errorf_Call) Run(run func(format string, v ...any)) *MockLogger_Errorf_Call

func (*MockLogger_Errorf_Call) RunAndReturn

func (_c *MockLogger_Errorf_Call) RunAndReturn(run func(string, ...any)) *MockLogger_Errorf_Call

type MockLogger_Expecter

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

func (*MockLogger_Expecter) Debugf

func (_e *MockLogger_Expecter) Debugf(format interface{}, v ...interface{}) *MockLogger_Debugf_Call

Debugf is a helper method to define mock.On call

  • format string
  • v ...any

func (*MockLogger_Expecter) Errorf

func (_e *MockLogger_Expecter) Errorf(format interface{}, v ...interface{}) *MockLogger_Errorf_Call

Errorf is a helper method to define mock.On call

  • format string
  • v ...any

func (*MockLogger_Expecter) Infof

func (_e *MockLogger_Expecter) Infof(format interface{}, v ...interface{}) *MockLogger_Infof_Call

Infof is a helper method to define mock.On call

  • format string
  • v ...any

func (*MockLogger_Expecter) Warnf

func (_e *MockLogger_Expecter) Warnf(format interface{}, v ...interface{}) *MockLogger_Warnf_Call

Warnf is a helper method to define mock.On call

  • format string
  • v ...any

type MockLogger_Infof_Call

type MockLogger_Infof_Call struct {
	*mock.Call
}

MockLogger_Infof_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Infof'

func (*MockLogger_Infof_Call) Return

func (*MockLogger_Infof_Call) Run

func (_c *MockLogger_Infof_Call) Run(run func(format string, v ...any)) *MockLogger_Infof_Call

func (*MockLogger_Infof_Call) RunAndReturn

func (_c *MockLogger_Infof_Call) RunAndReturn(run func(string, ...any)) *MockLogger_Infof_Call

type MockLogger_Warnf_Call

type MockLogger_Warnf_Call struct {
	*mock.Call
}

MockLogger_Warnf_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Warnf'

func (*MockLogger_Warnf_Call) Return

func (*MockLogger_Warnf_Call) Run

func (_c *MockLogger_Warnf_Call) Run(run func(format string, v ...any)) *MockLogger_Warnf_Call

func (*MockLogger_Warnf_Call) RunAndReturn

func (_c *MockLogger_Warnf_Call) RunAndReturn(run func(string, ...any)) *MockLogger_Warnf_Call

type MockSessionStore

type MockSessionStore[T any] struct {
	mock.Mock
}

MockSessionStore is an autogenerated mock type for the SessionStore type

func NewMockSessionStore

func NewMockSessionStore[T any](t interface {
	mock.TestingT
	Cleanup(func())
}) *MockSessionStore[T]

NewMockSessionStore creates a new instance of MockSessionStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockSessionStore[T]) Consume

func (_m *MockSessionStore[T]) Consume(token string) (*T, bool)

Consume provides a mock function with given fields: token

func (*MockSessionStore[T]) Create

func (_m *MockSessionStore[T]) Create(data T) (string, error)

Create provides a mock function with given fields: data

func (*MockSessionStore[T]) Delete

func (_m *MockSessionStore[T]) Delete(token string)

Delete provides a mock function with given fields: token

func (*MockSessionStore[T]) EXPECT

func (_m *MockSessionStore[T]) EXPECT() *MockSessionStore_Expecter[T]

func (*MockSessionStore[T]) Get

func (_m *MockSessionStore[T]) Get(token string) (*T, bool)

Get provides a mock function with given fields: token

type MockSessionStore_Consume_Call

type MockSessionStore_Consume_Call[T any] struct {
	*mock.Call
}

MockSessionStore_Consume_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Consume'

func (*MockSessionStore_Consume_Call[T]) Return

func (_c *MockSessionStore_Consume_Call[T]) Return(_a0 *T, _a1 bool) *MockSessionStore_Consume_Call[T]

func (*MockSessionStore_Consume_Call[T]) Run

func (_c *MockSessionStore_Consume_Call[T]) Run(run func(token string)) *MockSessionStore_Consume_Call[T]

func (*MockSessionStore_Consume_Call[T]) RunAndReturn

func (_c *MockSessionStore_Consume_Call[T]) RunAndReturn(run func(string) (*T, bool)) *MockSessionStore_Consume_Call[T]

type MockSessionStore_Create_Call

type MockSessionStore_Create_Call[T any] struct {
	*mock.Call
}

MockSessionStore_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'

func (*MockSessionStore_Create_Call[T]) Return

func (*MockSessionStore_Create_Call[T]) Run

func (_c *MockSessionStore_Create_Call[T]) Run(run func(data T)) *MockSessionStore_Create_Call[T]

func (*MockSessionStore_Create_Call[T]) RunAndReturn

func (_c *MockSessionStore_Create_Call[T]) RunAndReturn(run func(T) (string, error)) *MockSessionStore_Create_Call[T]

type MockSessionStore_Delete_Call

type MockSessionStore_Delete_Call[T any] struct {
	*mock.Call
}

MockSessionStore_Delete_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Delete'

func (*MockSessionStore_Delete_Call[T]) Return

func (*MockSessionStore_Delete_Call[T]) Run

func (_c *MockSessionStore_Delete_Call[T]) Run(run func(token string)) *MockSessionStore_Delete_Call[T]

func (*MockSessionStore_Delete_Call[T]) RunAndReturn

func (_c *MockSessionStore_Delete_Call[T]) RunAndReturn(run func(string)) *MockSessionStore_Delete_Call[T]

type MockSessionStore_Expecter

type MockSessionStore_Expecter[T any] struct {
	// contains filtered or unexported fields
}

func (*MockSessionStore_Expecter[T]) Consume

func (_e *MockSessionStore_Expecter[T]) Consume(token interface{}) *MockSessionStore_Consume_Call[T]

Consume is a helper method to define mock.On call

  • token string

func (*MockSessionStore_Expecter[T]) Create

func (_e *MockSessionStore_Expecter[T]) Create(data interface{}) *MockSessionStore_Create_Call[T]

Create is a helper method to define mock.On call

  • data T

func (*MockSessionStore_Expecter[T]) Delete

func (_e *MockSessionStore_Expecter[T]) Delete(token interface{}) *MockSessionStore_Delete_Call[T]

Delete is a helper method to define mock.On call

  • token string

func (*MockSessionStore_Expecter[T]) Get

func (_e *MockSessionStore_Expecter[T]) Get(token interface{}) *MockSessionStore_Get_Call[T]

Get is a helper method to define mock.On call

  • token string

type MockSessionStore_Get_Call

type MockSessionStore_Get_Call[T any] struct {
	*mock.Call
}

MockSessionStore_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get'

func (*MockSessionStore_Get_Call[T]) Return

func (_c *MockSessionStore_Get_Call[T]) Return(_a0 *T, _a1 bool) *MockSessionStore_Get_Call[T]

func (*MockSessionStore_Get_Call[T]) Run

func (_c *MockSessionStore_Get_Call[T]) Run(run func(token string)) *MockSessionStore_Get_Call[T]

func (*MockSessionStore_Get_Call[T]) RunAndReturn

func (_c *MockSessionStore_Get_Call[T]) RunAndReturn(run func(string) (*T, bool)) *MockSessionStore_Get_Call[T]

type MockUser

type MockUser struct {
	mock.Mock
}

MockUser is an autogenerated mock type for the User type

func NewMockUser

func NewMockUser(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockUser

NewMockUser creates a new instance of MockUser. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockUser) EXPECT

func (_m *MockUser) EXPECT() *MockUser_Expecter

func (*MockUser) WebAuthnCredentials

func (_mock *MockUser) WebAuthnCredentials() []webauthn.Credential

WebAuthnCredentials provides a mock function for the type MockUser

func (*MockUser) WebAuthnDisplayName

func (_mock *MockUser) WebAuthnDisplayName() string

WebAuthnDisplayName provides a mock function for the type MockUser

func (*MockUser) WebAuthnID

func (_mock *MockUser) WebAuthnID() []byte

WebAuthnID provides a mock function for the type MockUser

func (*MockUser) WebAuthnName

func (_mock *MockUser) WebAuthnName() string

WebAuthnName provides a mock function for the type MockUser

type MockUserStore

type MockUserStore struct {
	mock.Mock
}

MockUserStore is an autogenerated mock type for the UserStore type

func NewMockUserStore

func NewMockUserStore(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockUserStore

NewMockUserStore creates a new instance of MockUserStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockUserStore) Create

func (_mock *MockUserStore) Create(u NewUser) (User, error)

Create provides a mock function for the type MockUserStore

func (*MockUserStore) EXPECT

func (_m *MockUserStore) EXPECT() *MockUserStore_Expecter

func (*MockUserStore) Get

func (_mock *MockUserStore) Get(userID []byte) (User, error)

Get provides a mock function for the type MockUserStore

func (*MockUserStore) GetByName

func (_mock *MockUserStore) GetByName(username string) (User, error)

GetByName provides a mock function for the type MockUserStore

func (*MockUserStore) UpdateCredential

func (_mock *MockUserStore) UpdateCredential(userID []byte, credential webauthn.Credential) error

UpdateCredential provides a mock function for the type MockUserStore

type MockUserStore_Create_Call

type MockUserStore_Create_Call struct {
	*mock.Call
}

MockUserStore_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'

func (*MockUserStore_Create_Call) Return

func (*MockUserStore_Create_Call) Run

func (*MockUserStore_Create_Call) RunAndReturn

func (_c *MockUserStore_Create_Call) RunAndReturn(run func(u NewUser) (User, error)) *MockUserStore_Create_Call

type MockUserStore_Expecter

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

func (*MockUserStore_Expecter) Create

Create is a helper method to define mock.On call

  • u NewUser

func (*MockUserStore_Expecter) Get

Get is a helper method to define mock.On call

  • userID []byte

func (*MockUserStore_Expecter) GetByName

func (_e *MockUserStore_Expecter) GetByName(username any) *MockUserStore_GetByName_Call

GetByName is a helper method to define mock.On call

  • username string

func (*MockUserStore_Expecter) UpdateCredential

func (_e *MockUserStore_Expecter) UpdateCredential(userID any, credential any) *MockUserStore_UpdateCredential_Call

UpdateCredential is a helper method to define mock.On call

  • userID []byte
  • credential webauthn.Credential

type MockUserStore_GetByName_Call

type MockUserStore_GetByName_Call struct {
	*mock.Call
}

MockUserStore_GetByName_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetByName'

func (*MockUserStore_GetByName_Call) Return

func (*MockUserStore_GetByName_Call) Run

func (*MockUserStore_GetByName_Call) RunAndReturn

func (_c *MockUserStore_GetByName_Call) RunAndReturn(run func(username string) (User, error)) *MockUserStore_GetByName_Call

type MockUserStore_Get_Call

type MockUserStore_Get_Call struct {
	*mock.Call
}

MockUserStore_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get'

func (*MockUserStore_Get_Call) Return

func (*MockUserStore_Get_Call) Run

func (_c *MockUserStore_Get_Call) Run(run func(userID []byte)) *MockUserStore_Get_Call

func (*MockUserStore_Get_Call) RunAndReturn

func (_c *MockUserStore_Get_Call) RunAndReturn(run func(userID []byte) (User, error)) *MockUserStore_Get_Call

type MockUserStore_UpdateCredential_Call

type MockUserStore_UpdateCredential_Call struct {
	*mock.Call
}

MockUserStore_UpdateCredential_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateCredential'

func (*MockUserStore_UpdateCredential_Call) Return

func (*MockUserStore_UpdateCredential_Call) Run

func (*MockUserStore_UpdateCredential_Call) RunAndReturn

type MockUser_Expecter

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

func (*MockUser_Expecter) WebAuthnCredentials

func (_e *MockUser_Expecter) WebAuthnCredentials() *MockUser_WebAuthnCredentials_Call

WebAuthnCredentials is a helper method to define mock.On call

func (*MockUser_Expecter) WebAuthnDisplayName

func (_e *MockUser_Expecter) WebAuthnDisplayName() *MockUser_WebAuthnDisplayName_Call

WebAuthnDisplayName is a helper method to define mock.On call

func (*MockUser_Expecter) WebAuthnID

func (_e *MockUser_Expecter) WebAuthnID() *MockUser_WebAuthnID_Call

WebAuthnID is a helper method to define mock.On call

func (*MockUser_Expecter) WebAuthnName

func (_e *MockUser_Expecter) WebAuthnName() *MockUser_WebAuthnName_Call

WebAuthnName is a helper method to define mock.On call

type MockUser_WebAuthnCredentials_Call

type MockUser_WebAuthnCredentials_Call struct {
	*mock.Call
}

MockUser_WebAuthnCredentials_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WebAuthnCredentials'

func (*MockUser_WebAuthnCredentials_Call) Return

func (*MockUser_WebAuthnCredentials_Call) Run

func (*MockUser_WebAuthnCredentials_Call) RunAndReturn

type MockUser_WebAuthnDisplayName_Call

type MockUser_WebAuthnDisplayName_Call struct {
	*mock.Call
}

MockUser_WebAuthnDisplayName_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WebAuthnDisplayName'

func (*MockUser_WebAuthnDisplayName_Call) Return

func (*MockUser_WebAuthnDisplayName_Call) Run

func (*MockUser_WebAuthnDisplayName_Call) RunAndReturn

type MockUser_WebAuthnID_Call

type MockUser_WebAuthnID_Call struct {
	*mock.Call
}

MockUser_WebAuthnID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WebAuthnID'

func (*MockUser_WebAuthnID_Call) Return

func (*MockUser_WebAuthnID_Call) Run

func (*MockUser_WebAuthnID_Call) RunAndReturn

func (_c *MockUser_WebAuthnID_Call) RunAndReturn(run func() []byte) *MockUser_WebAuthnID_Call

type MockUser_WebAuthnName_Call

type MockUser_WebAuthnName_Call struct {
	*mock.Call
}

MockUser_WebAuthnName_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WebAuthnName'

func (*MockUser_WebAuthnName_Call) Return

func (*MockUser_WebAuthnName_Call) Run

func (*MockUser_WebAuthnName_Call) RunAndReturn

func (_c *MockUser_WebAuthnName_Call) RunAndReturn(run func() string) *MockUser_WebAuthnName_Call

type NewUser

type NewUser struct {
	Username   string
	UserID     []byte
	Credential webauthn.Credential
}

NewUser contains the data required to create a new registered user.

type Option

type Option func(*Passkey)

func WithInsecureCookie

func WithInsecureCookie() Option

WithInsecureCookie sets Cookie.Secure to false. This is useful for development. Do not use in production.

func WithLogger

func WithLogger(l Logger) Option

WithLogger sets the logger for the passkey instance.

func WithSessionCookieNamePrefix

func WithSessionCookieNamePrefix(prefix string) Option

WithSessionCookieNamePrefix sets custom prefix for names of the session cookies instead of default.

func WithUserSessionMaxAge

func WithUserSessionMaxAge(maxAge time.Duration) Option

WithUserSessionMaxAge sets the max age of the user session cookie.

type Passkey

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

func New

func New(cfg Config, opts ...Option) (*Passkey, error)

New creates new Passkey instance

func (*Passkey) Auth

func (p *Passkey) Auth(userIDKey AuthUserIDKey, onSuccess, onFail http.HandlerFunc) func(next http.Handler) http.Handler

Auth adds a valid user session's ID to the context, or calls onFail. A nil onFail defaults to Unauthorized.

func (*Passkey) Logout

func (p *Passkey) Logout(w http.ResponseWriter, r *http.Request)

Logout accepts POST with an allowed Origin, revokes the session, and returns 204.

func (*Passkey) MountRoutes

func (p *Passkey) MountRoutes(mux *http.ServeMux, path string)

MountRoutes mounts POST ceremony routes under path, which must end with a slash.

type RegistrationSessionData

type RegistrationSessionData struct {
	Username string
	Session  webauthn.SessionData
	Expires  time.Time
}

type SessionStore

type SessionStore[T any] interface {
	Create(data T) (string, error)
	Delete(token string)
	Get(token string) (*T, bool)
	Consume(token string) (*T, bool)
}

SessionStore is a storage for session data. Stores must use distinct key namespaces for each session type and application/tenant scope. Create must return a unique, cryptographically random token with at least 128 bits of entropy. Serialization must preserve all fields, including Purpose; adapters must not synthesize missing fields. Consume must atomically retrieve and delete the session identified by token to prevent replay. Get and Consume return (nil, false) for missing or expired records. Login and registration handlers consume ceremony sessions before verification, including failed attempts. Stores must bound retained records and reclaim expired entries before rejecting new sessions. Create returns ErrSessionStoreFull when capacity is exhausted; handlers enforce expiration independently.

type User

type User interface {
	webauthn.User
}

User is a user with webauthn credentials

type UserSessionData

type UserSessionData struct {
	Purpose string
	UserID  []byte
	Expires time.Time
}

type UserStore

type UserStore interface {
	Create(u NewUser) (User, error)
	// UpdateCredential atomically updates an existing credential's authentication state.
	// Preserve registration data and other credentials; ignore updates with older counters.
	// Retain previously observed clone warnings.
	// Unknown users and credentials return ErrUserNotFound and ErrCredentialNotFound respectively.
	UpdateCredential(userID []byte, credential webauthn.Credential) error

	Get(userID []byte) (User, error)
	GetByName(username string) (User, error)
}

UserStore is a persistent storage for users and credentials. Implementations of Create must atomically persist the account and its initial credential, preserving the exact UserID handle, and enforcing unique username and user ID. Create returns ErrUserAlreadyExists on conflicts; lookups return ErrUserNotFound for missing users. Reads and Create return detached snapshots, including credential byte slices. Errors may be logged; adapters must not include secrets or session tokens in them.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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