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
13 changes: 7 additions & 6 deletions docs/de/platform/admin/two-factor-authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Ein Passkey erfüllt Tales Zwei-Faktor-Richtlinie auch ohne eingerichteten Authe

## Einen Authenticator einrichten

1. Öffne **Einstellungen > Konto**, gehe zu **Sicherheit** und wähle **Zwei-Faktor aktivieren**.
1. Öffne **Einstellungen > Konto**, gehe zu **Zwei-Faktor-Authentifizierung** und wähle **Zwei-Faktor aktivieren**.
2. Gib dein aktuelles Tale-Passwort ein und wähle **Bestätigen**.
3. Scanne den QR-Code mit deiner Authenticator-App. Falls das nicht geht, gib den angezeigten Einrichtungsschlüssel manuell in der App ein.
4. Gib den aktuellen sechsstelligen Code unter **Bestätigungscode** ein und wähle **Prüfen und aktivieren**.
Expand All @@ -31,10 +31,11 @@ Bewahre Backup-Codes so auf, dass du sie auch ohne dein Anmeldegerät erreichst,

## Einen Passkey hinzufügen

1. Wähle unter **Einstellungen > Konto > Sicherheit** die Aktion **Passkey hinzufügen**.
2. Trage unter **Passkey-Name** einen Namen ein, den du wiedererkennst, etwa `Arbeitslaptop`.
3. Lass **Authenticator-Typ** auf **Beliebig (empfohlen)**, damit der Browser alle verfügbaren Möglichkeiten anbietet. Alternativ wählst du den eingebauten Authenticator oder einen Sicherheitsschlüssel beziehungsweise ein Smartphone.
4. Wähle **Passkey hinzufügen** und bestätige die Browserabfrage.
1. Öffne **Einstellungen > Konto**, gehe zu **Passkeys** und wähle **Passkey hinzufügen**.
2. Liegt deine Anmeldung mehr als einen Tag zurück, fragt Tale zuerst nach deinem Passwort. Gib es unter **Passwort** ein und wähle **Bestätigen**. Ein falsches Passwort zählt wie eine fehlgeschlagene Anmeldung zur vorübergehenden Sperre.
3. Trage unter **Passkey-Name** einen Namen ein, den du wiedererkennst, etwa `Arbeitslaptop`.
4. Lass **Authenticator-Typ** auf **Beliebig (empfohlen)**, damit der Browser alle verfügbaren Möglichkeiten anbietet. Alternativ wählst du den eingebauten Authenticator oder einen Sicherheitsschlüssel beziehungsweise ein Smartphone.
5. Wähle **Passkey hinzufügen** und bestätige die Browserabfrage.

Der Passkey erscheint in deiner Kontoliste. Wähle auf der Anmeldeseite **Mit einem Passkey anmelden**. Nach einer Passwortanmeldung kannst du auf der Bestätigungsseite auch **Stattdessen einen Passkey verwenden** wählen.

Expand Down Expand Up @@ -64,7 +65,7 @@ Admins richten die Richtlinie unter **Einstellungen > Richtlinien > Sicherheit**
| **Übergangsfrist (Tage)** | Zeit für die Einrichtung ab der ersten Anmeldung des Mitglieds unter dieser Richtlinie. Null verlangt sie sofort. |
| **Nur-SSO-Benutzer ausnehmen** | Mitglieder ohne Tale-Passwort verlassen sich auf die Anmeldung ihres Identitätsanbieters. |

Während der Übergangsfrist sehen Mitglieder eine Erinnerung. Danach sperrt Tale den Organisationszugang, bis sie eine Methode einrichten. Deinen eigenen Authenticator zu deaktivieren, hebt die Richtlinie nicht auf.
Während der Übergangsfrist sehen Mitglieder eine Erinnerung. Danach sperrt Tale den Organisationszugang, bis sie eine Methode einrichten: Die Einrichtungsseite fragt nach ihrem Passwort, um einen Authenticator einzurichten, oder bietet **Stattdessen einen Passkey registrieren** an. Wer schon länger als einen Tag angemeldet ist, bestätigt vor der Passkey-Abfrage sein Passwort. Wer sich nur per SSO anmeldet, wählt zuerst **Erneut anmelden**. Deinen eigenen Authenticator zu deaktivieren, hebt die Richtlinie nicht auf.

