passkey

package
v0.4.6 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 15 Imported by: 1 module, 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

Passkeys

中文

passkey.Service registers and verifies WebAuthn credentials. It returns a verified identity; existing auth services issue sessions and apply RBAC. It has no password dependency and does not generate private keys, synchronize accounts, or assign permissions.

Registration requests discoverable credentials and requires user verification. The algorithm list is ML-DSA-44 (-48), then ES256 (-7). This is negotiation, not a hybrid signature: each credential keeps its registered algorithm. Login uses its stored public key. Google Password Manager and other providers use the same protocol. The browser/user chooses the provider; the server cannot force Google storage or promise its ML-DSA support. Accounts allowing classical credentials or password recovery are not wholly quantum-resistant.

Setup

The application supplies durable credentials and a lookup that rejects missing/disabled users. User IDs must be immutable, opaque, non-empty, free of surrounding whitespace, and never reassigned. Do not use an email address or username as the ID. WebAuthn user handles are stable SHA-256 values derived from the RP ID and account ID; changing either breaks existing credentials.

keys, err := passkey.New(passkey.Options{
    RPID:          "example.com",
    RPDisplayName: "Example",
    Origins:       []string{"https://example.com"},
    Store:         credentialStore,
    Flows:         passkey.NewMemoryFlowStore(10000),
    LookupUser:    lookupActiveUser,
})
if err != nil {
    return err
}

LookupUser has signature func(context.Context, string) (passkey.User, bool, error). Return false, nil for absent or disabled accounts; return an error for backend failures. Supply the current Name and DisplayName for the account picker. Lookup runs for registration, credential management, and after successful signature verification before login completes.

Use an RP-scoped store and flow namespace. Origins are explicit; do not derive them from untrusted request headers. The default ceremony lifetime is five minutes. Memory flows are bounded, process-local, and lost on restart; no background goroutines need closing. At capacity, new flows fail rather than evict live challenges. For multiple instances:

flows, err := redisflow.New(redisClient, "example.com:passkey:flow:")
if err != nil {
    return err
}
// Set passkey.Options.Flows to flows.

Redis 6.2+ and ContextTimeoutEnabled: true are required. The caller owns the client. Operations have a five-second timeout. Redis outages are errors, with no memory fallback. Consumption uses GETDEL; a failed finish requires a new begin, including when a backend fails after consumption. A timeout may leave the flow already consumed.

Choose the session integration

Cookie-backed auth:

handler, err := authhttp.NewHandler(manager, authhttp.Options{
    LoginAuthenticator: existingPasswordAuthenticator,
    Passkeys: keys,
})

login.finish issues the same session tokens as password login, sets refresh/CSRF cookies, and returns access_token, expires_at, and csrf_token. The existing login event runs before the response; failure revokes the issued refresh session. Its Username is empty for passkeys; use UserID as the identity.

RBAC:

// Build the existing rbac.Service first.
keys, err := passkey.New(passkey.Options{
    RPID: "example.com", RPDisplayName: "Example",
    Origins: []string{"https://example.com"},
    Store: credentialStore, Flows: flows,
    LookupUser: rbacService.PasskeyUser,
})
if err != nil {
    return err
}
handler, err := rbachttp.NewHandler(rbacService, rbachttp.Options{Passkeys: keys})

RBAC reloads the active user before issuing tokens and runs the existing success event. The response remains the RBAC login JSON, including refresh token, principal and session metadata. Roles/scopes come from the current user store, not the credential. API-token principals cannot bind or manage user passkeys.

Enable either integration independently. Both existing constructors retain their password dependency requirements, but passkey requests never call password verification. Passkeys: nil adds no routes. Applications with their own session issuance can use BeginRegistration, FinishRegistration, BeginLogin, and FinishLogin directly; they must authorize the user ID for registration and management. Do not expose an endpoint that treats a caller-supplied user ID as a verified identity.

HTTP contract

Paths follow the existing BasePath (default /auth). POST /auth/passkey takes JSON with operation:

Operation Other fields Authentication Success body
register.begin none User Bearer flow_id, options.publicKey
register.finish flow_id, name, credential Same user Bearer Credential metadata
login.begin persistence: session or persistent Public flow_id, options.publicKey
login.finish flow_id, credential Public Adapter's existing login response

credential is the object returned by PublicKeyCredential.toJSON(). Persistence is bound at begin; sending another value at finish does not change it. Flows are single-use and bound to their operation, RP and registration user. Names contain 1–100 Unicode characters after trimming.

GET /auth/passkeys returns {"credentials": [...]}. PATCH /auth/passkeys/{id} accepts {"name":"Phone"}; DELETE /auth/passkeys/{id} removes the credential. Both mutations return 204. All management operations require the owning user's Bearer token. IDs are unpadded base64url. Metadata contains id, name, created_at, and optional last_used_at; it excludes keys. Deleting a credential does not revoke established sessions. Compose with existing session revocation if required.

