Skip to Content

Authentication

The @puzzle-ui/auth package provides framework-independent account, session, MFA, and authentication lifecycle primitives for Puzzle applications.

@puzzle-ui/auth is the server-side authentication core for Puzzle. It provides storage-backed registration and sign-in, account lifecycle workflows, multi-factor authentication, passkeys, recovery codes, and step-up verification without coupling those features to a web framework.

The package accepts storage, session, password-hashing, email, rate-limit, secret-protection, and WebAuthn dependencies through explicit interfaces. Your application remains responsible for creating secure HTTP endpoints, managing cookies and CSRF, and deciding what authenticated users may do.

Install

For a complete registration-to-dashboard flow, follow the Auth tutorial. Auth core, Session and the Fullstack integrations used there have Stable APIs, with within-major backward-compatibility intent. See the maturity policy.

npm install @puzzle-ui/auth

@puzzle-ui/auth depends on @puzzle-ui/storage, @puzzle-ui/session, and @simplewebauthn/server. You provide the storage and session implementations, password hasher, and rate-limit provider.

Quick start

Create a manager with server-side dependencies, initialize it before serving requests, and keep the returned token on the server boundary so it can be set in a secure, HttpOnly cookie.

import { StorageAuthManager } from "@puzzle-ui/auth";

const auth = new StorageAuthManager(
  { storage, passwordHasher, rateLimitProvider, sessions },
  { rateLimitKeySecret },
);

await auth.initialize();

const result = await auth.register({
  email: "person@example.com",
  password: "a-long-unique-password",
  ipAddress: trustedClientIp,
});

if ("status" in result) {
  // MFA is required; complete the enrollment flow on the server.
} else {
  // Set result.token in a secure, HttpOnly cookie. Do not return it in JSON.
}

The StorageAuthManager creates an authenticated session after registration unless policy requires an MFA enrollment first. A password sign-in can return an MFA challenge instead of a session. See MFA and step-up for how to complete these flows.

What the package provides

AreaDescriptionDocumentation
Authentication managerRegistration, password sign-in, session lookup, auth-state lookup, and sign-out.Configuration
Account lifecycleEmail verification and change, password reset and change, profile update, deactivation, and deletion.Account lifecycle
MFA and passkeysTOTP, WebAuthn passkeys, recovery codes, mandatory enrollment, and session-bound step-up.MFA and step-up
Deployment securityStorage capabilities, token handling, encryption, rate limits, and production guidance.Security

Authentication states

getAuthState(token) reports the server-side state for an authentication or pending challenge token. Treat only authenticated as normal application access.

StatusMeaning
unauthenticatedNo valid authenticated session or pending challenge was found.
primary-authenticatedA staged-auth state represented in the public state type; it is not returned by the core manager. Do not treat it as full access.
mfa-pendingPassword authentication succeeded and an enrolled factor must be verified.
mfa-enrollment-pendingPolicy requires initial enrollment; no normal session is issued yet.
mfa-enrollment-requiredA valid session exists, but policy requires a factor before protected access.
authenticatedThe session is valid and satisfies the configured email-verification and MFA policy.

Challenge tokens, like session tokens, are credentials. Keep them server-side and transport them only in appropriately scoped secure, HttpOnly cookies.

Integrating packages

  • @puzzle-ui/storage provides the adapter used to persist users, credentials, audit records, challenges, recovery codes, and rate-limit counters. Authentication requires the storage capabilities described in Security.
  • @puzzle-ui/fullstack provides server handlers, browser clients, cookie and CSRF integration, and framework adapters. The developer authentication guide covers generated application setup.
  • Auth also stores authentication audit events; keep credentials and secret values out of logs and telemetry.

Public exports

The package currently has one public entry point, @puzzle-ui/auth, and no documented subpath exports.

