LibreChat/e2e/specs/mock/scenarios/two-factor-opt-in.spec.ts
Marco Beretta 76c25680ce
Some checks failed
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Vote Gate / Gate (push) Waiting to run
Codegraph E2E Votes / vote (shard 1/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 10/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 2/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 3/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 4/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 5/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 6/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 7/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 8/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 9/10) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/chat (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Has been cancelled
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Has been cancelled
🔐 fix: Retire Credentials by Their Committing Write and on Opt-In 2FA (#17504)
* fix: Retire Credentials by Their Committing Write and on Opt-In 2FA

Re-date password reset and enrollment cutoffs once the write that set them commits, so a credential minted while the write is in flight is retired. Opt-in 2FA confirmation now stamps twoFactorEnrolledAt and rotates the session like required enrollment. OpenID refresh ends a session established before a reset or enrollment instead of spending its IdP grant.

* fix: Bind Opt-In 2FA Rotation to the Caller's Refresh Session

Confirmation now requires the refresh session the request was issued with, rotates it in place and revokes only the others, so an access token on its own cannot trade enrollment for a long-lived session. The OpenID retirement check moves into the refresh recovery service and ends the session through the existing session-missing path, leaving the CJS controller unchanged.

* fix: Clear a Retired OpenID Session Against the User It Was Checked For

* refactor: Inject the Refresh Secret Into OpenID Recovery

* fix: Report a Reset Whose Cutoff Could Not Be Re-Dated

A failed re-stamp now propagates as RETIREMENT_RESTAMP_FAILED. The reset controller still revokes sessions and passkeys and answers CREDENTIAL_RETIREMENT_INCOMPLETE; the CLI re-stamps after its revocations and exits non-zero; enrollment revokes sessions before the re-stamp and mints nothing when it fails.

* fix: Re-Date the Reset Cutoff Only After the Link Is Consumed

The web reset re-stamps credentialsChangedAt in the controller once resetPassword has committed, consumed the token and sent the notice, so a failed re-stamp can no longer leave the link replayable. Revocations still run and the response reports CREDENTIAL_RETIREMENT_INCOMPLETE.

* fix: Retire Credentials on Every Exit Path After a Reset Commits

resetPasswordWithToken owns the post-commit steps: deleting the link and sending the notice no longer throw, and a link issued before the account's last credentialsChangedAt is refused, so it is spent even when its deletion fails. The reset write is conditioned on the cutoff it read, so one link commits once. The controller re-dates the cutoff and revokes sessions and passkeys whenever the password changed, and answers CREDENTIAL_RETIREMENT_INCOMPLETE if any of that fails.

* fix: Spend Undated Reset Links and Move the Reset Notice Into TypeScript

* fix: Tell the User When a Reset Could Not Sign Out Every Session

The reset page now recognizes CREDENTIAL_RETIREMENT_INCOMPLETE, shared from librechat-data-provider, and shows a localized warning that the new password is active with a sign-in action, instead of reporting the spent link as invalid.

* perf: Re-Date the Reset Cutoff From the Committed Write

The committed reset hands its credentialsChangedAt back through PasswordResetResult, so the controller re-stamps without a second user read.

* fix: Retire Every Superseded Credential Before Minting on 2FA Enrollment

Opt-in confirmation and setup finalization now revoke sessions, re-date twoFactorEnrolledAt and wait for the auth cache to drop the pre-enrollment document, running every step even when one fails. If any step fails they mint nothing and answer CREDENTIAL_RETIREMENT_INCOMPLETE; the settings dialog keeps 2FA on with a warning and the setup screen sends the user back to sign in with the new factor.

* test: Cover the Settings Warning When 2FA Enrollment Leaves Sessions Behind

* fix: Send the User Back to Sign In After an Incomplete Opt-In Enrollment

Enrollment retires the confirming tab's bearer, and an incomplete retirement mints no replacement, so the settings dialog now shows the backup codes and then signs out to the login page, whether the user completes setup or closes the dialog.

* test: Run the Retirement Warning Scenarios Against Their Own Signed-Out or Fresh Accounts

* test: Open the Sidebar Drawer Before the Account Menu on Phones

* fix: Report a Committed Opt-In Enrollment When Rotating the Session Fails

Once 2FA is promoted, a later failure in confirm2FA withdraws whatever session it may have minted and answers CREDENTIAL_RETIREMENT_INCOMPLETE, so the settings dialog hands over the backup codes and signs the user in again instead of reporting an invalid code.

* test: Prove an Incomplete Reset Does Not Resume the Retired Session

The Sign in action sends a browser with a live session through /login for about 150 ms before it lands in chat, so the signed-in version of the warning scenario only passed when the URL check caught that window. The warning scenario runs signed out, and a new scenario holds a pre-reset session and asserts its refresh is refused and the user stays on the login page.

* fix: Settle the Auth Cache After the CLI Reset's Final Cutoff Write

* test: Require the Login Form After Signing In From a Signed-Out Reset

* fix: Explain an Incomplete Session Retirement Before Restarting Sign-In After Required 2FA Setup

* perf: Start the Opt-In Enrollment User and Session Reads Together
2026-11-05 22:53:11 +01:00

276 lines
11 KiB
TypeScript

import { expect, test } from '@playwright/test';
import { createHmac, randomInt, randomUUID } from 'node:crypto';
import type { APIRequestContext, PlaywrightWorkerArgs } from '@playwright/test';
import { deleteUserByEmail, withMongo } from '../db';
import { NEW_CHAT_PATH } from '../helpers';
const PASSWORD = 'test1234!';
const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
function decodeBase32(secret: string): Buffer {
let bits = '';
for (const char of secret.replace(/=+$/, '').toUpperCase()) {
bits += BASE32.indexOf(char).toString(2).padStart(5, '0');
}
const bytes: number[] = [];
for (let i = 0; i + 8 <= bits.length; i += 8) {
bytes.push(parseInt(bits.slice(i, i + 8), 2));
}
return Buffer.from(bytes);
}
/** RFC 6238 with the parameters the server verifies: SHA-1, 30 second steps, six digits. */
function totp(secret: string): string {
const counter = Buffer.alloc(8);
counter.writeUInt32BE(Math.floor(Date.now() / 1000 / 30), 4);
const digest = createHmac('sha1', decodeBase32(secret)).update(counter).digest();
const offset = digest[digest.length - 1] & 0xf;
const code = (digest.readUInt32BE(offset) & 0x7fffffff) % 1_000_000;
return code.toString().padStart(6, '0');
}
type Session = { request: APIRequestContext; token: string };
async function newClient(
playwright: PlaywrightWorkerArgs['playwright'],
baseURL: string | undefined,
): Promise<APIRequestContext> {
// The harness trusts one proxy; isolate each client's login rate-limit budget.
return playwright.request.newContext({
baseURL,
extraHTTPHeaders: {
'X-Forwarded-For': `127.${randomInt(1, 255)}.${randomInt(1, 255)}.${randomInt(1, 255)}`,
},
});
}
async function signIn(request: APIRequestContext, email: string): Promise<Session> {
const login = await request.post('/api/auth/login', { data: { email, password: PASSWORD } });
expect(login.ok()).toBeTruthy();
const { token } = (await login.json()) as { token: string };
expect(token).toBeTruthy();
return { request, token };
}
const bearer = (token: string) => ({ Authorization: `Bearer ${token}` });
async function isAuthorized(request: APIRequestContext, token: string): Promise<boolean> {
const response = await request.get('/api/user', { headers: bearer(token) });
return response.ok();
}
async function refreshedToken(request: APIRequestContext): Promise<string | undefined> {
const response = await request.post('/api/auth/refresh');
if (!response.ok()) {
return undefined;
}
const body = (await response.json().catch(() => ({}))) as { token?: string };
return body.token;
}
/** Enables 2FA from account settings with `session` and returns the session confirmation hands back. */
async function optIn(session: Session): Promise<{ token: string; secret: string }> {
const enable = await session.request.post('/api/auth/2fa/enable', {
headers: bearer(session.token),
});
expect(enable.ok()).toBeTruthy();
const { otpauthUrl } = (await enable.json()) as { otpauthUrl: string };
const secret = new URL(otpauthUrl).searchParams.get('secret') ?? '';
expect(secret).toBeTruthy();
const confirm = await session.request.post('/api/auth/2fa/confirm', {
headers: bearer(session.token),
data: { token: totp(secret) },
});
expect(confirm.status()).toBe(200);
const body = (await confirm.json()) as { token: string; user: { twoFactorEnabled?: boolean } };
expect(body.token).toBeTruthy();
expect(body.user.twoFactorEnabled).toBe(true);
return { token: body.token, secret };
}
async function registerUser(request: APIRequestContext): Promise<string> {
const email = `opt-in-2fa-${randomUUID().slice(0, 8)}@example.com`;
const register = await request.post('/api/auth/register', {
data: { email, name: 'Opt-in 2FA', password: PASSWORD, confirm_password: PASSWORD },
});
expect(register.ok()).toBeTruthy();
return email;
}
test.describe('opt-in two-factor enrollment', () => {
test('confirming 2FA from settings ends every other session @scenario:optin-2fa-retires-prior-sessions', async ({
playwright,
baseURL,
}) => {
const confirming = await newClient(playwright, baseURL);
const other = await newClient(playwright, baseURL);
const email = await registerUser(confirming);
try {
const confirmingSession = await signIn(confirming, email);
const otherSession = await signIn(other, email);
expect(await isAuthorized(other, otherSession.token)).toBe(true);
const { token } = await optIn(confirmingSession);
expect(await isAuthorized(confirming, token)).toBe(true);
expect(await isAuthorized(confirming, confirmingSession.token)).toBe(false);
expect(await isAuthorized(other, otherSession.token)).toBe(false);
expect(await refreshedToken(other)).toBeUndefined();
const rotated = await refreshedToken(confirming);
expect(rotated).toBeTruthy();
expect(await isAuthorized(confirming, rotated as string)).toBe(true);
await withMongo(async (db) => {
const user = await db.collection('users').findOne({ email });
expect(user?.twoFactorEnabled).toBe(true);
expect(user?.twoFactorEnrolledAt).toBeInstanceOf(Date);
});
} finally {
await deleteUserByEmail(email);
await confirming.dispose();
await other.dispose();
}
});
test('re-enabling 2FA after disabling it ends the sessions opened in between @scenario:optin-2fa-reenable-retires-sessions', async ({
playwright,
baseURL,
}) => {
const confirming = await newClient(playwright, baseURL);
const other = await newClient(playwright, baseURL);
const email = await registerUser(confirming);
try {
const first = await optIn(await signIn(confirming, email));
const disable = await confirming.post('/api/auth/2fa/disable', {
headers: bearer(first.token),
data: { token: totp(first.secret) },
});
expect(disable.ok()).toBeTruthy();
const otherSession = await signIn(other, email);
expect(await isAuthorized(other, otherSession.token)).toBe(true);
const second = await optIn({ request: confirming, token: first.token });
expect(await isAuthorized(confirming, second.token)).toBe(true);
expect(await isAuthorized(other, otherSession.token)).toBe(false);
expect(await refreshedToken(other)).toBeUndefined();
} finally {
await deleteUserByEmail(email);
await confirming.dispose();
await other.dispose();
}
});
test('an access token without its refresh session cannot enroll or obtain a session @scenario:optin-2fa-requires-refresh-session', async ({
playwright,
baseURL,
}) => {
const owner = await newClient(playwright, baseURL);
const bearerOnly = await newClient(playwright, baseURL);
const email = await registerUser(owner);
try {
const ownerSession = await signIn(owner, email);
const enable = await bearerOnly.post('/api/auth/2fa/enable', {
headers: bearer(ownerSession.token),
});
expect(enable.ok()).toBeTruthy();
const { otpauthUrl } = (await enable.json()) as { otpauthUrl: string };
const secret = new URL(otpauthUrl).searchParams.get('secret') ?? '';
const confirm = await bearerOnly.post('/api/auth/2fa/confirm', {
headers: bearer(ownerSession.token),
data: { token: totp(secret) },
});
expect(confirm.status()).toBe(401);
expect(await confirm.text()).not.toContain('"token"');
expect(await isAuthorized(owner, ownerSession.token)).toBe(true);
expect(await refreshedToken(owner)).toBeTruthy();
await withMongo(async (db) => {
const user = await db.collection('users').findOne({ email });
expect(user?.twoFactorEnabled).not.toBe(true);
expect(user?.twoFactorEnrolledAt).toBeFalsy();
});
} finally {
await deleteUserByEmail(email);
await owner.dispose();
await bearerOnly.dispose();
}
});
test.describe('with its own signed-in account', () => {
test.use({ storageState: { cookies: [], origins: [] } });
test('settings keeps 2FA on, hands over the backup codes and signs in again when other sessions could not all be signed out @scenario:optin-2fa-incomplete-retirement-warns', async ({
page,
}) => {
test.setTimeout(60000);
await page.context().setExtraHTTPHeaders({
'X-Forwarded-For': `127.${randomInt(1, 255)}.${randomInt(1, 255)}.${randomInt(1, 255)}`,
});
const email = await registerUser(page.request);
try {
await signIn(page.request, email);
await page.route('**/api/auth/2fa/confirm', (route) =>
route.fulfill({
status: 500,
contentType: 'application/json',
body: JSON.stringify({ code: 'CREDENTIAL_RETIREMENT_INCOMPLETE' }),
}),
);
await page.goto(NEW_CHAT_PATH);
/** On a phone the account menu lives in the sidebar drawer, which starts closed. */
if ((page.viewportSize()?.width ?? 1280) <= 768) {
await page
.getByRole('main')
.getByRole('button', { name: 'Open sidebar', exact: true })
.click();
await expect(page.locator('#mobile-drawer')).not.toHaveAttribute('inert', /.*/);
}
await page.getByTestId('nav-user').click();
await page.getByRole('menuitem', { name: 'Settings' }).click();
await page.getByRole('tab', { name: 'Account' }).click();
await page.getByRole('button', { name: 'Enable 2FA' }).click();
const enabling = page.waitForResponse((response) =>
response.url().endsWith('/api/auth/2fa/enable'),
);
await page.getByRole('button', { name: 'Generate QR Code' }).click();
const enabled = await enabling;
expect(enabled.status()).toBe(200);
const { otpauthUrl } = (await enabled.json()) as { otpauthUrl: string };
const secret = new URL(otpauthUrl).searchParams.get('secret') ?? '';
expect(secret).toBeTruthy();
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.getByRole('textbox').last().fill(totp(secret));
const confirming = page.waitForResponse((response) =>
response.url().endsWith('/api/auth/2fa/confirm'),
);
await page.getByRole('button', { name: 'Verify', exact: true }).click();
expect((await confirming).status()).toBe(500);
await expect(
page
.getByText(
'Two-factor authentication is on, but some other sessions may stay signed in',
{ exact: false },
)
.first(),
).toBeVisible();
await expect(
page.getByText('Invalid two-factor authentication code', { exact: true }),
).toHaveCount(0);
const download = page.waitForEvent('download');
await page.getByRole('button', { name: 'Download Backup Codes' }).click();
await download;
await page.getByRole('button', { name: 'Complete Setup' }).click();
await expect(page).toHaveURL(/\/login/);
} finally {
await deleteUserByEmail(email);
}
});
});
});