Virtneu Auth Docs

Authentication and sessions

Register a verified user, sign in, renew sessions, and revoke access.

This guide targets the published SDK 0.7.0. Use the matching API/schema before adopting the new capabilities; npm publication and registry consumer checks are separate from production API activation. Handle incomplete authentication before establishing a session.

For system-browser login in Web, macOS or Windows applications, see OAuth and OpenID Connect. That separate protocol uses client registrations, Authorization Code + PKCE and OIDC tokens; the /v1 session flows below keep their existing contract.

Prepare your backend key

Use the auth client configured in the Quickstart. Its sample sessions:validate key can validate sessions. Add the scopes needed for the flows you implement:

FlowRequired scopes
Email challenge and code verificationauth:challenge
Registration onlyauth:challenge, auth:register
Registration and sign-in in one stepauth:challenge, auth:register, auth:login
Password sign-inauth:login
Email-code sign-inauth:challenge, auth:login
Password resetauth:challenge, auth:password_reset
Validation, refresh, logoutsessions:validate, sessions:refresh, sessions:revoke, respectively

Each example runs on your backend. external_user_id is a stable identity you assign; it can be a random UUID even if your application has no local users table. Generate it once when a signup starts and keep it with that short-lived signup attempt and its operation keys across retries. Do not generate a new ID on each request or derive it from an email address. Virtneu Auth returns its own stable user_id; business records can reference that ID directly without creating a local users or mapping table. See the complete integration without a local directory.

Register a user

Choose a stable identifier and send it as external_user_id. Keep it consistent across challenge, verification, registration, and retries. An email address is a verified binding for that identity.

  1. In Studio, open the app's test environment and configure a supported Email provider. Verify real delivery before enabling registration.
  2. Call createChallenge with purpose register.
  3. Ask the user for the delivered code and call verifyChallenge.
  4. Pass the resulting proof to registerUserAndSession to create the new account and its first session together. The proof must match the app, environment, purpose, email, and external user ID.

The following calls run on your backend. Persist each idempotency key with its request, and use a separate key for each step.

// Start registration and return the challenge ID to your client.
const { data: challenge } = await auth.createChallenge(
  { external_user_id: userId, email, purpose: 'register' },
  { idempotencyKey: challengeKey },
);

// After the user submits the code, verify it and register their account.
const { data: proof } = await auth.verifyChallenge(
  { challenge_id: challenge.challenge_id, code },
  { idempotencyKey: verifyKey },
);
// Save the proof in the protected attempt before completion. On a completion
// retry load that proof and call only registerUserAndSession, not verifyChallenge.
const { data: registered } = await auth.registerUserAndSession(
  { external_user_id: userId, email, authentication_proof: proof.authentication_proof, password },
  { idempotencyKey: registrationKey },
);

When 'authentication_required' in registered, finish the MFA enrollment or verification described below; this response has no session token or authenticated user projection. Otherwise registered contains user_id, external_user_id, session_token, and session expiry fields. Store the completed token with the cookie/session protections described below and use its user_id on business records. A password is optional; omit it for email-code accounts. This flow needs only the registration code, so a new user does not receive a second login code.

registerUserAndSession calls POST /v1/registrations and requires both auth:register and auth:login. It only creates new users; a registration proof cannot sign in to an existing account. createSession continues to accept only a password or a login proof. A retry uses the original registration key and identical parameters within the recovery window; it does not create another account or restore a revoked session.

Use registerUser (POST /v1/users, auth:register) when your product deliberately creates an account without signing in. That operation returns the user identity only; a later sign-in requires a password or a fresh login challenge. Do not route every existing user through registration.

Email providers support Resend and Cloudflare Email Sending. Save a draft, send a test email, check the recipient inbox, then enable authentication emails for that configuration revision. MAIL_NOT_CONFIGURED means the selected environment has no enabled sender.

Codes are six digits and expire after five minutes. A successful verification returns a purpose-bound, one-use proof that expires after two minutes. Login and reset challenges require the identity's existing verified email. The API returns a uniform acceptance response for unavailable identities.

Sign in

const { data } = await auth.createSession(
  { external_user_id: userId, password },
  { idempotencyKey },
);
if ('authentication_required' in data) {
  // Keep authentication_token in the protected sign-in attempt.
  // Complete MFA; this response cannot establish a session or user ownership.
} else {
  // Only this branch may use data.session_token to establish a session.
}

Generate an idempotency key for each logical login attempt. If a request times out, reuse the original key and parameters within the recovery window. See retry rules.

