Authentication
UniAuth exposes separate email/password, passkey/WebAuthn, social OAuth, classic MFA, configured push, and recovery paths. Security, admission, lockout, risk, and optional session-signing behavior depends on the path and deployment configuration; do not assume every control applies to every method.
These examples describe UniAuth’s first-party, same-origin sign-in UI, not an integration API. Third-party apps must use hosted OAuth/OIDC Authorization Code with PKCE; they must not collect UniAuth passwords.
Email & Password Authentication
The primary authentication method uses email and password credentials. Passwords are hashed using Argon2id (via @node-rs/argon2) with the following parameters:
- Memory cost: 64 MB
- Time cost: 3 iterations
- Parallelism: 4 lanes
New and reset passwords are stored with Argon2id. Production password-hash import and transparent JIT login upgrade are unavailable. Standard profile import rejects legacy password credential fields and sends no onboarding message. Imported users need a separately initiated supported password reset or magic-link sign-in, or a separately implemented and validated credential bridge.
Registration
New users register via POST /api/auth/register with their email, password, and optional name fields. The password is validated against:
- zxcvbn strength check — Must score at least 2/4. The check is context-aware: it penalizes passwords that contain the user's email or name.
- HaveIBeenPwned breach check — Uses k-anonymity to safely check if the password has appeared in known breaches. This is a non-blocking warning (3-second timeout).
When email verification is required, registration attempts to issue a verification link and submit its message to the configured transport. The response reports whether that transport accepted the dispatch attempt; this does not prove inbox delivery, and a false result means no accepted dispatch was observed. Verification must be completed before features gated on a verified address become available, and another link can be requested from sign-in.
Login Flow
POST /api/auth/login
Content-Type: application/json
{
"email": "user@example.com",
"password": "securePassword123!"
}
// Success response (200):
{
"success": true,
"message": "Login successful",
"data": {
"authenticated": true,
"user": {
"id": "uuid",
"email": "user@example.com",
"firstName": "John",
"lastName": "Doe"
}
}
}
// If 2FA is enabled (200, requires second step):
{
"success": true,
"message": "2FA code required",
"data": {
"requires2FA": true,
"twoFactorMethod": "totp",
"enabledMethods": ["totp", "email"]
}
}On successful login, an HTTP-only, secure, SameSite cookie ( auth_token) is set with a 7-day expiration. The JWT payload contains the user's ID, email, name, avatar URL, and role. Sessions are also fingerprinted using a SHA-256 hash of the client's IP address and User-Agent string.
Bounded Statistical Login-Risk Assessment
Authentication paths that reach fresh risk evaluation use a statistical assessment. Factors include:
- Login from a new IP address not previously seen for this user
- Login from a new User-Agent / device
- Login at unusual hours (outside the user's historical pattern)
- Recent failed login attempts
- Burst detection (many rapid login attempts)
Per-user baselines are stored in the users.metadata.login_stats JSONB field. Baseline updates occur only on paths that explicitly record them; they are not guaranteed after every login method.
Social Login (Google & GitHub)
UniAuth supports OAuth-based social login with Google and GitHub. Both providers use PKCE (S256 code challenge) for security. The flow works as follows:
- The user clicks "Sign in with Google" or "Sign in with GitHub" on the login page.
- The client calls
POST /api/auth/oauth/initiatewith the provider name. - The server generates a CSRF state token and PKCE code_verifier, stores them in the user's metadata, and returns the authorization URL.
- The user is redirected to the provider's consent screen.
- After approval, the provider redirects back to
/api/auth/oauth/callbackwith an authorization code. - The server verifies the state, exchanges the code for tokens, fetches the user profile, and either logs in an existing user or creates a new account.
- The provider's access token is encrypted with AES-256-GCM before storage in the
connected_servicestable.
Configuration
To enable social login, set the following environment variables:
# Google OAuth
GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-google-client-secret
# GitHub OAuth
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secretThe callback URL to configure in your Google/GitHub OAuth app settings is:
https://your-domain.com/api/auth/oauth/callbackWebAuthn / Passkeys
UniAuth implements configured WebAuthn passkey registration and authentication using the @simplewebauthn/server and @simplewebauthn/browser packages. Registration requests direct attestation; the browser or authenticator may limit or withhold attestation.
Registering a Passkey
- The authenticated user navigates to their security settings.
- The client calls
POST /api/auth/passkey/register-optionsto obtain RP-bound options and a one-time, ceremony-bound registration challenge. - The browser invokes an authenticator, which may use a local PIN, biometric, or security key. UniAuth receives WebAuthn protocol data, not the biometric.
- The client sends the attestation response to
POST /api/auth/passkey/register-verify. - The server verifies the returned registration response against the configured origin and RP ID, then stores the accepted public-key credential in the
passkeystable.
Authenticating with a Passkey
- The client calls
POST /api/auth/passkey/authenticate-optionsto get authentication options. - The browser and authenticator decide whether and how an eligible passkey is offered and how local user verification is performed.
- The client sends the assertion response to
POST /api/auth/passkey/authenticate-verify. - On an eligible successful path, the server verifies the assertion and required user verification, applies counter and policy checks, then admits the session and counter update together.
Conditional UI (Passkey Autofill)
The login page attempts WebAuthn Conditional UI only when the browser reports autofill support. Credential display and selection remain browser- and authenticator-dependent.
The Relying Party (RP) ID is derived from the HOST environment variable. Validate the exact RP ID, origin, browser, and authenticator profile for the deployment.
Multi-Factor Authentication (2FA)
Classic TOTP, email OTP, and provider-backed SMS OTP factors may coexist. Configured push approval is a separate factor path, and passkeys are separate RP- and origin-bound WebAuthn credentials.
TOTP (Authenticator Apps)
TOTP uses 6-digit, 30-second RFC 6238 codes. Validate the intended authenticator clients for the deployment rather than treating named apps as a certified compatibility matrix. Setup flow:
- User calls
POST /api/auth/2fa/setupwith{ "method": "totp" }. - The server generates a TOTP secret, stores it with AES-256-GCM encryption, and returns data.method, data.secret, and data.qrCode.
- User scans the QR code with their authenticator app.
- User enters the 6-digit code to verify setup via
POST /api/auth/2fa/verify. - The verified factor becomes available on eligible first-party password-login paths. Verifying the first classic factor may also return eight one-use backup codes.
POST /api/auth/2fa/verify confirms enrollment only. It requires an auth_token cookie and step-up for 2fa.enable, with code and method in the body. It does not complete anonymous login.
Email OTP
Eligible configured paths can request a 6-digit code for the user's verified email address. The code is encrypted with AES-256-GCM before storage in the otp_tokens table and expires after a bounded validity window. A generic acknowledgement proves neither an account, proof issuance, transport acceptance, nor delivery. To request a code during login:
POST /api/auth/2fa/send-code
Content-Type: application/json
{
"email": "user@example.com",
"method": "email"
}
// Response (200):
{
"success": true,
"message": "Request processed",
"data": null
}Anonymous POST /api/auth/2fa/send-code accepts email and method (email or sms), not userId. Its generic Request processed response has data: null; it confirms neither an account, proof issuance, transport acceptance, nor delivery. Request another code only on a separate user action.
With an auth_token cookie, /api/auth/2fa/send-code instead authorizes a signed-in factor action using fresh, session-bound step-up for 2fa.disable. Send method, not another account’s email or userId. For email, advance only when data.emailDispatchAccepted === true; that means the configured transport accepted the request, not that a message reached an inbox.
Provider-backed SMS OTP
SMS OTP requires an eligible verified phone number and a usable configured Twilio, AWS SNS, or MessageBird route. The router selects the first usable matching rule; when no rules exist, it selects the first configured provider in Twilio, AWS SNS, then MessageBird order.
The UniAuth instance needs a usable Twilio, AWS SNS, or MessageBird route. See the Configuration guide for provider and routing configuration.
A generic request acknowledgement proves neither account existence nor handset delivery. Validate the chosen provider, route, destination format, and deployment limits.
Default Method Selection
When a user has multiple eligible classic or configured push factors, they can set a default via:
POST /api/auth/2fa/set-default
Content-Type: application/json
Cookie: auth_token=...
{
"method": "push" // "totp", "email", "sms", or "push"
}
// Response (200):
{
"success": true,
"message": "Push approval set as default",
"data": null
}On an eligible password login, the first usable default is offered first. Switching methods does not guarantee provider availability or delivery.
2FA Verification During Login
After data.requires2FA, complete password sign-in by posting email, password and twoFactorCode to /api/auth/login again. Use twoFactorMethod when selecting a method. No userId or pending-login token replaces the credentials; other required challenges, such as CAPTCHA, still apply.
POST /api/auth/login
Content-Type: application/json
{
"email": "user@example.com",
"password": "securePassword123!",
"twoFactorCode": "123456",
"twoFactorMethod": "totp"
}Apple and social sign-in use a separate pending credential: a browser cookie or a native pending credential (Apple returns applePendingToken; the continuation accepts it as pendingToken). Continue through /api/auth/social/2fa-options and /api/auth/social/2fa-verify; do not replace that flow with password login or /api/auth/2fa/verify.
Account Lockout
UniAuth applies progressive account lockout using the configured maxLoginAttempts limit. The thresholds below derive from that limit; when a failure meets multiple thresholds, the longest applicable duration is retained:
| Failed Attempts | Lockout Duration |
|---|---|
| max(1, floor(25% of the configured limit)) | 1 minute |
| max(1, floor(50% of the configured limit)) | 5 minutes |
| max(1, floor(75% of the configured limit)) | 15 minutes |
| Configured limit or above | 1 hour |
When an account is locked, the API returns HTTP 401 with a generic invalid credentials message (to prevent account enumeration). The counter resets on successful login or passkey authentication. Lockout state is stored in the failed_login_attempts and locked_until columns on the users table.
Session Management
Sessions are managed with multiple layers of security:
Session Lifecycle
- Inactivity timeout: Sessions expire after 24 hours of inactivity (configurable). The
last_activity_attimestamp is updated on each request viatouchSession(). - Concurrent session limit: A maximum of 10 active sessions per user (configurable). When the limit is reached, the oldest session is automatically revoked.
- Password-change revocation: When a user changes their password, all other sessions are immediately invalidated via
invalidateOtherSessions().
Session Fingerprinting
Each session is fingerprinted using a SHA-256 hash of the client's IP address and User-Agent. This fingerprint is stored in the fingerprint_hash column. If a subsequent request's fingerprint does not match the stored value, the system flags a potential session hijack.
Post-Quantum Session Signatures
When signing material is available, new sessions may receive an ML-DSA-44 (FIPS 204) signature. The server maintains encrypted signing material in system_settings). A present signature can be verified, but legacy sessions and sessions issued while initialization or signing is unavailable may have no PQC signature.
Viewing and Revoking Sessions
Users can view their active sessions and revoke individual sessions or all sessions at once:
// List active sessions
GET /api/user/sessions
// Revoke all sessions except current
POST /api/user/sessions/revoke-allData Retention
UniAuth automatically cleans up expired data via a scheduled task that runs every 24 hours (initialized in instrumentation.ts):
- Expired sessions: purged after 30 days
- Expired tokens (password reset, email verification): purged after 7 days
- Expired OTP codes: purged after 24 hours
- Old activity logs: purged after 1 year