The ceremony endpoint uses the handler's body limit and a separate limiter with the same RateLimit options. Both begin and finish count as requests. Password lockout and CAPTCHA continue to protect password login; passkey traffic does not increment or clear password lockout state. Invalid assertions, inactive accounts, and consumed flows return 401; missing owned credentials return 404; duplicate registration returns 409; backend errors remain server errors. The mixed ceremony route's generated contract describes operation-specific authentication in its summary; registration enforces Bearer authentication at runtime.

Persistence and browser example

examples/passkey/postgres.go and schema.sql show an application-owned PostgreSQL implementation. This is an example, not an automatically installed migration or required schema. Add the application's user foreign key and account-deletion policy as appropriate.

  • Enforce uniqueness on (rp_id, id). Insert must never overwrite or transfer ownership.
  • Persist the complete webauthn.Credential, including public key, flags, authenticator state and extensions. Keep durable data separate from short-lived flows.
  • Usage updates must match credential ID and user ID, update only an existing record, and preserve keys and names. Never use an upsert. Preserve the maximum counter and latched verification state when concurrent requests complete out of order. Synchronized credentials may have zero counters; kit follows library counter/backup semantics instead of imposing strict monotonic rejection.
  • Propagate database failures. Login does not issue a session until the usage update succeeds.

client.js uses browser JSON conversion APIs, without provider detection or algorithm branches. Serve it from the configured HTTPS origin (localhost is supported for development), call registerPasskey(accessToken, name) for binding, and loginWithPasskey() for login. Consume the returned session using the selected auth adapter's conventions. Account signup, recovery, a management UI and Google synchronization are application/provider responsibilities.

Documentation

Overview

Package passkey provides WebAuthn registration and authentication. Package passkey 提供 WebAuthn 注册与身份验证。

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrRejected reports an invalid, expired, or already consumed ceremony.
	// ErrRejected 表示流程无效、过期或已消费。
	ErrRejected = errors.New("passkey authentication rejected")
	// ErrNotFound reports a credential absent from the requested user's account.
	// ErrNotFound 表示指定用户账户中不存在该凭据。
	ErrNotFound = errors.New("passkey not found")
	// ErrConflict reports an existing credential ID or flow ID.
	// ErrConflict 表示凭据 ID 或流程 ID 已存在。
	ErrConflict = errors.New("passkey already exists")
	// ErrInvalidName reports an empty or oversized credential name.
	// ErrInvalidName 表示凭据名称为空或过长。
	ErrInvalidName = errors.New("passkey name must contain 1 to 100 characters")
	// ErrCapacity reports a full flow store.
	// ErrCapacity 表示流程存储已满。
	ErrCapacity = errors.New("passkey flow capacity reached")
)

Functions

This section is empty.

Types

type Credential

type Credential struct {
	UserID     string
	Name       string
	CreatedAt  time.Time
	LastUsedAt time.Time
	Data       webauthn.Credential
}

Credential is the persisted record. Data must be stored in full. Credential 是持久化记录。Data 必须完整保存。

type Flow

type Flow struct {
	RPID        string
	Operation   string
	UserID      string
	SessionOnly bool
	Session     webauthn.SessionData
}

Flow is server-owned ceremony state; never accept it from clients. Flow 是服务端管理的流程状态,不能从客户端接收。

type FlowStore

type FlowStore interface {
	Create(ctx context.Context, id string, flow Flow) error
	Consume(ctx context.Context, id string) (Flow, bool, error)
}

FlowStore stores ceremonies until Flow.Session.Expires. Create must not overwrite; Consume must atomically remove and return a flow, returning false for absent/expired IDs. FlowStore 存储流程至 Flow.Session.Expires。Create 不能覆盖;Consume 必须原子移除并返回流程, 对不存在或过期的 ID 返回 false。

type Info

type Info struct {
	ID         string    `json:"id"`
	Name       string    `json:"name"`
	CreatedAt  time.Time `json:"created_at"`
	LastUsedAt time.Time `json:"last_used_at,omitzero"`
}

Info is user-visible credential metadata; it excludes the public key. Info 是用户可见的凭据元数据,不含公钥。

type Login

type Login struct {
	FlowID  string                        `json:"flow_id"`
	Options *protocol.CredentialAssertion `json:"options"`
}

Login contains browser assertion options and an opaque flow ID. Login 包含浏览器断言选项与不透明流程 ID。

type LoginResult

type LoginResult struct {
	User        User
	SessionOnly bool
}

LoginResult contains the verified account and server-bound session preference. LoginResult 包含已验证账户与绑定在服务端的会话偏好。

type MemoryFlowStore

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

MemoryFlowStore stores single-use flows in one process without background goroutines. MemoryFlowStore 在单进程内存储一次性流程,不启动后台 goroutine。

func NewMemoryFlowStore

func NewMemoryFlowStore(capacity int) *MemoryFlowStore

NewMemoryFlowStore constructs a bounded store. Non-positive capacity panics. NewMemoryFlowStore 构造有容量上限的存储。capacity 非正数时 panic。

func (*MemoryFlowStore) Consume

func (s *MemoryFlowStore) Consume(ctx context.Context, id string) (Flow, bool, error)

