Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
import { AppErrorCode, getAppErrorCode, getErrorTranslationKey } from '@aliasvault/client/api/errors/AppErrorCodes';
import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';
import { ServerUpdateRequiredError } from '@aliasvault/client/api/errors/ServerUpdateRequiredError';
import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';
import { WebApiService } from '@aliasvault/client/api/WebApiService';
import { describeAuthError, type AuthErrorOptions } from '@aliasvault/client/auth/AuthErrorMessage';
import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';
import { MissingDerivationParamsError, UnlockService } from '@aliasvault/client/auth/UnlockService';
import { logoutReasonKey } from '@aliasvault/client/sync/VaultSync';
import { handleClearTwoFactorState, handleGetTwoFactorState, handleStoreTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';
import { handleClearSession, handleFullVaultSync, handleStoreAccountKey } from '@/entrypoints/background/VaultMessageHandler';
import { StorageKeys } from '@/utils/constants/storageKeys';
import { logExpected, logFailure } from '@/utils/Diagnostics';
import { accountKeyFromPinKey } from '@/utils/LegacyKeyConversion';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { IncorrectPinError, InvalidPinFormatError, PinLockedError, removeAndDisablePin, resetFailedAttempts, unlockWithPin } from '@/utils/PinUnlockService';
import type { BackgroundAuthResult } from '@/utils/types/messaging/BackgroundAuthResult';
import type { MobileLoginResult } from '@aliasvault/client/auth/MobileLoginService';
import type { KeyChainKey } from '@aliasvault/client/auth/VaultKeyService';
import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
import { browser, storage } from '#imports';
/*
* Login and unlock run start in the popup but are completed in the background so they still complete when the popup closes mid-flow.
*/
let pendingAuth: Promise<BackgroundAuthResult> | null = null;
/**
* Run an auth flow unless one is already running, in which case its result is returned.
*/
function runExclusive(flow: () => Promise<BackgroundAuthResult>): Promise<BackgroundAuthResult> {
if (pendingAuth) {
return pendingAuth;
}
const run = flow().finally(() => {
if (pendingAuth === run) {
pendingAuth = null;
}
});
pendingAuth = run;
return run;
}
/**
* The result of the auth flow that is running, or null when none is.
*/
export function handleAwaitPendingAuth(): Promise<BackgroundAuthResult | null> {
return pendingAuth ?? Promise.resolve(null);
}
/**
* Notify content scripts in all tabs that the vault was unlocked, so any conditional passkey request parked while
* the vault was locked can re-query, and an autofill popup the user unlocked from can reopen.
*/
export async function broadcastVaultUnlocked(): Promise<void> {
try {
const tabs = await browser.tabs.query({});
await Promise.all(tabs.map(async (tab) => {
if (tab.id === undefined) {
return;
}
try {
await sendMessage('VAULT_UNLOCKED', undefined, tab.id);
} catch {
// No receiving content script in this tab, ignore.
}
}));
} catch {
// tabs.query can fail in rare contexts, best-effort, ignore.
}
}
/**
* Map a failed flow to its result.
*/
async function failureResult(context: string, err: unknown, options?: AuthErrorOptions): Promise<BackgroundAuthResult> {
if (err instanceof VaultVersionIncompatibleError) {
return { status: 'logout', message: err.message };
}
if (err instanceof ClientUpgradeRequiredError) {
return { status: 'logout', reasonKey: 'common.errors.clientNotSupported' };
}
if (getAppErrorCode(err) === AppErrorCode.KEY_OUT_OF_SYNC) {
return { status: 'logout', reasonKey: getErrorTranslationKey(AppErrorCode.KEY_OUT_OF_SYNC) };
}
logFailure(context, err);
return { status: 'error', error: await describeAuthError(err, options) };
}
/**
* Check the server status before an unlock. Returns whether the unlock can go online and whether the server is unreachable,
* or the logout this client needs. A server that predates the v2 API is reachable but unlocks locally, so the upgrade
* page can tell the user it needs updating.
*/
async function checkServerStatus(webApi: WebApiService): Promise<{ online: boolean; offline: boolean } | { logout: BackgroundAuthResult }> {
try {
const status = await webApi.getStatus();
if (status.serverVersion === '0.0.0') {
return { online: false, offline: true };
}
const statusError = webApi.validateStatusResponse(status);
if (statusError !== null) {
return { logout: { status: 'logout', reasonKey: logoutReasonKey(statusError) } };
}
return { online: true, offline: false };
} catch (err) {
if (err instanceof ClientUpgradeRequiredError) {
return { logout: { status: 'logout', reasonKey: 'common.errors.clientNotSupported' } };
}
if (err instanceof ServerUpdateRequiredError) {
return { online: false, offline: false };
}
// Any other error is an auth failure: the server is reachable but the session is gone.
logExpected('[Auth] Status check failed during unlock', err);
return { logout: { status: 'logout', reasonKey: 'common.errors.sessionExpired' } };
}
}
/**
* Store the verified Account Key, which unlocks the vault, and tell content scripts about it.
*/
async function storeAccountKey(accountKey: string, offline: boolean, broadcast: boolean): Promise<void> {
const stored = await handleStoreAccountKey(accountKey);
if (!stored.success) {
throw new Error(stored.error);
}
await markUnlocked(offline, broadcast);
}
/**
* Record the unlocked state next to a stored Account Key, and tell content scripts about it when asked.
*/
async function markUnlocked(offline: boolean, broadcast: boolean): Promise<void> {
await storage.setItem(StorageKeys.IS_OFFLINE_MODE, offline);
await LocalPreferencesService.setVaultLockedDismissUntil(0);
if (broadcast) {
void broadcastVaultUnlocked();
}
}
/**
* Unlock the vault with the master password, online against the server's key chain or offline against the cached one.
*/
export function handleUnlockWithPassword(data: { password: string }): Promise<BackgroundAuthResult> {
return runExclusive(async () => {
const webApi = new WebApiService();
const status = await checkServerStatus(webApi);
if ('logout' in status) {
return status.logout;
}
try {
// Throws an unlock-key-rejected (E-206) error on a wrong password.
const accountKey = await UnlockService.unlockWithPassword(data.password, { online: status.online, webApi });
await storeAccountKey(accountKey, status.offline, true);
await resetFailedAttempts();
await LocalPreferencesService.resetPasswordUnlockFailedAttempts();
await LocalPreferencesService.setLastUsedUnlockMethod('password');
return { status: 'success', offline: status.offline };
} catch (err) {
if (err instanceof MissingDerivationParamsError) {
// Offline unlock needs the derivation params of an earlier online login.
return { status: 'error', error: { key: 'common.errors.serverNotAvailable', wrongPassword: false } };
}
const message = await describeAuthError(err, { uncodedIsWrongPassword: true });
if (message.wrongPassword) {
const failedAttempts = await LocalPreferencesService.getPasswordUnlockFailedAttempts() + 1;
await LocalPreferencesService.setPasswordUnlockFailedAttempts(failedAttempts);
return { status: 'wrongPassword', failedAttempts };
}
return failureResult('Unlock error', err, { uncodedIsWrongPassword: true });
}
});
}
/**
* Unlock the vault with the PIN, which decrypts the stored Account Key.
*/
export function handleUnlockWithPin(data: { pin: string }): Promise<BackgroundAuthResult> {
return runExclusive(async () => {
try {
const pinKey = await unlockWithPin(data.pin);
// This legacy key conversion call can be removed once all clients have updated to 0.31.0+.
const accountKey = await accountKeyFromPinKey(data.pin, pinKey);
const status = await checkServerStatus(new WebApiService());
if ('logout' in status) {
return status.logout;
}
await storeAccountKey(accountKey, status.offline, true);
await LocalPreferencesService.setLastUsedUnlockMethod('pin');
return { status: 'success', offline: status.offline };
} catch (err) {
if (err instanceof PinLockedError) {
return { status: 'pinFailed', reason: 'locked' };
}
if (err instanceof IncorrectPinError) {
return { status: 'pinFailed', reason: 'incorrect', attemptsRemaining: err.attemptsRemaining };
}
if (err instanceof InvalidPinFormatError) {
return { status: 'pinFailed', reason: 'invalidFormat' };
}
const message = await describeAuthError(err, { fallback: 'common.errors.unknownErrorTryAgain' });
if (message.wrongPassword) {
/*
* The PIN was right (AES-GCM decrypted), but the key it holds no longer opens the chain: a legacy PIN still
* holding the unlock key of a password that has since changed. It can never work again, so disable it.
*/
logExpected('[Unlock] The key restored by the PIN no longer opens the key chain, disabling PIN unlock', err);
await removeAndDisablePin();
return { status: 'pinFailed', reason: 'locked' };
}
return failureResult('PIN unlock failed', err, { fallback: 'common.errors.unknownErrorTryAgain' });
}
});
}
/**
* Log in with username and master password. Returns `twoFactorRequired` when the account needs a 2FA code next.
*/
export function handleLoginWithPassword(data: { username: string; password: string; rememberMe: boolean }): Promise<BackgroundAuthResult> {
return runExclusive(async () => {
try {
const username = SrpAuthService.normalizeUsername(data.username);
const srp = new SrpLoginService(new WebApiService());
const loginResponse = await srp.initiateLogin(username);
const credentials = await SrpAuthService.prepareLoginCredentials(data.password, loginResponse, username);
const proof = await srp.createLoginProof(username, credentials, loginResponse);
const validation = await srp.validateLoginWithProof(username, proof, data.rememberMe, loginResponse.loginSessionId);
if (validation.requiresTwoFactor) {
// Kept in memory for the 2FA step, which may come from a reopened popup. The server accepts the same proof again.
const { salt, encryptionType, encryptionSettings } = loginResponse;
handleStoreTwoFactorState({ username, rememberMe: data.rememberMe, loginSessionId: loginResponse.loginSessionId, proof, unlockKeyBase64: credentials.unlockKeyBase64, derivationParams: { salt, encryptionType, encryptionSettings } });
return { status: 'twoFactorRequired', username, rememberMe: data.rememberMe };
}
if (!validation.token) {
return { status: 'error', error: { key: 'common.errors.unknownError', wrongPassword: false } };
}
return await completeLogin(username, validation.token.token, validation.token.refreshToken, { unlockKey: credentials.unlockKeyBase64 }, loginResponse, data.password);
} catch (err) {
return failureResult('Login error', err);
}
});
}
/**
* Finish a login that needs a 2FA code, using the state the password step left behind.
*/
export function handleLoginWithTwoFactor(data: { code: string }): Promise<BackgroundAuthResult> {
return runExclusive(async () => {
const state = handleGetTwoFactorState();
if (!state) {
return { status: 'error', error: { key: 'common.errors.unknownError', wrongPassword: false } };
}
try {
const srp = new SrpLoginService(new WebApiService());
const validation = await srp.validateLogin2FaWithProof(state.username, state.proof, state.rememberMe, state.loginSessionId, parseInt(data.code));
if (!validation.token) {
return { status: 'error', error: { key: 'common.errors.unknownError', wrongPassword: false } };
}
handleClearTwoFactorState();
return await completeLogin(state.username, validation.token.token, validation.token.refreshToken, { unlockKey: state.unlockKeyBase64 }, state.derivationParams);
} catch (err) {
return failureResult('2FA error', err);
}
});
}
/**
* Finish a login a mobile app approved, with the Account Key it sent.
*/
export function handleLoginWithMobile(data: MobileLoginResult): Promise<BackgroundAuthResult> {
return runExclusive(async () => {
try {
const { salt, encryptionType, encryptionSettings } = data;
return await completeLogin(SrpAuthService.normalizeUsername(data.username), data.token, data.refreshToken, { accountKey: data.accountKey }, { salt, encryptionType, encryptionSettings });
} catch (err) {
return failureResult('Mobile login error', err);
}
});
}
/**
* Store the session of an accepted login and pull its vault. A password login also raises older key derivation
* settings to the current defaults.
*/
async function completeLogin(username: string, token: string, refreshToken: string, key: KeyChainKey, derivationParams: UnlockKeyDerivationParams, password?: string): Promise<BackgroundAuthResult> {
await storage.setItem(StorageKeys.USERNAME, username);
await storage.setItem(StorageKeys.ACCESS_TOKEN, token);
await storage.setItem(StorageKeys.REFRESH_TOKEN, refreshToken);
// Fetch the key chain and check the key opens it. Not recoverable when it fails, so log out again.
const webApi = new WebApiService();
await UnlockService.completeKeyChainLogin(key, derivationParams, webApi, async () => {
await webApi.revokeTokens();
await handleClearSession();
});
if (password && 'unlockKey' in key) {
await UnlockService.upgradeKeyDerivation(password, derivationParams, key.unlockKey, webApi, username);
}
// Content scripts are told once the vault is pulled: before that there is nothing to autofill from.
await markUnlocked(false, false);
const sync = await handleFullVaultSync({ forcePull: true, reportErrorToPopup: false });
if (sync.logoutReason === 'clientVersionNotSupported') {
throw new ClientUpgradeRequiredError();
}
if (sync.logoutReason === 'serverVersionNotSupported') {
return { status: 'error', error: await describeAuthError(new ServerUpdateRequiredError()) };
}
if (!sync.success) {
return { status: 'vaultPullFailed', sync };
}
void broadcastVaultUnlocked();
return { status: 'success', offline: false };
}