Only store a completed session's session_token in a backend session or a protected HttpOnly, Secure, SameSite cookie. Bound the cookie lifetime by the returned expires_at. Use your application's own rules for business permissions.

Sign in with an email code

Issue a challenge with purpose login and verify the delivered code using the same steps as registration. Pass the returned login proof to createSession:

const { data: login } = await auth.createSession(
  { external_user_id: userId, authentication_proof: loginProof },
  { idempotencyKey: loginKey },
);

Check 'authentication_required' in login before using the result as a session. The proof belongs to the same app, environment and external user ID. Registration can omit password for an email-code account. If password authentication is disabled in the environment, omit the password during registration and use email-code sign-in.

MFA and authentication continuations

Studio controls MFA enrollment (off, optional, required), passkey availability and whether verified passkey user verification may satisfy MFA for each App/environment. Primary login can return HTTP 202 with authentication_required: true, a short-lived authentication_token, next_step and allowed methods. This is not a session. Keep the token with the same protected attempt and service credential.

For next_step: "enroll", use only methods offered by the response. The TOTP path calls prepareMfaEnrollment({ authentication_token }); privately show the returned TOTP URI and recovery codes once, then submit the authenticator code with confirmMfaEnrollment({ enrollment_token, code }). The 0.6.0 API may additionally offer passkey when verified user verification satisfies the policy and the user has no passkey or verified TOTP. That path uses the primary continuation to begin passkey registration on the hosted RP and returns a complete session only after successful verification. It requires the matching API/schema and 0.6.0 SDK; immutable 0.5.0 does not gain this extension. For next_step: "mfa" with totp / recovery_code, call verifyMfa with the corresponding method. If the response instead offers only passkey, restart authentication with the already enrolled passkey; a password/email/social primary attempt cannot bind a replacement passkey or TOTP. Check the returned authentication result after completion; only a completed session can establish user access.

getMfaStatus reads enrollment status. Disabling MFA and regenerating recovery codes require a recent complete session and TOTP; successful mutations invalidate older sessions. Never automatically retry uncertain factor mutations. Google Authenticator supplies TOTP codes; it is separate from passkeys.

Without an embedded context, passkeys use the hosted authentication domain and a server-verified signature. SDK 0.7.0 also offers same-page and native embedded passkeys, using a verified customer RP and fixed backend context, not arbitrary client-selected origin. Both routes require UV and current MFA policy; otherwise MFA continues with TOTP. Hosted OIDC remains available for application sign-in and Google / GitHub / Apple authorization. The SDK does not accept browser-supplied provider tokens as a login shortcut.

For passkey management after application login, add an Account security action to your application's settings. It creates an independent hosted security transaction using the current OIDC access token and fresh state/nonce/PKCE, requires the same user to authenticate, and returns a new authorization code after Done. Old sessions revoked by a security change must be replaced through that callback; cancelling does not restore them. Passkey list/rename metadata and the backend-only contract are covered in the SDK guide.

Reset a password

Issue a challenge with purpose reset_password, verify the delivered code, then use that reset proof:

await auth.resetPassword(
  {
    external_user_id: userId,
    authentication_proof: resetProof,
    new_password: newPassword,
  },
  { idempotencyKey: resetKey },
);

User passwords must contain 8 to 128 characters. Reset creates or replaces the password credential and invalidates the user's existing sessions and proofs. Sign in again after success. Password registration, sign-in and reset require password authentication to be enabled in the selected environment; otherwise the API returns PASSWORD_AUTH_DISABLED.

Manage a session

ActionSDK methodBehavior
Check a requestvalidateSession(token)Returns active: false for an inactive session. The check does not extend expiry.
Extend an active sessionrefreshSession(token, { idempotencyKey })Extends the idle lifetime under the original absolute deadline and keeps the same token.
Sign outrevokeSession(token)Revokes that session. Repeated revocations are safe.

A service failure such as HTTP 503 means the session could not be checked. Handle it as a failed validation and preserve the distinction from an inactive session.

Password resets, account disablement, and revoking all sessions invalidate existing sessions. Re-enabling a user does not restore old sessions. The default idle lifetime is seven days and the default absolute lifetime is 30 days. App settings can change the policy for future sessions.

After a successful refresh, update your backend session or cookie expiration from the returned expires_at. The token stays the same. A refresh response contains session metadata; the token was delivered when the session was created.

For persistent cookies, low-frequency renewal across visits, cross-tab coordination and the new combined session context HTTP endpoint, see Browser session renewal. getSessionContext is included in SDK 0.4.0; the immutable 0.3.0 package does not contain it.

On this page