## Einem ausgesperrten Mitglied helfen

Expand Down
13 changes: 7 additions & 6 deletions docs/en/platform/admin/two-factor-authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ A passkey satisfies Tale's two-factor policy even if you have never set up an au

## Set up an authenticator

1. Open **Settings > Account**, find **Security**, and select **Enable two-factor**.
1. Open **Settings > Account**, find **Two-factor authentication**, and select **Enable two-factor**.
2. Enter your current Tale password and select **Confirm**.
3. Scan the QR code with your authenticator app. If scanning is unavailable, enter the displayed setup secret manually in the app.
4. Enter its current six-digit code in **Verification code**, then select **Verify and enable**.
Expand All @@ -31,10 +31,11 @@ Keep recovery codes somewhere you can reach without the device you use to sign i

## Add a passkey

1. Under **Settings > Account > Security**, select **Add a passkey**.
2. Give **Passkey name** a recognizable name, such as `Work laptop`.
3. Leave **Authenticator type** on **Any (recommended)** to see the browser's available options, or choose the built-in device authenticator or a security key/phone.
4. Select **Add a passkey** and complete the browser prompt.
1. Open **Settings > Account**, find **Passkeys**, and select **Add a passkey**.
2. If you signed in more than a day ago, Tale first asks for your password. Enter it in **Password** and select **Confirm**. A wrong password counts toward the same temporary lock as a failed sign-in.
3. Give **Passkey name** a recognizable name, such as `Work laptop`.
4. Leave **Authenticator type** on **Any (recommended)** to see the browser's available options, or choose the built-in device authenticator or a security key/phone.
5. Select **Add a passkey** and complete the browser prompt.

The passkey appears in your account's list. On the sign-in page, choose **Sign in with a passkey**. After a password sign-in, **Use a passkey instead** is also available on the verification screen.

Expand Down Expand Up @@ -64,7 +65,7 @@ Admins configure the policy in **Settings > Governance > Security**. Arrange a r
| **Grace period (days)** | Time to enroll, counted from the member's first sign-in under the policy. Zero requires enrollment immediately. |
| **Exempt SSO-only users** | Lets members without a Tale password rely on their identity provider's authentication. |

During the grace period, members see a reminder. After it expires, Tale blocks organization access until they enroll. Disabling your personal authenticator does not exempt you from this policy.
During the grace period, members see a reminder. After it expires, Tale blocks organization access until they enroll: the enrollment page asks for their password to set up an authenticator, or offers **Register a passkey instead**. A member who has been signed in for more than a day confirms their password before the passkey prompt; one who signs in only through SSO selects **Sign in again** first. Disabling your personal authenticator does not exempt you from this policy.

## Help a locked-out member

Expand Down
13 changes: 7 additions & 6 deletions docs/fr/platform/admin/two-factor-authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Un passkey satisfait la règle de double facteur de Tale, même sans application

## Configurer une application d’authentification

1. Ouvre **Paramètres > Compte**, repère **Sécurité** et choisis **Activer le double facteur**.
1. Ouvre **Paramètres > Compte**, repère **Authentification à double facteur** et choisis **Activer le double facteur**.
2. Saisis ton mot de passe Tale actuel et choisis **Confirmer**.
3. Scanne le code QR avec ton application d’authentification. Si tu ne peux pas le scanner, saisis manuellement le secret de configuration affiché dans l’application.
4. Saisis son code à six chiffres actuel dans **Code de vérification**, puis choisis **Vérifier et activer**.
Expand All @@ -31,10 +31,11 @@ Conserve tes codes de secours dans un endroit accessible sans ton appareil de co

## Ajouter un passkey