Consume atomically removes a flow, including expired flows. Consume 原子移除流程,包括已过期流程。

func (*MemoryFlowStore) Create

func (s *MemoryFlowStore) Create(ctx context.Context, id string, flow Flow) error

Create saves an unexpired flow without replacing an existing ID. Create 保存未过期流程,不替换已有 ID。

type Options

type Options struct {
	RPID          string
	RPDisplayName string
	Origins       []string
	Store         Store
	Flows         FlowStore
	LookupUser    func(context.Context, string) (User, bool, error)
	// Timeout defaults to five minutes.
	// Timeout 默认五分钟。
	Timeout time.Duration
}

Options configures one relying party. LookupUser must return ok=false for missing or disabled accounts. Stores must be scoped to this relying party. Options 配置单个依赖方。LookupUser 对不存在或禁用账户必须返回 ok=false。 存储必须限定在此依赖方范围内。

type Registration

type Registration struct {
	FlowID  string                       `json:"flow_id"`
	Options *protocol.CredentialCreation `json:"options"`
}

Registration contains browser creation options and an opaque flow ID. Registration 包含浏览器创建选项与不透明流程 ID。

type Service

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

Service verifies passkeys without issuing sessions. Construct with New. Service 验证通行密钥,不签发会话。使用 New 构造。

func New

func New(opts Options) (*Service, error)

New constructs a service requiring discoverable credentials and user verification. New 构造要求可发现凭据及用户验证的服务。

func (*Service) BeginLogin

func (s *Service) BeginLogin(ctx context.Context, sessionOnly bool) (Login, error)

BeginLogin starts a username-less login and binds its session preference. BeginLogin 开始无用户名登录并绑定会话偏好。

func (*Service) BeginRegistration

func (s *Service) BeginRegistration(ctx context.Context, userID string) (Registration, error)

BeginRegistration starts binding a credential. The caller must authorize userID. BeginRegistration 开始绑定凭据。调用方必须已授权 userID。

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, userID, id string) error

Delete removes an authorized user's credential without revoking sessions. Delete 删除已授权用户的凭据,不撤销现有会话。

func (*Service) FinishLogin

func (s *Service) FinishLogin(ctx context.Context, flowID string, response []byte) (LoginResult, error)

FinishLogin consumes a flow, verifies the assertion, checks the current account, and persists usage before returning an identity. It never issues tokens. FinishLogin 消费流程、验证断言、检查当前账户并保存使用状态后返回身份,不签发 token。

func (*Service) FinishRegistration

func (s *Service) FinishRegistration(ctx context.Context, userID, flowID, name string, response []byte) (Info, error)

FinishRegistration consumes a flow and saves the verified credential. The caller must authorize the same userID as BeginRegistration. FinishRegistration 消费流程并保存验证后的凭据。 调用方必须授权与 BeginRegistration 相同的 userID。

func (*Service) List

func (s *Service) List(ctx context.Context, userID string) ([]Info, error)

List returns metadata for an authorized user's credentials. List 返回已授权用户的凭据元数据。

func (*Service) Rename

func (s *Service) Rename(ctx context.Context, userID, id, name string) error

Rename changes an authorized user's credential name. Rename 修改已授权用户的凭据名称。

type Store

type Store interface {
	Insert(context.Context, Credential) error
	Get(ctx context.Context, id string) (Credential, bool, error)
	List(ctx context.Context, userID string) ([]Credential, error)
	UpdateUsage(ctx context.Context, id, userID string, authenticator webauthn.Authenticator, flags webauthn.CredentialFlags, at time.Time) (bool, error)
	Rename(ctx context.Context, id, userID, name string) (bool, error)
	Delete(ctx context.Context, id, userID string) (bool, error)
}

Store persists credentials. All methods must be concurrency-safe and return owned data. String credential IDs are unpadded base64url encodings of Data.ID. Insert must return ErrConflict for duplicate Data.ID and never overwrite a record. UpdateUsage must only update usage fields on an existing (id,userID) record; it must not insert, replace the key/owner/name, or decrease stored counters. Rename and Delete must also match both id and userID. False means not found. Store 持久化凭据。所有方法必须并发安全,返回独立数据。 字符串凭据 ID 是 Data.ID 的无填充 base64url 编码。 Insert 遇到重复 Data.ID 必须返回 ErrConflict,不能覆盖记录。 UpdateUsage 只能更新现有 (id,userID) 记录的使用状态,不能插入、替换密钥、所有者、名称或降低计数器。 Rename 和 Delete 也必须匹配 id 和 userID;false 表示不存在。

type User

type User struct {
	ID          string
	Name        string
	DisplayName string
}

User contains current account information. ID must be immutable, opaque, non-empty, without surrounding whitespace, and never reassigned. User 包含当前账户信息。ID 必须不变、不含个人信息、非空、无首尾空白且永不重新分配。

Directories

Path Synopsis
Package redisflow stores single-use WebAuthn flows in Redis.
Package redisflow stores single-use WebAuthn flows in Redis.

Jump to

Keyboard shortcuts

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