Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add invite code support to web app registration flow (#2143)

Leendert de Borstd7e6f88b7357
diff --git a/apps/web/src/components/auth/setup/SetupSteps.tsx b/apps/web/src/components/auth/setup/SetupSteps.tsx
index 2549fe086..cb81f3d6c 100644
--- a/apps/web/src/components/auth/setup/SetupSteps.tsx
+++ b/apps/web/src/components/auth/setup/SetupSteps.tsx
@@ -73,7 +73,7 @@ export const TermsAndConditionsStep: React.FC<{ agreedToTerms: boolean; onAgreed
/**
* Step 2: pick a username.
*/
-export const UsernameStep: React.FC<{ defaultUsername: string; onUsernameChange: (username: string) => void }> = ({ defaultUsername, onUsernameChange }) => {
+export const UsernameStep: React.FC<{ defaultUsername: string; inviteCode?: string; onUsernameChange: (username: string) => void }> = ({ defaultUsername, inviteCode, onUsernameChange }) => {
const { t } = useTranslation();
const webApi = useWebApi();
const isLoading = useStepLoading();
@@ -95,7 +95,7 @@ export const UsernameStep: React.FC<{ defaultUsername: string; onUsernameChange:
return;
}
try {
- await webApi.post<{ username: string }, unknown>('Auth/validate-username', { username: value }, false);
+ await webApi.post<{ username: string; inviteCode?: string }, unknown>('Auth/validate-username', { username: value, inviteCode }, false);
setIsValid(true);
setErrorMessage('');
onUsernameChange(value);
@@ -275,7 +275,7 @@ export const PasswordStep: React.FC<{ onPasswordChange: (password: string) => vo
/**
* Step 4: create the account.
*/
-export const CreatingStep: React.FC<{ username: string; password: string; onDone: () => void }> = ({ username, password, onDone }) => {
+export const CreatingStep: React.FC<{ username: string; password: string; inviteCode?: string; onDone: () => void }> = ({ username, password, inviteCode, onDone }) => {
const { t } = useTranslation();
const auth = useAuth();
const webApi = useWebApi();
@@ -294,7 +294,7 @@ export const CreatingStep: React.FC<{ username: string; password: string; onDone
*/
const completeSetup = async (): Promise<void> => {
try {
- await RegistrationService.register(webApi, username, password, auth.setAuthTokens);
+ await RegistrationService.register(webApi, username, password, auth.setAuthTokens, inviteCode);
onDone();
} catch (error) {
console.error('Registration failed:', error);
@@ -303,7 +303,7 @@ export const CreatingStep: React.FC<{ username: string; password: string; onDone
}
};
void completeSetup();
- }, [auth.setAuthTokens, notifications, onDone, password, t, username, webApi]);
+ }, [auth.setAuthTokens, inviteCode, notifications, onDone, password, t, username, webApi]);
return (
<div className="w-full mx-auto">
diff --git a/apps/web/src/pages/auth/Setup.tsx b/apps/web/src/pages/auth/Setup.tsx
index 9da6a0991..c8ebfd2c0 100644
--- a/apps/web/src/pages/auth/Setup.tsx
+++ b/apps/web/src/pages/auth/Setup.tsx
@@ -1,11 +1,16 @@
+import { apiErrorMessage } from '@aliasvault/client/api/errors/ApiErrorMessage';
+import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
import React, { useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { Link, useNavigate, useSearchParams } from 'react-router-dom';
+import AlertMessageError from '@/components/alerts/AlertMessageError';
import LanguageSwitcher from '@/components/auth/LanguageSwitcher';
+import Logo from '@/components/auth/Logo';
import { CreatingStep, PasswordStep, TermsAndConditionsStep, UsernameStep } from '@/components/auth/setup/SetupSteps';
import { ButtonLabel } from '@/components/shared/Button';
import { getAppConfig } from '@/config/AppConfig';
+import { useWebApi } from '@/context/WebApiContext';
import { usePageTitle } from '@/hooks/usePageTitle';
/** The wizard steps, in order. */
@@ -13,25 +18,44 @@ const STEPS = ['terms', 'username', 'password', 'creating'] as const;
type SetupStep = typeof STEPS[number];
/**
- * The create vault wizard: terms, username, password, then registration.
+ * The create vault wizard: terms, username, password, then registration. When public registration is disabled, the wizard
+ * only opens from a valid admin invite link (`?invite=<code>`).
*/
const Setup: React.FC = () => {
const { t } = useTranslation();
const navigate = useNavigate();
-
+ const webApi = useWebApi();
+ const [searchParams] = useSearchParams();
+ const requiresInvite = !getAppConfig().publicRegistrationEnabled;
+ const inviteCode = requiresInvite ? (searchParams.get('invite') ?? '').trim() : '';
+
usePageTitle(t('auth.setup.setupStepTitle'));
const [step, setStep] = useState<SetupStep>('terms');
+ const [isCheckingInvite, setIsCheckingInvite] = useState(requiresInvite && inviteCode.length > 0);
+ const [isInviteRejected, setIsInviteRejected] = useState(false);
+ const [inviteError, setInviteError] = useState('');
const [agreedToTerms, setAgreedToTerms] = useState(false);
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
+ // Check the invite link up front, so an invalid or used link fails before the user fills in the wizard.
useEffect(() => {
- if (!getAppConfig().publicRegistrationEnabled) {
- navigate('/user/login', { replace: true });
+ if (!requiresInvite || inviteCode.length === 0) {
+ return;
}
- }, [navigate]);
+ webApi.post<{ inviteCode: string }, unknown>('Auth/validate-invite-code', { inviteCode }, false)
+ .catch((error: unknown) => {
+ if (apiErrorCodeOf(error) === 'INVITE_CODE_INVALID') {
+ setIsInviteRejected(true);
+ } else {
+ setInviteError(apiErrorMessage(error, t, t('auth.setup.usernameStep.serverCommunicationError')));
+ }
+ })
+ .finally(() => setIsCheckingInvite(false));
+ }, [inviteCode, requiresInvite, t, webApi]);
+ const isBlocked = isCheckingInvite || inviteError.length > 0;
const isNextEnabled = step === 'terms' ? agreedToTerms : step === 'username' ? username.trim().length > 0 : step === 'password' ? password.trim().length > 0 : false;
const stepIndex = STEPS.indexOf(step);
const progressPercentage = Math.floor(stepIndex * 100 / (STEPS.length - 1));
@@ -70,6 +94,19 @@ const Setup: React.FC = () => {
navigate('/', { replace: true });
}, [navigate]);
+ if (requiresInvite && (inviteCode.length === 0 || isInviteRejected)) {
+ return (
+ <div className="flex flex-col items-center justify-center px-6 pt-8 pb-8 mx-auto md:h-screen relative">
+ <Logo />
+ <div className="w-full max-w-xl p-6 sm:p-8 bg-white rounded-lg shadow dark:bg-gray-800">
+ <h2 className="mb-3 text-xl font-semibold text-gray-900 dark:text-white">{t('auth.setup.registrationDisabledTitle')}</h2>
+ <p className="mb-6 text-gray-500 dark:text-gray-400">{isInviteRejected ? t('apiErrors.INVITE_CODE_INVALID') : t('auth.setup.registrationDisabledMessage')}</p>
+ <Link to="/" className="text-primary-700 hover:underline dark:text-primary-500">{t('app.notFound.goHome')}</Link>
+ </div>
+ </div>
+ );
+ }
+
return (
<div className="min-h-screen bg-gray-100 dark:bg-gray-900 flex flex-col lg:items-center lg:justify-center">
<div className="absolute top-4 right-4 z-10 mt-16 lg:mt-0 hidden lg:block">
@@ -80,7 +117,7 @@ const Setup: React.FC = () => {
<div className="flex-grow p-6 pt-4 lg:pt-6 pb-28 lg:pb-4">
<div className="flex justify-between items-center mb-4">
<div>
- <button type="button" onClick={goBack} className={`text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200 ${step === 'terms' ? 'invisible' : ''}`}>
+ <button type="button" onClick={goBack} className={`text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200 ${stepIndex === 0 ? 'invisible' : ''}`}>
<svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
</svg>
@@ -105,10 +142,16 @@ const Setup: React.FC = () => {
e.preventDefault();
goNext();
}}>
- {step === 'terms' && <TermsAndConditionsStep agreedToTerms={agreedToTerms} onAgreedToTermsChange={setAgreedToTerms} />}
- {step === 'username' && <UsernameStep defaultUsername={username} onUsernameChange={setUsername} />}
+ {isCheckingInvite && (
+ <div className="flex justify-center items-center mt-10">
+ <div className="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-primary-500"></div>
+ </div>
+ )}
+ {inviteError.length > 0 && <AlertMessageError message={inviteError} />}
+ {!isBlocked && step === 'terms' && <TermsAndConditionsStep agreedToTerms={agreedToTerms} onAgreedToTermsChange={setAgreedToTerms} />}
+ {step === 'username' && <UsernameStep defaultUsername={username} inviteCode={inviteCode || undefined} onUsernameChange={setUsername} />}
{step === 'password' && <PasswordStep onPasswordChange={setPassword} />}
- {step === 'creating' && <CreatingStep username={username} password={password} onDone={onRegistered} />}
+ {step === 'creating' && <CreatingStep username={username} password={password} inviteCode={inviteCode || undefined} onDone={onRegistered} />}
<button type="submit" className="hidden" />
</form>
</div>
@@ -117,7 +160,7 @@ const Setup: React.FC = () => {
<button type="button" onClick={goNext} className="w-full py-3 px-4 bg-green-600 hover:bg-green-700 text-white font-semibold rounded-lg transition duration-300 ease-in-out">
{t('auth.setup.createAccountButton')}
</button>
- ) : step !== 'creating' && (
+ ) : step !== 'creating' && !isBlocked && (
<button type="button" onClick={goNext} disabled={!isNextEnabled} className={`w-full py-3 px-4 bg-primary-600 hover:bg-primary-700 text-white font-semibold rounded-lg transition duration-300 ease-in-out ${isNextEnabled ? '' : 'opacity-50 cursor-not-allowed'}`}>
<ButtonLabel arrow="forward">{t('common.continue')}</ButtonLabel>
</button>
diff --git a/apps/web/src/services/RegistrationService.ts b/apps/web/src/services/RegistrationService.ts
index e364856b6..17c976f0c 100644
--- a/apps/web/src/services/RegistrationService.ts
+++ b/apps/web/src/services/RegistrationService.ts
@@ -13,10 +13,11 @@ export const RegistrationService = {
/**
* Register an account.
* @param setAuthTokens - stores the username and tokens (the app context's setter, so the UI state follows)
+ * @param inviteCode - the registration invite code, required when public registration is disabled
* @throws ApiRequestError with the server's error code when the server refuses the registration
*/
- async register(webApi: WebApiService, username: string, password: string, setAuthTokens: (username: string, accessToken: string, refreshToken: string) => Promise<void>): Promise<void> {
- const registered = await new SrpLoginService(webApi).register(username, password);
+ async register(webApi: WebApiService, username: string, password: string, setAuthTokens: (username: string, accessToken: string, refreshToken: string) => Promise<void>, inviteCode?: string): Promise<void> {
+ const registered = await new SrpLoginService(webApi).register(username, password, inviteCode);
await setAuthTokens(registered.username, registered.token.token, registered.token.refreshToken);
await VaultKeyService.cacheVaultKeyBlobs({ type: UnlockMethodType.Password, ...registered.keys.accountKeys, ...registered.derivationParams });
diff --git a/core/i18n/locales/en.json b/core/i18n/locales/en.json
index 60b0ac995..fa1a53a49 100644
--- a/core/i18n/locales/en.json
+++ b/core/i18n/locales/en.json
@@ -9,6 +9,7 @@
"INVALID_AUTHENTICATOR_CODE": "Invalid authenticator code. Please try again.",
"INVALID_RECOVERY_CODE": "Invalid recovery code. Please try again.",
"INVALID_REFRESH_TOKEN": "Invalid refresh token.",
+ "INVITE_CODE_INVALID": "This invite link is invalid, has expired or has already been used. Please ask the administrator for a new one.",
"PASSWORD_MISMATCH": "The provided password does not match your current password.",
"PENDING_MIGRATIONS": "There are pending migrations. Please run 'dotnet ef database update' to apply them.",
"PUBLIC_REGISTRATION_DISABLED": "New account registration is currently disabled on this server. Please contact the administrator.",
@@ -161,6 +162,8 @@
"welcomeMessage": "Great! Now, let's set up your master password for AliasVault."
},
"passwordStepTitle": "Set Password",
+ "registrationDisabledMessage": "New accounts can only be created with an invite link. Ask the server administrator for an invite.",
+ "registrationDisabledTitle": "User registration is disabled",
"setupStepTitle": "Setup",
"termsAndConditionsStepTitle": "Using AliasVault",
"termsStep": {