Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .changeset/29105-two-factor-sign-in.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
'@object-ui/auth': patch
'@object-ui/app-shell': patch
'@object-ui/i18n': patch
'@object-ui/console': patch
---

fix(auth): a user with two-factor sign-in on is asked for their code after the password, instead of staying on the sign-in page

Clause-②: yes (widening)
Metadata-protocol: none

A user who turned on two-factor sign-in (an authenticator app) and signed in with their password could not get into the Console: the server accepted the password and asked for the second factor, the Console dropped that answer, and the sign-in page stayed as it was, with no code field and no message.

The sign-in form now shows a second step: the 6-digit code from the authenticator app, or one of the backup codes saved at set-up. A wrong code says so in place and the user can try again; "Back to sign in" returns to the password step. When the server ends the attempt (too many wrong codes, or ten minutes passed), the password step comes back with the reason. Both login pages (the Console's and `DefaultLoginPage`) show the step, in every language pack.

Added to `@object-ui/auth`: `AuthClient.signIn` answers `{ twoFactor: { methods } }` for such an account (exported `SignInResult`, `TwoFactorChallenge`, `TwoFactorMethod`); `AuthClient.verifySignInTwoFactor(code, 'totp' | 'backup-code')` finishes it (`SignInTwoFactorCodeKind`); `useAuth()` gains `twoFactorChallenge`, `verifySignInTwoFactor` and `cancelTwoFactorChallenge`, and its `signIn` resolves `{ twoFactorRequired }`; `LoginFormLabels` gains ten `twoFactor*` labels. `@object-ui/i18n` gains the matching `auth.login.twoFactor*` and `auth.login.errors.twoFactor*` keys.

What to do: nothing, unless you pass your own `AuthClient` to `AuthProvider`. `verifySignInTwoFactor` is a required member of `AuthClient`, so such an implementation must add it to type-check (and its `signIn` may now answer `{ twoFactor }`).
20 changes: 19 additions & 1 deletion ui/apps/console/src/pages/auth/LoginPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,13 @@ function DevAdminRow({ seed }: { seed: DevSeedAdmin }) {
setError(null);
setPending(true);
try {
await signIn(seed.email, seed.password);
const { twoFactorRequired } = await signIn(seed.email, seed.password);
// The seeded admin enrolled two-factor sign-in: the form beside this
// row now asks for the code (objectstack#29105), so this chip is idle.
if (twoFactorRequired) {
setPending(false);
return;
}
// Signed in: `user` is set and the page swaps to its post-login state.
} catch (err) {
const authError = err instanceof Error ? err : new Error(String(err));
Expand Down Expand Up @@ -595,6 +601,18 @@ function LoginFormCard({
noSignInMethodText: t('auth.login.noSignInMethodText', {
defaultValue: 'No sign-in method is available. Contact your administrator.',
}),
// The two-factor step a password sign-in leads to when the account
// has two-factor sign-in on (objectstack#29105).
twoFactorTitle: t('auth.login.twoFactorTitle', { defaultValue: 'Two-factor authentication' }),
twoFactorDescription: t('auth.login.twoFactorDescription', { defaultValue: 'Enter the 6-digit code from your authenticator app.' }),
twoFactorBackupDescription: t('auth.login.twoFactorBackupDescription', { defaultValue: 'Enter one of the backup codes you saved when you set up two-factor authentication.' }),
twoFactorCodeLabel: t('auth.login.twoFactorCodeLabel', { defaultValue: 'Authentication code' }),
twoFactorBackupCodeLabel: t('auth.login.twoFactorBackupCodeLabel', { defaultValue: 'Backup code' }),
twoFactorVerifyButton: t('auth.login.twoFactorVerifyButton', { defaultValue: 'Verify' }),
twoFactorVerifyingButton: t('auth.login.twoFactorVerifyingButton', { defaultValue: 'Verifying…' }),
twoFactorUseBackupCodeText: t('auth.login.twoFactorUseBackupCodeText', { defaultValue: 'Use a backup code instead' }),
twoFactorUseAuthenticatorText: t('auth.login.twoFactorUseAuthenticatorText', { defaultValue: 'Use your authenticator app instead' }),
twoFactorBackText: t('auth.login.twoFactorBackText', { defaultValue: 'Back to sign in' }),
}}
/>
);
Expand Down
12 changes: 12 additions & 0 deletions ui/packages/app-shell/src/console/auth/LoginPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,18 @@ export function LoginPage() {
usePasswordText: t('auth.login.usePasswordText'),
backToSsoText: t('auth.login.backToSsoText'),
noSignInMethodText: t('auth.login.noSignInMethodText'),
// The two-factor step a password sign-in leads to when the account
// has two-factor sign-in on (objectstack#29105).
twoFactorTitle: t('auth.login.twoFactorTitle'),
twoFactorDescription: t('auth.login.twoFactorDescription'),
twoFactorBackupDescription: t('auth.login.twoFactorBackupDescription'),
twoFactorCodeLabel: t('auth.login.twoFactorCodeLabel'),
twoFactorBackupCodeLabel: t('auth.login.twoFactorBackupCodeLabel'),
twoFactorVerifyButton: t('auth.login.twoFactorVerifyButton'),
twoFactorVerifyingButton: t('auth.login.twoFactorVerifyingButton'),
twoFactorUseBackupCodeText: t('auth.login.twoFactorUseBackupCodeText'),
twoFactorUseAuthenticatorText: t('auth.login.twoFactorUseAuthenticatorText'),
twoFactorBackText: t('auth.login.twoFactorBackText'),
}}
/>
);
Expand Down
19 changes: 19 additions & 0 deletions ui/packages/app-shell/src/console/auth/signInRefusalMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,24 @@ export function signInRefusalMessages(t: TranslateFn): Record<string, string> {
EMAIL_NOT_VERIFIED: t('auth.login.errors.emailNotVerified', {
defaultValue: 'Please verify your email address before signing in.',
}),
// objectstack#29105 — refusals of the two-factor step (better-auth's
// `twoFactor()` codes). A wrong code is shown on the step itself; a spent
// or expired challenge (the third and fourth) on the password step it
// returns to.
INVALID_CODE: t('auth.login.errors.twoFactorInvalidCode', {
defaultValue: 'That code is not valid. Check your authenticator app and try again.',
}),
INVALID_BACKUP_CODE: t('auth.login.errors.twoFactorInvalidBackupCode', {
defaultValue: 'That backup code is not valid or has already been used.',
}),
TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE: t('auth.login.errors.twoFactorTooManyAttempts', {
defaultValue: 'Too many incorrect codes. Sign in with your password again.',
}),
INVALID_TWO_FACTOR_COOKIE: t('auth.login.errors.twoFactorExpired', {
defaultValue: 'This sign-in has expired. Sign in with your password again.',
}),
ACCOUNT_TEMPORARILY_LOCKED: t('auth.login.errors.twoFactorLocked', {
defaultValue: 'Too many failed attempts. Your account is temporarily locked. Try again later.',
}),
};
}
28 changes: 25 additions & 3 deletions ui/packages/auth/src/AuthContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/