GroupExports
ManagersStorageAuthManager, StorageAuthLifecycleManager, StorageAuthMfaManager, StorageAuthStepUpManager, StorageRateLimitProvider
ProvidersWebCryptoAuthSecretProtector, SimpleWebAuthnProvider, Pbkdf2PasswordHasher, PASSWORD_HASH_ALGORITHMS
StorageAUTH_USER_COLLECTION, AUTH_CREDENTIAL_COLLECTION, AUTH_ACTION_TOKEN_COLLECTION, AUTH_AUDIT_COLLECTION, AUTH_RATE_LIMIT_COLLECTION, AUTH_MFA_FACTOR_COLLECTION, AUTH_MFA_CHALLENGE_COLLECTION, AUTH_RECOVERY_CODE_COLLECTION, AUTH_MFA_STEP_UP_COLLECTION, initializeAuthStorage
ErrorsAuthError, AuthValidationError, AuthInvalidCredentialsError, AuthEmailVerificationRequiredError, AuthAccountConflictError, AuthRateLimitError, AuthConfigurationError, AuthProviderError, AuthSessionError, AuthTokenError, AuthMfaChallengeError, AuthMfaFactorError
Email and crypto utilitiesnormalizeEmail, normalizeDisplayName, generateAuthId, generateSecureAuthToken, hashAuthToken, createRateLimitKey, encodeBase32, decodeBase32, generateTotpSecret, generateTotpCode, verifyTotpCode, createTotpUri
Core auth typesAuthUser, AuthState, PasswordCredentialStorageRecord, AuthManager, AuthManagerOptions, AuthManagerDependencies, StorageAuthManagerDependencies, AuthRateLimitRule, AuthRateLimitScopePolicy, AuthRateLimitPolicies, AuthSession, AuthResult, AuthRegisterResult, AuthSignInResult, AuthRegisterInput, AuthSignInInput, AuthMfaPolicy
Lifecycle and rate-limit typesAuthActionTokenPurpose, AuthActionTokenStorageRecord, AuthAuditAction, AuthAuditEventStorageRecord, AuthRateLimitStorageRecord, AuthLifecycleRateLimitAction, AuthLifecycleRateLimitPolicy, AuthLifecycleRateLimitPolicies, AuthLifecycleManagerOptions, StorageAuthLifecycleManagerDependencies, RequestEmailVerificationInput, RequestPasswordResetInput, ResetPasswordInput, ChangePasswordInput, UpdateAuthProfileInput, RequestEmailChangeInput, DeleteAuthAccountInput, DeactivateAuthAccountInput, StorageRateLimitProviderOptions
Provider typesPasswordHash, PasswordHashAlgorithm, PasswordHasher, Pbkdf2PasswordHasherOptions, EmailMessage, EmailProvider, RateLimitProvider, ProtectedAuthSecret, AuthSecretProtector, WebAuthnOptionsJSON, WebAuthnRegistrationCredential, WebAuthnRegistrationVerification, WebAuthnAuthenticationVerification, WebAuthnProvider, WebCryptoAuthSecretProtectorOptions
MFA typesAuthMfaFactorType, AuthMfaFactorStatus, AuthMfaAvailableFactor, AuthMfaEnrollmentFactor, AuthMfaFactor, AuthMfaFactorStorageRecord, AuthMfaChallengePurpose, AuthMfaChallengeStorageRecord, AuthRecoveryCodeStorageRecord, AuthMfaPendingResult, AuthMfaEnrollmentPendingResult, AuthMfaEnrollmentCompleted, AuthMfaGateway, AuthMfaTotpOptions, AuthMfaWebAuthnOptions, AuthMfaManagerOptions, StorageAuthMfaManagerDependencies, BeginTotpEnrollmentInput, TotpEnrollmentStarted, VerifyTotpEnrollmentInput, MfaEnrollmentCompleted, BeginRequiredMfaEnrollmentInput, VerifyRequiredTotpEnrollmentInput, FinishRequiredPasskeyEnrollmentInput, BeginPasskeyRegistrationInput, PasskeyRegistrationStarted, FinishPasskeyRegistrationInput, BeginPasskeySignInInput, PasskeySignInStarted, CompleteMfaSignInInput, PasskeyMfaStarted, PasskeyMfaCompletedInput, RemoveMfaFactorInput, RegenerateRecoveryCodesInput
Step-up and storage typesAuthStepUpChallengeStorageRecord, AuthStepUpManagerOptions, StorageAuthStepUpManagerDependencies, BeginStepUpInput, CompleteStepUpInput, BeginStepUpPasskeyInput, FinishStepUpPasskeyInput, AuthStepUpPendingState, AuthUserStorageRecord, InitializeAuthStorageOptions
Error typesAuthErrorCode

See the configuration, lifecycle, and MFA pages for option defaults and method behavior.