1. Dans **Paramètres > Compte > Sécurité**, choisis **Ajouter un passkey**.
2. Dans **Nom du passkey**, indique un nom reconnaissable, par exemple `Portable professionnel`.
3. Garde **Type d'authentificateur** sur **Indifférent (recommandé)** pour voir les possibilités du navigateur, ou choisis l’authentificateur intégré à l’appareil ou une clé de sécurité/un téléphone.
4. Choisis **Ajouter un passkey** et termine la procédure du navigateur.
1. Ouvre **Paramètres > Compte**, repère **Passkeys** et choisis **Ajouter un passkey**.
2. Si ta connexion remonte à plus d’un jour, Tale te demande d’abord ton mot de passe. Saisis-le dans **Mot de passe** et choisis **Confirmer**. Un mot de passe erroné compte pour le verrouillage temporaire, comme un échec de connexion.
3. Dans **Nom du passkey**, indique un nom reconnaissable, par exemple `Portable professionnel`.
4. Garde **Type d'authentificateur** sur **Indifférent (recommandé)** pour voir les possibilités du navigateur, ou choisis l’authentificateur intégré à l’appareil ou une clé de sécurité/un téléphone.
5. Choisis **Ajouter un passkey** et termine la procédure du navigateur.

Le passkey apparaît dans la liste de ton compte. Sur la page de connexion, choisis **Se connecter avec un passkey**. Après une connexion par mot de passe, tu peux aussi choisir **Utiliser un passkey à la place** sur l’écran de vérification.

Expand Down Expand Up @@ -64,7 +65,7 @@ Les admins configurent la règle dans **Paramètres > Gouvernance > Sécurité**
| **Période de grâce (jours)** | Délai de configuration à partir de la première connexion du membre sous cette règle. Zéro impose une configuration immédiate. |
| **Exempter les utilisateurs SSO uniquement** | Les membres sans mot de passe Tale s’appuient sur l’authentification de leur fournisseur d’identité. |

Pendant ce délai, les membres voient un rappel. Une fois le délai écoulé, Tale bloque l’accès à l’organisation jusqu’à la configuration. Désactiver ton application d’authentification personnelle ne te dispense pas de cette règle.
Pendant ce délai, les membres voient un rappel. Une fois le délai écoulé, Tale bloque l’accès à l’organisation jusqu’à la configuration : la page de configuration demande leur mot de passe pour configurer une application d’authentification, ou propose **Enregistrer un passkey à la place**. Un membre connecté depuis plus d’un jour confirme son mot de passe avant la demande du navigateur ; un membre qui se connecte uniquement par SSO choisit d’abord **Se reconnecter**. Désactiver ton application d’authentification personnelle ne te dispense pas de cette règle.

## Aider un membre qui a perdu son accès

Expand Down
32 changes: 32 additions & 0 deletions services/platform/app/features/auth/hooks/use-lockout-message.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { useCallback } from 'react';

import { useT } from '@/lib/i18n/client';