import { createContext } from 'react';
import type { AuthUser, AuthClientSession, PreviewModeOptions, AuthOrganization, AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, AuthPublicConfig, SignInWithProviderOptions, DelegableScope } from './types.js';
import type { AuthUser, AuthClientSession, PreviewModeOptions, AuthOrganization, AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, AuthPublicConfig, SignInWithProviderOptions, DelegableScope, TwoFactorChallenge, SignInTwoFactorCodeKind } from './types.js';

export interface AuthContextValue {
/** Current authenticated user */
Expand All @@ -31,8 +31,30 @@ export interface AuthContextValue {
isPreviewMode: boolean;
/** Preview mode configuration (only set when isPreviewMode is true) */
previewMode: PreviewModeOptions | null;
/** Sign in with email and password */
signIn: (email: string, password: string) => Promise<void>;
/**
* Sign in with email and password. `twoFactorRequired` is true when the
* server accepted the password but the account has two-factor sign-in on
* (objectstack#29105): no user is signed in yet, `twoFactorChallenge` is
* set, and `verifySignInTwoFactor` finishes the sign-in.
*/
signIn: (email: string, password: string) => Promise<{ twoFactorRequired: boolean }>;
/**
* objectstack#29105 — the pending two-factor sign-in, or `null`. Set by a
* `signIn` whose password the server accepted for an account with
* two-factor sign-in on; cleared when the code is verified, when
* `cancelTwoFactorChallenge` runs, and when the server reports the pending
* sign-in spent or expired.
*/
twoFactorChallenge: TwoFactorChallenge | null;
/**
* Finish the pending two-factor sign-in with an authenticator code or a
* backup code. Rejects with the server's `code` on a wrong code and keeps
* the challenge; on a spent or expired challenge it also clears it, so the
* user signs in with their password again.
*/
verifySignInTwoFactor: (code: string, kind: SignInTwoFactorCodeKind) => Promise<void>;
/** Abandon the pending two-factor sign-in and go back to the password step. */
cancelTwoFactorChallenge: () => void;
/** Sign up with name, email, and password.
* Returns `{ requiresVerification: true }` when the server accepted the
* account but is gating sign-in on email verification; callers should
Expand Down
46 changes: 44 additions & 2 deletions ui/packages/auth/src/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@

import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { authGateEvents } from './auth-gate-events.js';
import type { AuthUser, AuthClient, AuthProviderOptions, PreviewModeOptions, AuthOrganization, AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, AuthPublicConfig, SignInWithProviderOptions } from './types.js';
import type { AuthUser, AuthClient, AuthProviderOptions, PreviewModeOptions, AuthOrganization, AuthOrganizationMember, AuthInvitation, AuthInvitationPreview, AuthPublicConfig, SignInWithProviderOptions, SignInTwoFactorCodeKind, TwoFactorChallenge } from './types.js';
import { TWO_FACTOR_CHALLENGE_ENDED_CODES } from './two-factor-codes.js';
import { AuthCtx, type AuthContextValue } from './AuthContext.js';
import { createAuthClient, takePreflightSession, TokenStorage } from './createAuthClient.js';
import { ActiveOrganizationStorage, SessionUserScope } from './ActiveOrganizationStorage.js';
Expand Down Expand Up @@ -191,6 +192,8 @@ export function AuthProvider({
const bootSessionFor = useRef<string | null>(bootSession ? authUrl : null);
const [error, setError] = useState<Error | null>(null);
const [remediationRequired, setRemediationRequired] = useState<{ code: string; message: string } | null>(null);
// objectstack#29105 — a password sign-in waiting for its second factor.
const [twoFactorChallenge, setTwoFactorChallenge] = useState<TwoFactorChallenge | null>(null);

// Organization / workspace state
const [organizations, setOrganizations] = useState<AuthOrganization[]>([]);
Expand Down Expand Up @@ -393,8 +396,16 @@ export function AuthProvider({
setError(null);
try {
const result = await client.signIn({ email, password });
if (result.twoFactor) {
// Password accepted, no session yet: the account has two-factor
// sign-in on. The sign-in page asks for the code (objectstack#29105).
setTwoFactorChallenge(result.twoFactor);
return { twoFactorRequired: true };
}
setTwoFactorChallenge(null);
setUser(result.user);
setSession(result.session);
return { twoFactorRequired: false };
} catch (err) {
const authError = err instanceof Error ? err : new Error(String(err));
setError(authError);
Expand All @@ -406,6 +417,33 @@ export function AuthProvider({
[client],
);

const verifySignInTwoFactor = useCallback(
async (code: string, kind: SignInTwoFactorCodeKind) => {
setError(null);
try {
const result = await client.verifySignInTwoFactor(code, kind);
setTwoFactorChallenge(null);
setUser(result.user);
setSession(result.session);
} catch (err) {
const authError = err instanceof Error ? err : new Error(String(err));
// The server has dropped the pending sign-in: too many wrong codes, or
// its cookie expired. Another code can never succeed, so the challenge
// ends here and the user signs in with their password again.
const code = (authError as Error & { code?: string }).code;
if (code && TWO_FACTOR_CHALLENGE_ENDED_CODES.has(code)) setTwoFactorChallenge(null);
setError(authError);
throw authError;
}
},
[client],
);

const cancelTwoFactorChallenge = useCallback(() => {
setTwoFactorChallenge(null);
setError(null);
}, []);

const signUp = useCallback(
async (name: string, email: string, password: string, callbackURL?: string, captchaToken?: string) => {
setIsLoading(true);
Expand Down Expand Up @@ -445,6 +483,7 @@ export function AuthProvider({
setUser(null);
setSession(null);
setError(null);
setTwoFactorChallenge(null);
// The organization block is the previous principal's data too: the list
// is the workspaces THAT user belongs to (the switcher renders it), and
// a lingering `activeOrganization` would additionally suppress the
Expand Down Expand Up @@ -1108,6 +1147,9 @@ export function AuthProvider({
isPreviewMode,
previewMode: isPreviewMode ? previewMode : null,
signIn,
twoFactorChallenge,
verifySignInTwoFactor,
cancelTwoFactorChallenge,
signUp,
signOut,
refreshSession,
Expand Down Expand Up @@ -1155,7 +1197,7 @@ export function AuthProvider({
}),
[
user, session, isAuthenticated, isAuthEnabled, isLoading, error, isPreviewMode, previewMode,
signIn, signUp, signOut, refreshSession, updateUser, forgotPassword, sendVerificationEmail, resetPassword, changePassword, setInitialPassword, hasLocalPassword, getAuthConfig, signInWithProvider,
signIn, twoFactorChallenge, verifySignInTwoFactor, cancelTwoFactorChallenge, signUp, signOut, refreshSession, updateUser, forgotPassword, sendVerificationEmail, resetPassword, changePassword, setInitialPassword, hasLocalPassword, getAuthConfig, signInWithProvider,
sendPhoneOtp, signInWithPhoneOtp, signInWithPhonePassword, requestPhonePasswordReset, resetPasswordWithPhoneOtp,
remediationRequired, enrollTotp, verifyTotp,
organizations, activeOrganization, activeMember, isOrganizationsLoading, isMembershipResolved, switchOrganization, createOrganization, refreshOrganizations,
Expand Down
Loading
Loading