Skip to content

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

Refactor grant access to invite user (#2159)

Leendert de Borst4fda70ffba84
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.ts
index ff4224b65..d3d2e5e03 100644
--- a/apps/browser-extension/src/entrypoints/background.ts
+++ b/apps/browser-extension/src/entrypoints/background.ts
@@ -9,7 +9,7 @@ import { handleGetWebAuthnSettings, handleWebAuthnCreate, handleWebAuthnGet, han
import { handleOpenPopup, handlePopupWithItem, handleOpenPopupCreateCredential, handleToggleContextMenu } from '@/entrypoints/background/PopupMessageHandler';
import { handleStoreSavePromptState, handleGetSavePromptState, handleClearSavePromptState, handleStoreLastAutofilled, handleGetLastAutofilled, handleClearLastAutofilled } from '@/entrypoints/background/SavePromptStateHandler';
import { handleStoreTwoFactorState, handleGetTwoFactorState, handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorStateHandler';
-import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleGetFilteredItems, handleGetSearchItems, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGeneratePassword, handleGetPersistedFormValues, handleGetVault, handleGetVaultMigrationStatus, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVaultMetadata, handleSyncVault, handleUploadVault, handleGetEncryptedVault, handleStoreEncryptedVault, handleGetSyncState, handleMarkVaultClean, handleMigrateVaultManifest, handleFullVaultSync, handleGroupCreateVault, handleGroupGrantAccess, handleGroupRevokeAccess, handleGroupRemoveMember, handleCheckLoginDuplicate, handleSaveLoginCredential, handleAddUrlToCredential, handleIsUrlLinkedToCredential, handleGetLoginSaveSettings, handleSetLoginSaveEnabled, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpSecrets, handleGenerateTotpCode, handleSetRecentlySelected, handleGetRecentlySelected, handleRecordItemUsage } from '@/entrypoints/background/VaultMessageHandler';
+import { handleCheckAuthStatus, handleClearPersistedFormValues, handleClearSession, handleClearVaultData, handleLockVault, handleGetFilteredItems, handleGetSearchItems, handleGetDefaultEmailDomain, handleGetDefaultIdentitySettings, handleGetEncryptionKey, handleGetEncryptionKeyDerivationParams, handleGetPasswordSettings, handleGeneratePassword, handleGetPersistedFormValues, handleGetVault, handleGetVaultMigrationStatus, handlePersistFormValues, handleStoreEncryptionKey, handleStoreEncryptionKeyDerivationParams, handleStoreVaultMetadata, handleSyncVault, handleUploadVault, handleGetEncryptedVault, handleStoreEncryptedVault, handleGetSyncState, handleMarkVaultClean, handleMigrateVaultManifest, handleFullVaultSync, handleGroupCreateVault, handleGroupInviteMember, handleGroupRevokeAccess, handleGroupRemoveMember, handleCheckLoginDuplicate, handleSaveLoginCredential, handleAddUrlToCredential, handleIsUrlLinkedToCredential, handleGetLoginSaveSettings, handleSetLoginSaveEnabled, handleGetItemsWithTotp, handleSearchItemsWithTotp, handleGetTotpSecrets, handleGenerateTotpCode, handleSetRecentlySelected, handleGetRecentlySelected, handleRecordItemUsage } from '@/entrypoints/background/VaultMessageHandler';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { onMessage, sendMessage } from "@/utils/messaging/ExtensionMessaging";
@@ -272,7 +272,7 @@ export default defineBackground({
onMessage('GET_VAULT_MIGRATION_STATUS', () => handleGetVaultMigrationStatus());
onMessage('MIGRATE_VAULT_MANIFEST', () => handleMigrateVaultManifest());
onMessage('GROUP_CREATE_VAULT', ({ data, sender }) => isTrustedExtensionSender(sender) ? handleGroupCreateVault(data) : { success: false });
- onMessage('GROUP_GRANT_ACCESS', ({ data, sender }) => isTrustedExtensionSender(sender) ? handleGroupGrantAccess(data) : { success: false });
+ onMessage('GROUP_INVITE_MEMBER', ({ data, sender }) => isTrustedExtensionSender(sender) ? handleGroupInviteMember(data) : { success: false });
onMessage('GROUP_REVOKE_ACCESS', ({ data, sender }) => isTrustedExtensionSender(sender) ? handleGroupRevokeAccess(data) : { success: false });
onMessage('GROUP_REMOVE_MEMBER', ({ data, sender }) => isTrustedExtensionSender(sender) ? handleGroupRemoveMember(data) : { success: false });
onMessage('LOCK_VAULT', () => handleLockVault());
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index 98057f0c7..a3b2edb92 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -14,7 +14,7 @@ import { EncryptionUtility } from '@/utils/EncryptionUtility';
import { readLegacySessionEncryptionKey } from '@/utils/legacy/LegacyStorageKeyFallbacks';
import { requiresLegacyAccountKeyMigration } from '@/utils/legacy/LegacyStorageModelMigration';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
-import { getManifestRevisions, manifestsRequiringPull, recordManifestRevisions, toManifestRevisionMap } from '@/utils/ManifestRevisions';
+import { getManifestRevisions, getPersonalManifestId, manifestsRequiringPull, recordManifestRevisions, toManifestRevisionMap } from '@/utils/ManifestRevisions';
import { sendMessage, type TotpSecret } from '@/utils/messaging/ExtensionMessaging';
import { PendingActionProcessor } from '@/utils/PendingActionProcessor';
import { RecentlySelectedItemService } from '@/utils/RecentlySelectedItemService';
@@ -104,6 +104,9 @@ function serverManifestsNeedPull(serverManifests: ManifestRevision[], localRevis
let isSyncInProgress = false;
let hasPendingSync = false;
+/** The shared manifests a pull was already forced for over a missing key record, so one the server stopped serving does not pull on every sync. */
+const manifestsPulledForSharedKeys = new Set<string>();
+
/**
* Check if the user is logged in and if the vault is locked, and also check for both kinds of pending vault.
*/
@@ -1419,9 +1422,10 @@ async function persistSyncErrorState(result: FullVaultSyncResult): Promise<void>
* Full vault sync orchestration that runs entirely in background context.
* Wraps the internal implementation with sync-error persistence so the popup
* can show a targeted alert for failures even if it wasn't open at the time.
+ * @param options - what the caller asks of the sync beyond what the revisions decide
*/
-export async function handleFullVaultSync(): Promise<FullVaultSyncResult> {
- const result = await handleFullVaultSyncInternal();
+export async function handleFullVaultSync(options?: FullVaultSyncOptions): Promise<FullVaultSyncResult> {
+ const result = await handleFullVaultSyncInternal(options);
await persistSyncErrorState(result);
return result;
}
@@ -1437,8 +1441,9 @@ function syncResult(overrides: Partial<FullVaultSyncResult> = {}): FullVaultSync
/**
* Internal implementation of the full vault sync. Wrapped by handleFullVaultSync
* so the result can be persisted to local storage for the popup to surface.
+ * @param options - what the caller asks of the sync beyond what the revisions decide
*/
-async function handleFullVaultSyncInternal(): Promise<FullVaultSyncResult> {
+async function handleFullVaultSyncInternal(options?: FullVaultSyncOptions): Promise<FullVaultSyncResult> {
// Check if sync is already in progress
if (isSyncInProgress) {
// Mark that we need to sync again after current sync completes
@@ -1456,7 +1461,7 @@ async function handleFullVaultSyncInternal(): Promise<FullVaultSyncResult> {
const webApi = new WebApiService();
try {
- const preflight = await runSyncPreflight(webApi);
+ const preflight = await runSyncPreflight(webApi, options);
if (!preflight.proceed) {
return preflight.result;
}
@@ -1506,6 +1511,12 @@ async function handleFullVaultSyncInternal(): Promise<FullVaultSyncResult> {
}
}
+/** What a caller may ask of a full sync beyond what the revisions decide. */
+type FullVaultSyncOptions = {
+ /** Pull even when the revisions say the vault is current, for state only a pull re-records (the shared-vault key records). */
+ forcePull?: boolean;
+};
+
/**
* Outcome of the sync preflight: either a result the sync returns as-is, or the state the sync then runs on.
*/
@@ -1525,9 +1536,10 @@ function abortSync(overrides: Partial<FullVaultSyncResult>): SyncPreflightResult
* Sync preflight (sanity checks) to determine if the sync should proceed.
*
* @param webApi - the API service the status call runs on
+ * @param options - what the caller asks of the sync beyond what the revisions decide
* @returns Either the result the sync must return unchanged, or the status, sync state and pull decision.
*/
-async function runSyncPreflight(webApi: WebApiService): Promise<SyncPreflightResult> {
+async function runSyncPreflight(webApi: WebApiService, options?: FullVaultSyncOptions): Promise<SyncPreflightResult> {
// Check if user is logged in
const authStatus = await handleCheckAuthStatus();
if (!authStatus.isLoggedIn) {
@@ -1545,7 +1557,7 @@ async function runSyncPreflight(webApi: WebApiService): Promise<SyncPreflightRes
// Get current sync state
const syncState = await handleGetSyncState();
- let needsPull = serverManifestsNeedPull(statusResponse.manifestRevisions, await getManifestRevisions());
+ let needsPull = options?.forcePull === true || serverManifestsNeedPull(statusResponse.manifestRevisions, await getManifestRevisions());
devLog(`[VaultSync] Status received (needsPull ${needsPull}, isDirty ${syncState.isDirty})`);
@@ -1575,7 +1587,7 @@ async function runSyncPreflight(webApi: WebApiService): Promise<SyncPreflightRes
return abortSync({ success: false, requiresLogout: true, errorKey: 'passwordChanged' });
}
- // Valid connection - exit offline mode if we were in it
+ // Valid connection: exit offline mode if we were in it
const isOffline = await storage.getItem(StorageKeys.IS_OFFLINE_MODE) as boolean | null;
if (isOffline) {
await storage.setItem(StorageKeys.IS_OFFLINE_MODE, false);
@@ -1585,15 +1597,13 @@ async function runSyncPreflight(webApi: WebApiService): Promise<SyncPreflightRes
syncState.isDirty = false;
}
- /*
- * The shared-vault keys this session holds are session state; the stored vault is not, so the two can drift
- * apart on their own — a browser restart clears the keys while the vault keeps its shared rows. Pushing in that
- * state would drop those rows from the write instead of failing it, so pull first: the pull is what re-records
- * the keys. Only checked when there is something to push, since that is the only case it protects.
- */
+ // Check if we are missing any manifest related information that we do have write access for.
if (syncState.isDirty && !needsPull && await vaultHoldsUnwritableManifests()) {
needsPull = true;
}
+ if (!needsPull && await vaultHoldsUnrecordedSharedManifests()) {
+ needsPull = true;
+ }
return { proceed: true, statusResponse, syncState, needsPull };
}
@@ -1618,6 +1628,37 @@ async function vaultHoldsUnwritableManifests(): Promise<boolean> {
}
}
+/**
+ * Whether the stored vault holds rows of shared manifests this session has no key record for, which a pull has to repair.
+ * A manifest still unrecorded after its pull (the server no longer serves it) is not pulled for again.
+ */
+async function vaultHoldsUnrecordedSharedManifests(): Promise<boolean> {
+ try {
+ const recorded = new Set(Object.values(await SharingService.getSessionSharedManifests()).map(record => record.manifestId.toLowerCase()));
+ for (const manifestId of recorded) {
+ manifestsPulledForSharedKeys.delete(manifestId);
+ }
+
+ const personalManifestId = (await getPersonalManifestId())?.toLowerCase() ?? null;
+ const unrecorded = [...VaultCodec.manifestIdsInVault(await createVaultSqliteClient())]
+ .map(manifestId => manifestId.toLowerCase())
+ .filter(manifestId => manifestId !== personalManifestId && !recorded.has(manifestId) && !manifestsPulledForSharedKeys.has(manifestId));
+ if (unrecorded.length === 0) {
+ return false;
+ }
+
+ for (const manifestId of unrecorded) {
+ manifestsPulledForSharedKeys.add(manifestId);
+ }
+
+ devWarn(`[VaultSync] Vault holds rows for shared manifest(s) this session has no key record for (${unrecorded.join(', ')}); pulling to re-record them.`);
+ return true;
+ } catch (error) {
+ devWarn('[VaultSync] Could not check which shared manifests this session holds key records for; leaving the pull decision to the revisions.', error);
+ return false;
+ }
+}
+
/**
* Fall back to offline mode when the server cannot be reached. Without a local vault there is nothing to fall
* back on, so that case reports a failure instead.
@@ -2613,17 +2654,26 @@ export async function handleGroupCreateVault(message: { groupId: string; name: s
}
/**
- * Give a member of a family access to one of its shared vaults, handing them the vault's key sealed for them.
+ * Invite a member of a family to one of its shared vaults, handing them the vault's key sealed for them.
*
* The recipient is picked off the family's own roster, so this never names an account outside the family.
- * @param message - the family, the vault, and the member being let in.
+ * @param message - the family, the vault, and the member being invited.
*/
-export async function handleGroupGrantAccess(message: { groupId: string; manifestId: string; userId: string }): Promise<{ success: boolean; error?: string; apiErrorCode?: string }> {
+export async function handleGroupInviteMember(message: { groupId: string; manifestId: string; userId: string }): Promise<{ success: boolean; error?: string; apiErrorCode?: string }> {
const encryptionKey = await handleGetEncryptionKey();
if (!encryptionKey) {
return { success: false, error: formatErrorWithCode(await t('common.errors.vaultIsLocked'), AppErrorCode.VAULT_LOCKED) };
}
+ /**
+ * Fail the invite with a reason.
+ * @param reason - what was missing.
+ */
+ const failed = async (reason: string): Promise<{ success: boolean; error: string }> => {
+ devWarn(`[Sharing] Could not invite ${message.userId} to vault ${message.manifestId}: ${reason}.`);
+ return { success: false, error: `${await t('sharing.family.errors.inviteFailed')} [${reason}]` };
+ };
+
try {
const webApi = new WebApiService();
const overview = await SharingService.getOverview(webApi);
@@ -2631,8 +2681,16 @@ export async function handleGroupGrantAccess(message: { groupId: string; manifes
const manifest = group?.manifests.find(candidate => candidate.manifestId.toLowerCase() === message.manifestId.toLowerCase());
const member = group?.members.find(candidate => candidate.userId === message.userId);
- if (!group || group.role === 'Member' || !manifest || !member) {
- return { success: false, error: await t('sharing.family.errors.inviteFailed') };
+ if (!group || group.role === 'Member') {
+ return failed('not an administrator of the group');
+ }
+
+ if (!manifest) {
+ return failed('the vault does not belong to the group');
+ }
+
+ if (!member) {
+ return failed('the recipient is not a member of the group');
}
if (!member.publicKey) {
@@ -2640,15 +2698,21 @@ export async function handleGroupGrantAccess(message: { groupId: string; manifes
}
// Find the session's own grant on the vault: a key that was never handed to this account cannot be passed on.
- const record = Object.values(await SharingService.getSessionSharedManifests()).find(candidate => candidate.manifestId.toLowerCase() === manifest.manifestId.toLowerCase());
+ let record = await SharingService.getSessionSharedManifest(manifest.manifestId);
+ if (!record) {
+ devWarn(`[Sharing] No key record for vault ${manifest.manifestId} in this session; pulling to re-record it before inviting.`);
+ await handleFullVaultSync({ forcePull: true });
+ record = await SharingService.getSessionSharedManifest(manifest.manifestId);
+ }
+
if (!record) {
- return { success: false, error: await t('sharing.family.errors.inviteFailed') };
+ return failed('this session holds no key for the vault');
}
const sqliteClient = await createVaultSqliteClient();
const manifestVek = await SharingService.openSharedManifestVek(sqliteClient, record);
if (!manifestVek) {
- return { success: false, error: await t('sharing.family.errors.inviteFailed') };
+ return failed('the key of the vault did not open');
}
const vaultName = anchorFolderNames(sqliteClient)[manifest.manifestId.toLowerCase()] ?? record.name ?? null;
@@ -2657,16 +2721,16 @@ export async function handleGroupGrantAccess(message: { groupId: string; manifes
return { success: false, apiErrorCode: 'INVITE_RECIPIENT_NOT_READY' };
}
- await SharingService.grantAccess(webApi, group.groupId, manifest.manifestId, member.userId, grant, VaultKeyAlgorithm.RsaOaepSha256);
+ await SharingService.inviteMember(webApi, group.groupId, manifest.manifestId, member.userId, grant, VaultKeyAlgorithm.RsaOaepSha256);
- devLog(`[Sharing] Offered ${member.userId} access to vault ${manifest.manifestId} with its key encrypted for them.`);
+ devLog(`[Sharing] Invited ${member.userId} to vault ${manifest.manifestId} with its key encrypted for them.`);
return { success: true };
} catch (error) {
if (error instanceof ApiRequestError && error.apiErrorCode) {
return { success: false, apiErrorCode: error.apiErrorCode };
}
- console.error('Failed to grant shared vault access:', error);
+ console.error('Failed to invite member to shared vault:', error);
return { success: false, error: await t('sharing.family.errors.inviteFailed') };
}
}
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Dialogs/ConfirmPasswordModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/Dialogs/ConfirmPasswordModal.tsx
new file mode 100644
index 000000000..f39937905
--- /dev/null
+++ b/apps/browser-extension/src/entrypoints/popup/components/Dialogs/ConfirmPasswordModal.tsx
@@ -0,0 +1,112 @@
+import React, { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import ModalWrapper from '@/entrypoints/popup/components/Dialogs/ModalWrapper';
+
+type ConfirmPasswordModalProps = {
+ isOpen: boolean;
+ onClose: () => void;
+ onConfirm: (password: string) => Promise<void>;
+ title: string;
+ message: string;
+ confirmText: string;
+}
+
+/**
+ * A reusable confirmation modal for destructive actions that must be confirmed with the user's master password.
+ * The password is handed to the caller for verification; a thrown error is shown inside the modal so the user can retry.
+ */
+const ConfirmPasswordModal: React.FC<ConfirmPasswordModalProps> = ({
+ isOpen,
+ onClose,
+ onConfirm,
+ title,
+ message,
+ confirmText
+}) => {
+ const { t } = useTranslation();
+ const [password, setPassword] = useState('');
+ const [error, setError] = useState<string | null>(null);
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ useEffect(() => {
+ if (isOpen) {
+ setPassword('');
+ setError(null);
+ setIsSubmitting(false);
+ }
+ }, [isOpen]);
+
+ /**
+ * Hand the entered password to the caller, keeping the modal open with the error when it throws.
+ * @param event - the form submit event.
+ */
+ const handleSubmit = async (event: React.FormEvent): Promise<void> => {
+ event.preventDefault();
+ if (password.length === 0 || isSubmitting) {
+ return;
+ }
+
+ setIsSubmitting(true);
+ setError(null);
+ try {
+ await onConfirm(password);
+ } catch (confirmError) {
+ setError(confirmError instanceof Error && confirmError.message.length > 0 ? confirmError.message : t('common.errors.unknownErrorTryAgain'));
+ setIsSubmitting(false);
+ }
+ };
+
+ return (
+ <ModalWrapper
+ isOpen={isOpen}
+ onClose={onClose}
+ title={title}
+ maxWidth="max-w-sm"
+ >
+ <form onSubmit={handleSubmit} className="space-y-4">
+ <p className="text-gray-500 dark:text-gray-400">
+ {message}
+ </p>
+
+ <div>
+ <label htmlFor="confirm-master-password" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
+ {t('auth.masterPassword')}
+ </label>
+ <input
+ id="confirm-master-password"
+ type="password"
+ autoFocus
+ autoComplete="current-password"
+ value={password}
+ onChange={event => setPassword(event.target.value)}
+ placeholder={t('auth.passwordPlaceholder')}
+ className="w-full px-3 py-2 text-sm rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
+ />
+ </div>
+
+ {error && <p className="text-sm text-red-600 dark:text-red-400">{error}</p>}
+
+ <div className="flex justify-end gap-2">
+ <button
+ type="button"
+ onClick={onClose}
+ disabled={isSubmitting}
+ className="px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded disabled:opacity-50"
+ >
+ {t('common.cancel')}
+ </button>
+ <button
+ type="submit"
+ disabled={isSubmitting || password.length === 0}
+ className="px-4 py-2 text-sm bg-red-600 text-white rounded hover:bg-red-700 disabled:opacity-50"
+ >
+ {confirmText}
+ </button>
+ </div>
+ </form>
+ </ModalWrapper>
+ );
+};
+
+export default ConfirmPasswordModal;
diff --git a/apps/browser-extension/src/entrypoints/popup/utils/SrpUtility.ts b/apps/browser-extension/src/entrypoints/popup/utils/SrpUtility.ts
index 7552d4cd0..c54b4ddf2 100644
--- a/apps/browser-extension/src/entrypoints/popup/utils/SrpUtility.ts
+++ b/apps/browser-extension/src/entrypoints/popup/utils/SrpUtility.ts
@@ -68,37 +68,12 @@ class SrpUtility {
loginResponse: LoginResponse
): Promise<ValidateLoginResponse> {
const normalizedUsername = SrpAuthService.normalizeUsername(username);
-
- /*
- * Use srpIdentity from server response if available, otherwise fall back to normalized username.
- * @todo Remove fallback after 0.26.0+ has been released.
- */
- const srpIdentity = loginResponse.srpIdentity ?? normalizedUsername;
-
- // Generate client ephemeral
- const clientEphemeral = await SrpAuthService.generateEphemeral();
-
- // Derive private key using srpIdentity (not the typed username)
- const privateKey = await SrpAuthService.derivePrivateKey(
- loginResponse.salt,
- srpIdentity,
- passwordHashString
- );
-
- // Derive session using srpIdentity (not the typed username)
- const session = await SrpAuthService.deriveSession(
- clientEphemeral.secret,
- loginResponse.serverEphemeral,
- loginResponse.salt,
- srpIdentity,
- privateKey
- );
+ const proof = await SrpAuthService.deriveLoginProof(loginResponse, normalizedUsername, passwordHashString);
const model: ValidateLoginRequest = {
username: normalizedUsername,
rememberMe: rememberMe,
- clientPublicEphemeral: clientEphemeral.public,
- clientSessionProof: session.proof,
+ ...proof,
};
const response = await this.webApiService.rawFetch('Auth/validate', {
@@ -133,37 +108,12 @@ class SrpUtility {
code2Fa: number
): Promise<ValidateLoginResponse> {
const normalizedUsername = SrpAuthService.normalizeUsername(username);
-
- /*
- * Use srpIdentity from server response if available, otherwise fall back to normalized username.
- * @todo Remove fallback after 0.26.0+ has been released.
- */
- const srpIdentity = loginResponse.srpIdentity ?? normalizedUsername;
-
- // Generate client ephemeral
- const clientEphemeral = await SrpAuthService.generateEphemeral();
-
- // Derive private key using srpIdentity (not the typed username)
- const privateKey = await SrpAuthService.derivePrivateKey(
- loginResponse.salt,
- srpIdentity,
- passwordHashString
- );
-
- // Derive session using srpIdentity (not the typed username)
- const session = await SrpAuthService.deriveSession(
- clientEphemeral.secret,
- loginResponse.serverEphemeral,
- loginResponse.salt,
- srpIdentity,
- privateKey
- );
+ const proof = await SrpAuthService.deriveLoginProof(loginResponse, normalizedUsername, passwordHashString);
const model: ValidateLoginRequest2Fa = {
username: normalizedUsername,
rememberMe,
- clientPublicEphemeral: clientEphemeral.public,
- clientSessionProof: session.proof,
+ ...proof,
code2Fa,
};
diff --git a/apps/browser-extension/src/utils/auth/SrpAuthService.ts b/apps/browser-extension/src/utils/auth/SrpAuthService.ts
index 9d928e498..78f78ab36 100644
--- a/apps/browser-extension/src/utils/auth/SrpAuthService.ts
+++ b/apps/browser-extension/src/utils/auth/SrpAuthService.ts
@@ -50,6 +50,14 @@ export type RegistrationResult = {
error?: string;
};
+/**
+ * SRP client proof type.
+ */
+export type SrpClientProof = {
+ clientPublicEphemeral: string;
+ clientSessionProof: string;
+};
+
/**
* Login credentials prepared from password derivation.
*/
@@ -248,6 +256,50 @@ export class SrpAuthService {
) as SrpSession;
}
+ /**
+ * Derives the client's SRP proof for one server-verified master password check.
+ *
+ * @param salt - The SRP salt from the initiate response
+ * @param srpIdentity - The SRP identity from the initiate response
+ * @param passwordHashString - The password hash as uppercase hex string
+ * @param serverEphemeral - The server's public ephemeral from the initiate response
+ * @returns The client public ephemeral and session proof to submit to the confirm endpoint
+ */
+ public static async deriveClientProof(
+ salt: string,
+ srpIdentity: string,
+ passwordHashString: string,
+ serverEphemeral: string
+ ): Promise<SrpClientProof> {
+ const clientEphemeral = await SrpAuthService.generateEphemeral();
+ const privateKey = await SrpAuthService.derivePrivateKey(salt, srpIdentity, passwordHashString);
+ const session = await SrpAuthService.deriveSession(clientEphemeral.secret, serverEphemeral, salt, srpIdentity, privateKey);
+
+ return { clientPublicEphemeral: clientEphemeral.public, clientSessionProof: session.proof };
+ }
+
+ /**
+ * Derives the client's SRP proof for a login initiate response.
+ *
+ * @param loginResponse - The login initiate response holding salt, SRP identity and server ephemeral
+ * @param username - The username typed by the user, used as SRP identity fallback on older servers
+ * @param passwordHashString - The password hash as uppercase hex string
+ * @returns The client public ephemeral and session proof to submit to the validate endpoint
+ */
+ public static async deriveLoginProof(
+ loginResponse: LoginResponse,
+ username: string,
+ passwordHashString: string
+ ): Promise<SrpClientProof> {
+ /*
+ * Use srpIdentity from server response if available, otherwise fall back to normalized username.
+ * @todo Remove fallback after 0.26.0+ has been released.
+ */
+ const srpIdentity = loginResponse.srpIdentity ?? SrpAuthService.normalizeUsername(username);
+
+ return SrpAuthService.deriveClientProof(loginResponse.salt, srpIdentity, passwordHashString, loginResponse.serverEphemeral);
+ }
+
/**
* Prepares login credentials by deriving the password hash.
*
@@ -444,12 +496,6 @@ export class SrpAuthService {
const loginResponse = (await initiateResponse.json()) as LoginResponse;
- /*
- * Use srpIdentity from server response if available, otherwise fall back to normalized username.
- * @todo Remove fallback after 0.26.0+ has been released.
- */
- const srpIdentity = loginResponse.srpIdentity ?? normalizedUsername;
-
// Step 2: Prepare credentials
const credentials = await SrpAuthService.prepareCredentials(
password,
@@ -458,20 +504,8 @@ export class SrpAuthService {
loginResponse.encryptionSettings
);
- // Step 3: Generate SRP session using srpIdentity (not the typed username)
- const clientEphemeral = await SrpAuthService.generateEphemeral();
- const privateKey = await SrpAuthService.derivePrivateKey(
- loginResponse.salt,
- srpIdentity,
- credentials.passwordHashString
- );
- const session = await SrpAuthService.deriveSession(
- clientEphemeral.secret,
- loginResponse.serverEphemeral,
- loginResponse.salt,
- srpIdentity,
- privateKey
- );
+ // Step 3: Generate the SRP proof for this login response
+ const proof = await SrpAuthService.deriveLoginProof(loginResponse, normalizedUsername, credentials.passwordHashString);
// Step 4: Validate login
const validateResponse = await fetch(`${baseUrl}Auth/validate`, {
@@ -480,8 +514,7 @@ export class SrpAuthService {
body: JSON.stringify({
username: normalizedUsername,
rememberMe,
- clientPublicEphemeral: clientEphemeral.public,
- clientSessionProof: session.proof,
+ ...proof,
}),
});
diff --git a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
index 97e134787..9bb0ff911 100644
--- a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
+++ b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
@@ -90,7 +90,7 @@ export interface IExtensionMessageProtocol {
GET_VAULT_MIGRATION_STATUS(): VaultMigrationStatus;
GET_WEBAUTHN_SETTINGS(data: any): WebAuthnSettingsResponse;
GROUP_CREATE_VAULT(data: { groupId: string; name: string }): { success: boolean; error?: string; apiErrorCode?: string };
- GROUP_GRANT_ACCESS(data: { groupId: string; manifestId: string; userId: string }): { success: boolean; error?: string; apiErrorCode?: string };
+ GROUP_INVITE_MEMBER(data: { groupId: string; manifestId: string; userId: string }): { success: boolean; error?: string; apiErrorCode?: string };
GROUP_REVOKE_ACCESS(data: { groupId: string; manifestId: string; userId: string }): { success: boolean; error?: string; apiErrorCode?: string };
GROUP_REMOVE_MEMBER(data: { groupId: string; userId: string }): { success: boolean; error?: string; apiErrorCode?: string };
IS_URL_LINKED_TO_CREDENTIAL(data: { itemId: string; url: string }): { linked: boolean };