/**
* The sentence for a password check refused because the account is locked
* (429), with the wait rounded to the largest whole unit. Shared by every
* door that counts against the lockout: the log-in form and the password
* confirmation before adding a passkey.
*/
export function useLockoutMessage(): (
retryAfterSec: number | undefined,
) => string {
const { t } = useT('auth');
return useCallback(
(retryAfterSec: number | undefined): string => {
if (!retryAfterSec || retryAfterSec <= 0) {
return t('login.accountLockedGeneric');
}
if (retryAfterSec < 60) {
return t('login.accountLockedSeconds', { seconds: retryAfterSec });
}
const minutes = Math.ceil(retryAfterSec / 60);
if (minutes < 60) {
return t('login.accountLockedMinutes', { minutes });
}
const hours = Math.ceil(retryAfterSec / 3600);
return t('login.accountLockedHours', { hours });
},
[t],
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,255 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { checkAccessibility } from '@/tests/utils/a11y';
import { render, screen, waitFor } from '@/tests/utils/render';

// Registering a passkey needs a session signed in within a day. Someone who
// stayed signed in longer — everyone the post-grace 2FA wall catches — used
// to meet a bare "Session is not fresh" with no way forward. The dialog now
// asks for the password first and only then for the passkey.

const HOUR = 60 * 60 * 1000;

const h = vi.hoisted(() => ({
session: { createdAt: new Date() as Date | undefined },
status: { value: { authenticated: true, hasCredential: true } as unknown },
addPasskey: vi.fn(),
reauthenticate: vi.fn(),
signOut: vi.fn(),
redirectToLogIn: vi.fn(),
}));

vi.mock('@tanstack/react-query', async (importOriginal) => ({
...(await importOriginal<typeof import('@tanstack/react-query')>()),
// The session read (['auth', 'session']) and the 2FA status
// (['backend', …]) share this hook; switch on the key.
useQuery: (options: { queryKey?: unknown[] }) =>
options.queryKey?.[0] === 'auth'
? {
data: {
data:
h.session.createdAt === undefined
? null
: { session: { createdAt: h.session.createdAt } },
},
}
: { data: h.status.value },
useQueryClient: () => ({
invalidateQueries: vi.fn().mockResolvedValue(undefined),
}),
}));

vi.mock('@/lib/auth-client', () => ({
authClient: {
passkey: { addPasskey: h.addPasskey },
// The password confirmation is the one `$fetch` call
// (`POST /api/auth/reauthenticate`).
$fetch: h.reauthenticate,
},
}));

vi.mock('@/app/hooks/use-session-user', () => ({
useAuth: () => ({ signOut: h.signOut }),
}));

vi.mock('@/app/lib/auth/log-in-redirect', () => ({
redirectToLogIn: h.redirectToLogIn,
}));

// FormDialog resolves the org id from router params for its unsaved-changes
// guard; there is no router in a component test.
vi.mock('@/app/hooks/use-organization-id', () => ({
useOrganizationId: () => 'org-1',
}));

import { PasskeyRegisterDialog } from './passkey-register-dialog';

const CONFIRM_DESCRIPTION =
/you signed in a while ago\. confirm your password to add a passkey/i;

function renderDialog() {
const onRegistered = vi.fn();
const onOpenChange = vi.fn();
const rendered = render(
<PasskeyRegisterDialog
open
onOpenChange={onOpenChange}
onRegistered={onRegistered}
/>,
);
return { ...rendered, onRegistered, onOpenChange };
}

describe('PasskeyRegisterDialog', () => {
beforeEach(() => {
vi.clearAllMocks();
h.session.createdAt = new Date(Date.now() - HOUR);
h.status.value = { authenticated: true, hasCredential: true };
h.addPasskey.mockResolvedValue({ data: { id: 'pk-1' }, error: null });
h.reauthenticate.mockResolvedValue({ data: { status: true }, error: null });
});

it('goes straight to the passkey on a session signed in within the day', async () => {
const { user, onRegistered } = renderDialog();

const name = screen.getByLabelText('Passkey name');
await user.clear(name);
await user.type(name, 'Work laptop');
await user.click(screen.getByRole('button', { name: 'Add a passkey' }));

await waitFor(() =>
expect(h.addPasskey).toHaveBeenCalledWith({ name: 'Work laptop' }),
);
expect(onRegistered).toHaveBeenCalledTimes(1);
expect(h.reauthenticate).not.toHaveBeenCalled();
expect(screen.queryByLabelText('Password')).not.toBeInTheDocument();
});

it('asks for the password first on a session past the fresh window, then registers', async () => {
h.session.createdAt = new Date(Date.now() - 25 * HOUR);
const { user, onRegistered } = renderDialog();

expect(screen.getByText(CONFIRM_DESCRIPTION)).toBeInTheDocument();
expect(screen.queryByLabelText('Passkey name')).not.toBeInTheDocument();
const password = screen.getByLabelText('Password');
expect(password).toHaveFocus();

await user.type(password, 'correct horse');
await user.click(screen.getByRole('button', { name: 'Confirm' }));

await waitFor(() =>
expect(h.reauthenticate).toHaveBeenCalledWith('/reauthenticate', {
method: 'POST',
body: { password: 'correct horse' },
}),
);
const name = await screen.findByLabelText('Passkey name');
expect(name).toHaveFocus();
expect(h.addPasskey).not.toHaveBeenCalled();

await user.clear(name);
await user.type(name, 'Work laptop');
await user.click(screen.getByRole('button', { name: 'Add a passkey' }));

await waitFor(() =>
expect(h.addPasskey).toHaveBeenCalledWith({ name: 'Work laptop' }),
);
expect(onRegistered).toHaveBeenCalledTimes(1);
});

it('asks for the password when too little of the fresh window is left to finish', async () => {
h.session.createdAt = new Date(Date.now() - (24 * HOUR - 2 * 60 * 1000));
renderDialog();

expect(screen.getByText(CONFIRM_DESCRIPTION)).toBeInTheDocument();
});

it('keeps the person on the password step when it is wrong', async () => {
h.session.createdAt = new Date(Date.now() - 25 * HOUR);
h.reauthenticate.mockResolvedValue({
data: null,
error: {
status: 400,
statusText: 'BAD_REQUEST',
code: 'INVALID_PASSWORD',
},
});
const { user } = renderDialog();

await user.type(screen.getByLabelText('Password'), 'wrong');
await user.click(screen.getByRole('button', { name: 'Confirm' }));

expect(
await screen.findByText(
'Wrong password. Repeated failed attempts temporarily lock your account.',
),
).toBeInTheDocument();
expect(screen.queryByLabelText('Passkey name')).not.toBeInTheDocument();
expect(h.addPasskey).not.toHaveBeenCalled();
});

it('says how long a locked account waits', async () => {
h.session.createdAt = new Date(Date.now() - 25 * HOUR);
h.reauthenticate.mockResolvedValue({
data: null,
error: {
status: 429,
statusText: 'TOO_MANY_REQUESTS',
message: 'Invalid credentials',
retryAfter: 120,
},
});
const { user } = renderDialog();

await user.type(screen.getByLabelText('Password'), 'anything');
await user.click(screen.getByRole('button', { name: 'Confirm' }));

expect(
await screen.findByText(
'Account temporarily locked. Try again in 2 minutes, or contact an administrator.',
),
).toBeInTheDocument();
});

it('comes back to the password step when the server refuses the session as not fresh', async () => {
// The browser's clock says fresh; the server's word is final.
const { user } = renderDialog();
h.addPasskey.mockResolvedValueOnce({
data: null,
error: {
code: 'SESSION_NOT_FRESH',
message: 'Session is not fresh',
status: 403,
statusText: 'FORBIDDEN',
},
});

const name = screen.getByLabelText('Passkey name');
await user.clear(name);
await user.type(name, 'Work laptop');
await user.click(screen.getByRole('button', { name: 'Add a passkey' }));

expect(await screen.findByText(CONFIRM_DESCRIPTION)).toBeInTheDocument();
expect(screen.queryByText('Session is not fresh')).not.toBeInTheDocument();

await user.type(screen.getByLabelText('Password'), 'correct horse');
await user.click(screen.getByRole('button', { name: 'Confirm' }));

// The name typed before the detour survives it.
expect(await screen.findByLabelText('Passkey name')).toHaveValue(
'Work laptop',
);
await user.click(screen.getByRole('button', { name: 'Add a passkey' }));
await waitFor(() => expect(h.addPasskey).toHaveBeenCalledTimes(2));
expect(h.addPasskey).toHaveBeenLastCalledWith({ name: 'Work laptop' });
});

it('offers to sign in again to an account without a password', async () => {
h.session.createdAt = new Date(Date.now() - 25 * HOUR);
h.status.value = { authenticated: true, hasCredential: false };
h.signOut.mockResolvedValue(undefined);
const { user } = renderDialog();

expect(
screen.getByText(
/you signed in a while ago\. sign in again, then add your passkey/i,
),
).toBeInTheDocument();
expect(screen.queryByLabelText('Password')).not.toBeInTheDocument();

await user.click(screen.getByRole('button', { name: 'Sign in again' }));

await waitFor(() => expect(h.redirectToLogIn).toHaveBeenCalledTimes(1));
expect(h.signOut).toHaveBeenCalledTimes(1);
expect(h.reauthenticate).not.toHaveBeenCalled();
});

it('passes an axe audit on the password step', async () => {
h.session.createdAt = new Date(Date.now() - 25 * HOUR);
const { baseElement } = renderDialog();

await screen.findByLabelText('Password');
await checkAccessibility(baseElement);
});
});
Loading