Skip to content

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

Update docs

Leendert de Borst16eef293f071
diff --git a/apps/browser-extension/src/utils/PinUnlockService.ts b/apps/browser-extension/src/utils/PinUnlockService.ts
index 07fbc1ee7..b1b789cf5 100644
--- a/apps/browser-extension/src/utils/PinUnlockService.ts
+++ b/apps/browser-extension/src/utils/PinUnlockService.ts
@@ -1,3 +1,7 @@
+/**
+ * PIN unlock: the Account Key encrypted with a key derived from the PIN, stored locally with the failed-attempt counter.
+ */
+
import { pinDecrypt, pinEncrypt, pinExtensionSalt, pinGenerateSalt, pinIsLocked, pinRegisterFailure } from '@aliasvault/client/rust/RustCore';
import { base64ToBytes, bytesToBase64 } from '@aliasvault/client/utilities/Base64';
@@ -7,20 +11,11 @@ import { logFailure } from '@/utils/Diagnostics';
import { browser, storage } from '#imports';
/**
- * PinUnlockService - Handles PIN-based vault unlock
- *
- * This service allows users to set a PIN (digits, letters or symbols) to unlock their vault instead
- * of entering their full master password. The Account Key
- * is encrypted with a key derived from the PIN and stored locally.
- */
-
-/**
- * Error thrown when PIN is locked after too many failed attempts.
- * Translation key: settings.unlockMethod.pinLocked
+ * The PIN is locked after too many failed attempts (translation key settings.unlockMethod.pinLocked).
*/
export class PinLockedError extends Error {
/**
- * Creates a new instance of PinLockedError.
+ * Creates the error.
*/
public constructor() {
super('PIN locked after too many failed attempts');
@@ -29,12 +24,11 @@ export class PinLockedError extends Error {
}
/**
- * Error thrown when PIN format is invalid.
- * Translation key: settings.unlockMethod.invalidPinFormat
+ * The PIN has an invalid format (translation key settings.unlockMethod.invalidPinFormat).
*/
export class InvalidPinFormatError extends Error {
/**
- * Creates a new instance of InvalidPinFormatError.
+ * Creates the error.
*/
public constructor() {
super('Invalid PIN format');
@@ -43,16 +37,14 @@ export class InvalidPinFormatError extends Error {
}
/**
- * Error thrown when PIN is incorrect.
- * Includes remaining attempts count.
- * Translation key: settings.unlockMethod.incorrectPin
+ * The PIN is incorrect (translation key settings.unlockMethod.incorrectPin).
*/
export class IncorrectPinError extends Error {
public readonly attemptsRemaining: number;
/**
- * Creates a new instance of IncorrectPinError.
- * @param attemptsRemaining - Number of attempts remaining
+ * Creates the error.
+ * @param attemptsRemaining - Attempts left before the PIN locks
*/
public constructor(attemptsRemaining: number) {
super(`Incorrect PIN. ${attemptsRemaining} attempts remaining.`);
@@ -62,20 +54,7 @@ export class IncorrectPinError extends Error {
}
/**
- * Error thrown when encryption key is not available for PIN setup.
- */
-export class EncryptionKeyNotAvailableError extends Error {
- /**
- * Creates a new instance of EncryptionKeyNotAvailableError.
- */
- public constructor() {
- super('Encryption key not available');
- this.name = 'EncryptionKeyNotAvailableError';
- }
-}
-
-/**
- * Check if PIN unlock is enabled
+ * Whether PIN unlock is enabled.
*/
export async function isPinEnabled(): Promise<boolean> {
try {
@@ -87,7 +66,7 @@ export async function isPinEnabled(): Promise<boolean> {
}
/**
- * Get the length of the configured PIN
+ * The length of the configured PIN, or null when none is set.
*/
export async function getPinLength(): Promise<number | null> {
try {
@@ -105,14 +84,14 @@ export const PIN_MIN_LENGTH = 6;
export const PIN_MAX_LENGTH = 64;
/**
- * Validate PIN format (6-64 characters of any kind)
+ * Whether a PIN has a valid format: 6 to 64 characters of any kind.
*/
export function isValidPin(pin: string): boolean {
return pin.length >= PIN_MIN_LENGTH && pin.length <= PIN_MAX_LENGTH;
}
/**
- * Get the failed attempts count, or null when the stored counter is unreadable (which counts as locked).
+ * The failed-attempt count, or null when the stored counter is unreadable (which counts as locked).
*/
async function getFailedAttempts(): Promise<number | null> {
try {
@@ -127,7 +106,7 @@ async function getFailedAttempts(): Promise<number | null> {
}
/**
- * Check if PIN attempts are exhausted
+ * Whether the PIN is locked after too many failed attempts.
*/
export async function isPinLocked(): Promise<boolean> {
const attempts = await getFailedAttempts();
@@ -135,11 +114,9 @@ export async function isPinLocked(): Promise<boolean> {
}
/**
- * Setup PIN unlock
- * Encrypts the session's Account Key with the PIN and stores it
- *
+ * Encrypt the session's Account Key with the PIN and store it.
* @param pin - The PIN to set (6-64 characters)
- * @param accountKey - The base64 Account Key to protect (VaultKeyService.getSessionAccountKey)
+ * @param accountKey - The base64 Account Key to protect
*/
export async function setupPin(pin: string, accountKey: string): Promise<void> {
if (!isValidPin(pin)) {
@@ -151,7 +128,6 @@ export async function setupPin(pin: string, accountKey: string): Promise<void> {
const saltBase64 = bytesToBase64(salt);
const encryptedKeyBase64 = bytesToBase64(await pinEncrypt(pin, await argon2Salt(salt), new TextEncoder().encode(accountKey)));
- /* Store encrypted key, salt, PIN length, and enable flag */
await Promise.all([
storage.setItem(StorageKeys.PIN_ENABLED, true),
storage.setItem(StorageKeys.PIN_ENCRYPTED_KEY, encryptedKeyBase64),
@@ -159,38 +135,28 @@ export async function setupPin(pin: string, accountKey: string): Promise<void> {
storage.setItem(StorageKeys.PIN_LENGTH, pin.length),
storage.setItem(StorageKeys.PIN_FAILED_ATTEMPTS, 0)
]);
-
} catch (error: unknown) {
- /* Re-throw custom errors as-is */
- if (error instanceof InvalidPinFormatError) {
- throw error;
- }
- /* Log internal errors and throw generic error for user */
logFailure('[PinUnlockService] Failed to setup PIN', error);
throw error;
}
}
/**
- * Unlock with PIN
- * Returns the decrypted stored key (the Account Key, or an unlock key from before the account had a key chain)
- *
- * @param pin - The PIN to use for unlocking
- * @returns The decrypted key (base64), which opens the account key chain
+ * Decrypt the stored key with the PIN.
+ * @param pin - The PIN
+ * @returns The decrypted key (base64)
*/
export async function unlockWithPin(pin: string): Promise<string> {
if (!isValidPin(pin)) {
throw new InvalidPinFormatError();
}
- /* Check if locked due to too many attempts */
const failedAttempts = await getFailedAttempts();
if (failedAttempts === null || await pinIsLocked(failedAttempts)) {
throw new PinLockedError();
}
try {
- /* Get stored data */
const [encryptedKeyBase64, saltBase64] = await Promise.all([
storage.getItem(StorageKeys.PIN_ENCRYPTED_KEY) as Promise<string | null>,
storage.getItem(StorageKeys.PIN_SALT) as Promise<string | null>
@@ -201,20 +167,16 @@ export async function unlockWithPin(pin: string): Promise<string> {
}
const decryptedData = await pinDecrypt(pin, await argon2Salt(base64ToBytes(saltBase64)), base64ToBytes(encryptedKeyBase64));
- const unlockKey = new TextDecoder().decode(decryptedData);
+ const storedKey = new TextDecoder().decode(decryptedData);
- /* Reset failed attempts on success */
await storage.setItem(StorageKeys.PIN_FAILED_ATTEMPTS, 0);
- return unlockKey;
+ return storedKey;
} catch {
const failure = await pinRegisterFailure(failedAttempts);
await storage.setItem(StorageKeys.PIN_FAILED_ATTEMPTS, failure.failedAttempts);
- /*
- * If max attempts reached, disable PIN and clear ALL stored data for security.
- * This prevents offline brute-force attacks on the encrypted key.
- */
+ // Locked: the encrypted key is deleted so it cannot be brute-forced offline.
if (failure.locked) {
await removeAndDisablePin();
throw new PinLockedError();
@@ -238,8 +200,7 @@ export async function removeAndDisablePin(): Promise<void> {
}
/**
- * Reset failed attempts counter
- * Called after successful password unlock
+ * Reset the failed-attempt counter, after a successful password unlock.
*/
export async function resetFailedAttempts(): Promise<void> {
try {
@@ -250,11 +211,9 @@ export async function resetFailedAttempts(): Promise<void> {
}
/**
- * The Argon2id salt for the PIN key: the stored random salt with the extension ID as pepper, composed in the Rust core.
- *
- * The extension ID is not stored in chrome.storage, which adds friction for an attacker who only copies that directory.
- *
- * @param randomSalt - The random salt stored in chrome.storage
+ * The Argon2id salt for the PIN key: the stored random salt with the extension id, which the storage directory alone
+ * does not reveal.
+ * @param randomSalt - The random salt as stored
*/
async function argon2Salt(randomSalt: Uint8Array): Promise<Uint8Array> {
return pinExtensionSalt(randomSalt, browser.runtime.id);
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt
index 45fcde83b..7f964ad02 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt
@@ -16,7 +16,7 @@ import uniffi.aliasvault_core.vaultBlobDecrypt as rustVaultBlobDecrypt
import uniffi.aliasvault_core.vaultBlobEncrypt as rustVaultBlobEncrypt
/**
- * Handles encryption, decryption, and key management for the vault.
+ * Key derivation, the account key chain, the keystore-backed session and the vault blob.
*/
class VaultCrypto(
private val keystoreProvider: KeystoreProvider,
@@ -51,14 +51,13 @@ class VaultCrypto(
get() = sessionKeys()?.accountKey?.let { Base64.encodeToString(it, Base64.NO_WRAP) }
/**
- * What the session key opens in the cached account key chain. A session opened before the device had a chain holds
- * the unlock key; once a sync caches the chain it opens as such and the Account Key replaces it (see [LegacyKeyConversion]).
+ * What the session key opens in the cached account key chain.
*/
@Suppress("SwallowedException")
private fun sessionKeys(): SessionKeys? {
val key = accountKey ?: return null
return try {
- // This legacy key conversion call can be removed once all clients have updated to 0.31.0+.
+ // LEGACY: a stored unlock key is converted into the Account Key. TODO: remove once all clients run 0.31.0+.
LegacyKeyConversion.openStoredKey(this, key).also { if (!it.accountKey.contentEquals(key)) accountKey = it.accountKey }
} catch (e: Exception) {
null
@@ -68,14 +67,9 @@ class VaultCrypto(
// region Key Derivation
/**
- * Derive a key from a password using Argon2Id.
+ * Derive the unlock key from a password with Argon2id.
*/
- fun deriveKeyFromPassword(
- password: String,
- salt: String,
- encryptionType: String,
- encryptionSettings: String,
- ): ByteArray {
+ fun deriveKeyFromPassword(password: String, salt: String, encryptionType: String, encryptionSettings: String): ByteArray {
// Both types derive the unlock key with Argon2id; they differ only in how the SRP input is made from it.
require(encryptionType == "Argon2Id" || encryptionType == "Argon2IdHkdf") { "Unsupported encryption type: $encryptionType" }
@@ -138,7 +132,6 @@ class VaultCrypto(
Log.d(TAG, "Encryption key stored in memory only, biometric keystore persistence deferred")
}
} catch (e: Exception) {
- // Catch any unexpected errors during keystore operations
Log.d(TAG, "Could not persist encryption key to keystore, stored in memory only: ${e.message}")
}
} else {
@@ -154,57 +147,54 @@ class VaultCrypto(
}
/**
- * Open a session in memory with a key the keystore stored: the Account Key, or the unlock key of a store written
- * before the account had a key chain (see [LegacyKeyConversion]).
+ * Open a session in memory with a key the keystore stored: the Account Key, or LEGACY the unlock key of a store
+ * written before the account had a key chain.
*/
fun openSessionWithStoredKey(key: ByteArray) {
- // This legacy key conversion call can be removed once all clients have updated to 0.31.0+.
+ // LEGACY: a stored unlock key is converted into the Account Key. TODO: remove once all clients run 0.31.0+.
accountKey = LegacyKeyConversion.openStoredKey(this, key).accountKey
}
/**
- * Clear the Account Key from memory.
- * This forces getEncryptionKey() to fetch the Account Key from keystore on next biometric access.
+ * Clear the Account Key from memory, so the next access opens the session from the keystore.
*/
fun clearEncryptionKeyFromMemory() {
clearKey()
}
/**
- * Store the encryption key derivation parameters.
+ * Store the unlock key derivation parameters (JSON) of the password.
*/
fun storeUnlockKeyDerivationParams(keyDerivationParams: String) {
storageProvider.setKeyDerivationParams(keyDerivationParams)
}
/**
- * Get the encryption key derivation parameters.
+ * The stored unlock key derivation parameters (JSON) of the password.
*/
fun getUnlockKeyDerivationParams(): String {
return storageProvider.getKeyDerivationParams()
}
/**
- * Store the account-key chain the native unlock opens: JSON with the Account Key wrapped by the
- * KEK derived from the unlock key ("encryptedAccountKey") and the VEK wrapped by the Account Key ("encryptedVek").
- * Null until the account is upgraded; its unlock key encrypts the vault directly.
+ * Store the account key chain the native unlock opens, as the server sent it; null for a legacy account.
*/
fun storeAccountKeyChain(chainJson: String?) {
storageProvider.setAccountKeyChain(chainJson?.takeIf { it.isNotEmpty() })
}
/**
- * The stored account-key chain JSON, or null until the account is upgraded.
+ * The stored account key chain JSON, or null for a legacy account.
*/
fun getAccountKeyChain(): String? {
return storageProvider.getAccountKeyChain()
}
/**
- * The session keys the account key chain gives.
+ * The keys an opened account key chain gives.
*
* @property vaultEncryptionKey The key that encrypts and decrypts the vault
- * @property accountPrivateKey The account private key (JWK), null when the account has no keypair
+ * @property accountPrivateKey The account private key (JWK), null when the account has no keypair or it does not open
* @property accountKey The Account Key to keep, in place of the key the chain was opened with
*/
class SessionKeys(val vaultEncryptionKey: ByteArray, val accountPrivateKey: String?, val accountKey: ByteArray)
@@ -260,21 +250,21 @@ class VaultCrypto(
}
/**
- * Check if biometric authentication is enabled and available.
+ * Whether biometrics are enabled in the settings and available on the device.
*/
fun isBiometricAuthEnabled(authMethods: String): Boolean {
return authMethods.contains(BIOMETRICS_AUTH_METHOD) && keystoreProvider.isBiometricAvailable()
}
/**
- * Get the encryption key, the key that encrypts and decrypts the vault.
+ * The encryption key, the key that encrypts and decrypts the vault.
*/
fun getEncryptionKey(callback: CryptoOperationCallback, authMethods: String) {
withSession(callback, authMethods) { encryptionKey }
}
/**
- * Get the Account Key, the key the keystore and PIN protect.
+ * The Account Key, the key the keystore and PIN protect.
*/
fun getAccountKey(callback: CryptoOperationCallback, authMethods: String) {
withSession(callback, authMethods) { accountKey }
@@ -297,7 +287,7 @@ class VaultCrypto(
try {
val keystoreKey = Base64.decode(result, Base64.NO_WRAP)
openSessionWithStoredKey(keystoreKey)
- // This legacy key conversion call can be removed once all clients have updated to 0.31.0+.
+ // LEGACY: a stored unlock key is converted into the Account Key. TODO: remove once all clients run 0.31.0+.
accountKey?.let { LegacyKeyConversion.convertLegacyKeystoreKey(keystoreProvider, keystoreKey, it) }
callback.onSuccess(Base64.encodeToString(key(), Base64.NO_WRAP))
} catch (e: AppError) {
@@ -311,7 +301,6 @@ class VaultCrypto(
override fun onError(e: Exception) {
Log.e(TAG, "Error retrieving key", e)
- // Pass through the error - AndroidKeystoreProvider now throws proper AppError types
callback.onError(e)
}
},
@@ -322,7 +311,7 @@ class VaultCrypto(
}
/**
- * Clear the encryption key from memory.
+ * Clear the Account Key from memory.
*/
fun clearKey() {
accountKey = null
@@ -381,8 +370,7 @@ class VaultCrypto(
// region Mobile Login
/**
- * Encrypts the Account Key using an RSA public key for mobile login. The receiving
- * client opens the account key chain with it, exactly as after a password login.
+ * Encrypt the Account Key for a mobile login request's RSA public key.
*/
fun encryptAccountKeyForMobileLogin(publicKeyJWK: String, authMethods: String): String {
var result: String? = null
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
index 795683be5..5470112bd 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
@@ -4,13 +4,10 @@ import Security
import RustCoreFramework
import VaultUtils
-/// Extension for the VaultStore class to handle encryption/decryption
+/// Key derivation, the account key chain, the keychain-backed session and the vault blob.
extension VaultStore {
- /// Derives a key from a password using Argon2Id
- public func deriveKeyFromPassword(_ password: String,
- salt: String,
- encryptionType: String,
- encryptionSettings: String) throws -> Data {
+ /// Derive the unlock key from a password with Argon2id.
+ public func deriveKeyFromPassword(_ password: String, salt: String, encryptionType: String, encryptionSettings: String) throws -> Data {
// Both types derive the unlock key with Argon2id; they differ only in how the SRP input is made from it.
guard encryptionType == "Argon2Id" || encryptionType == "Argon2IdHkdf" else {
throw NSError(domain: "VaultStore", code: 13, userInfo: [NSLocalizedDescriptionKey: "Unsupported encryption type: \(encryptionType)"])
@@ -49,8 +46,7 @@ extension VaultStore {
return keyData
}
- /// Clear the Account Key from memory.
- /// This forces getEncryptionKey() to fetch the Account Key from keychain on next access.
+ /// Clear the Account Key from memory, so the next access opens the session from the keychain.
public func clearEncryptionKeyFromMemory() {
self.accountKey = nil
clearLastSuccessfulAuth()
@@ -77,18 +73,13 @@ extension VaultStore {
}
}
- /// Store the key derivation parameters used for deriving the encryption key from the plain text password
+ /// Store the unlock key derivation parameters (JSON) of the password.
public func storeUnlockKeyDerivationParams(_ keyDerivationParams: String) throws {
- // Store the key derivation params in memory
self.keyDerivationParams = keyDerivationParams
-
- // Store the key derivation params in UserDefaults
self.userDefaults.set(keyDerivationParams, forKey: VaultConstants.unlockKeyDerivationParamsKey)
-
- print("Stored key derivation params in UserDefaults")
}
- /// Get the key derivation parameters used for deriving the encryption key from the plain text password
+ /// The stored unlock key derivation parameters (JSON) of the password.
public func getUnlockKeyDerivationParams() -> String? {
return self.keyDerivationParams
}
@@ -193,11 +184,9 @@ extension VaultStore {
return try? RustCoreFramework.accountSigningKeyFingerprint(encryptedSigningPrivateKey: encryptedSigningPrivateKey, accountKey: accountKey)
}
- /// Verify the password and return its unlock key (base64) if correct. Callers derive the SRP input from it for the
- /// account's encryption type; `storeAccountKey` turns it into the Account Key.
+ /// Verify the password offline and return its unlock key (base64), or nil when it does not open the key chain.
public func verifyPassword(_ password: String) -> String? {
do {
- // Get encryption key derivation parameters
guard let paramsString = getUnlockKeyDerivationParams(),
let paramsData = paramsString.data(using: .utf8),
let params = try? JSONSerialization.jsonObject(with: paramsData) as? [String: Any],
@@ -207,12 +196,10 @@ extension VaultStore {
return nil
}
- // Derive the unlock key from the password and unwrap the chain; a wrong password fails the unwrap.
let derivedKey = try deriveKeyFromPassword(password, salt: salt, encryptionType: encryptionType, encryptionSettings: encryptionSettings)
_ = try openKeyChainWithUnlockKey(derivedKey)
return derivedKey.base64EncodedString()
} catch {
- // Password incorrect or the key chain did not open
return nil
}
}
@@ -228,21 +215,12 @@ extension VaultStore {
do {
let decryptedData = try RustCoreFramework.vaultBlobDecrypt(encryptedBlob: encryptedBlob, key: encryptionKey)
- /*
- * If the decryption succeeds, try to persist the Account Key in the keychain.
- * This makes sure that on future password unlock attempts, only successful decryptions
- * will be remembered and used so failed re-authentication attempts won't overwrite
- * a previous successful decryption key stored in the keychain.
- *
- * We only attempt this if Face ID is enabled AND keystore is available.
- * If keystore is not available (no device passcode), we silently skip this step.
- */
+ // The Account Key is persisted only after a successful decryption, so a failed re-authentication never
+ // overwrites a working key in the keychain. A failure to persist (passcode removed) does not fail the decryption.
if self.enabledAuthMethods.contains(.faceID) && isKeystoreAvailable(), let accountKey = self.accountKey {
do {
try storeKeyInKeychain(accountKey)
} catch {
- // Don't fail the decryption if we can't store to keychain
- // This can happen if device passcode is removed after Face ID was enabled
print("Warning: Could not persist encryption key to keychain: \(error)")
}
}
@@ -251,28 +229,20 @@ extension VaultStore {
} catch {
print("Decryption failed: \(error)")
- // Note: We intentionally do not clear the encryption key here.
- // The key may be valid for a different vault (e.g., after password change
- // during login, the new key is stored but the old vault can't be decrypted).
- // Clearing it would break the subsequent sync that downloads the new vault.
-
+ // The key is kept: after a password change it opens the vault the next sync downloads.
throw NSError(domain: "VaultStore", code: 12, userInfo: [NSLocalizedDescriptionKey: "Decryption failed"])
}
}
- /// Check if biometric authentication is enabled and available
- /// Returns true if Face ID is enabled in settings AND the device supports biometric authentication
+ /// Whether Face ID is enabled in the settings and the device supports biometrics (always on the simulator).
public func isBiometricAuthEnabled() -> Bool {
- // Check if Face ID is enabled in app settings
guard self.enabledAuthMethods.contains(.faceID) else {
return false
}
#if targetEnvironment(simulator)
- // In simulator, always return true if Face ID is enabled in settings
return true
#else
- // Check if device supports biometric authentication
let context = LAContext()
var error: NSError?
return context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error)
@@ -284,13 +254,12 @@ extension VaultStore {
return try getEncryptionKey().base64EncodedString()
}
- /// Get the encryption key - the key used to encrypt and decrypt the vault.
+ /// The encryption key, the key that encrypts and decrypts the vault.
internal func getEncryptionKey() throws -> Data {
let key = try getAccountKey()
- // This legacy key conversion call can be removed once all clients have updated to 0.31.0+.
+ // LEGACY: a stored unlock key is converted into the Account Key. TODO: remove once all clients run 0.31.0+.
let keys = try openStoredKey(key)
if keys.accountKey != key {
- // A legacy key, see `VaultStore+LegacyKeyConversion`.
self.accountKey = keys.accountKey
convertLegacyKeychainKey(keychainKey: key, accountKey: keys.accountKey)
}
@@ -312,8 +281,6 @@ extension VaultStore {
/// Open a session with the Account Key the keychain holds, behind a biometric prompt.
private func openSessionFromKeychain() throws {
- // Key not in memory - check if we should try keychain retrieval
- // Only attempt keychain retrieval if Face ID is enabled AND keystore is available
if self.enabledAuthMethods.contains(.faceID) && isKeystoreAvailable() {
let context = LAContext()
var error: NSError?
@@ -322,7 +289,6 @@ extension VaultStore {
print("Simulator detected, skipping biometric policy evaluation check and continuing with key retrieval from keychain")
#else
if !context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
- // Map LAError codes to specific error types for better debugging
if let laError = error as? LAError {
switch laError.code {
case .biometryNotAvailable:
@@ -351,7 +317,7 @@ extension VaultStore {
}
do {
- // This legacy key conversion call can be removed once all clients have updated to 0.31.0+.
+ // LEGACY: a stored unlock key is converted into the Account Key. TODO: remove once all clients run 0.31.0+.
let accountKey = try openStoredKey(keyData).accountKey
self.accountKey = accountKey
convertLegacyKeychainKey(keychainKey: keyData, accountKey: accountKey)
@@ -365,18 +331,12 @@ extension VaultStore {
return
}
- // Key not in memory and cannot retrieve from keychain
- // This happens when:
- // 1. Password-only auth (Face ID not enabled)
- // 2. Face ID enabled but keystore unavailable (no device passcode)
- // 3. Face ID enabled but key was never stored (e.g., during initial login)
+ // Face ID is not enabled, the keystore is unavailable (no device passcode) or no key was stored yet.
throw AppError.keystoreKeyNotFound
}
- /// Check if keystore is available (requires device passcode to be set)
+ /// Whether the keystore is available, which requires a device passcode.
public func isKeystoreAvailable() -> Bool {
- // Try to create access control with passcode requirement
- // If this fails, it means no passcode is set
guard let accessControl = SecAccessControlCreateWithFlags(
nil,
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
@@ -386,7 +346,7 @@ extension VaultStore {
return false
}
- // Try a test keychain operation
+ // A test item under that access control tells whether a passcode is set.
let testKey = "test_keystore_availability"
let testData = Data([0x00])
let query: [String: Any] = [
@@ -398,28 +358,21 @@ extension VaultStore {
kSecAttrAccessControl as String: accessControl
]
- // Clean up any existing test item
SecItemDelete(query as CFDictionary)
-
- // Try to add - if it succeeds, keystore is available
let status = SecItemAdd(query as CFDictionary, nil)
-
- // Clean up test item
SecItemDelete(query as CFDictionary)
return status == errSecSuccess
}
- /// Store the Account Key in the keychain
+ /// Store the Account Key in the keychain behind biometrics.
internal func storeKeyInKeychain(_ keyData: Data) throws {
- // Check if keystore is available (device passcode must be set)
guard isKeystoreAvailable() else {
print("Cannot store key in keychain: device passcode not set")
throw AppError.biometricNotAvailable
}
- // Use .biometryCurrentSet to require biometric authentication only (no passcode fallback)
- // This also invalidates the key when biometrics are added/removed.
+ // .biometryCurrentSet requires biometrics (no passcode fallback) and invalidates the key when they change.
guard let accessControl = SecAccessControlCreateWithFlags(
nil,
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
@@ -446,7 +399,7 @@ extension VaultStore {
}
}
- /// Remove the encryption key from the keychain
+ /// Remove the Account Key from the keychain.
internal func removeKeyFromKeychain() throws {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
@@ -463,14 +416,12 @@ extension VaultStore {
// MARK: - Private Keychain Methods
- /// Retrieve the Account Key from the keychain
+ /// Retrieve the Account Key from the keychain behind a biometric prompt.
private func retrieveKeyFromKeychain(context: LAContext) throws -> Data {
- // Ensure interaction is allowed so system can prompt for biometric authentication
context.interactionNotAllowed = false
context.localizedReason = "Authenticate to unlock your vault"
- // Add a small delay to ensure the context is fully ready
- // This helps prevent race conditions where the biometric prompt doesn't show on first tap
+ // Without this delay the biometric prompt sometimes does not show on the first tap.
Thread.sleep(forTimeInterval: 0.05)
let query: [String: Any] = [
@@ -488,30 +439,25 @@ extension VaultStore {
guard status == errSecSuccess,
let keyData = result as? Data else {
- // Map keychain status codes to specific errors for better debugging
switch status {
case errSecUserCanceled:
throw AppError.biometricCancelled
case errSecAuthFailed:
throw AppError.biometricFailed
case errSecItemNotFound:
- // Key not found in keychain - user may need to re-login
print("Keychain item not found (errSecItemNotFound: \(status))")
throw AppError.keychainItemNotFound
case errSecInteractionNotAllowed:
- // Access denied - may happen if app is in background or screen is locked
+ // The app is in the background or the screen is locked.
print("Keychain interaction not allowed (errSecInteractionNotAllowed: \(status))")
throw AppError.keychainAccessDenied(status: status)
case errSecMissingEntitlement:
- // Missing keychain-access-groups entitlement or access group mismatch
print("Missing keychain entitlement (errSecMissingEntitlement: \(status))")
throw AppError.keychainAccessDenied(status: status)
case errSecDecode:
- // Data corruption or format issue
print("Keychain decode error (errSecDecode: \(status))")
throw AppError.keychainAccessDenied(status: status)
default:
- // Log the specific status code for debugging
print("Keychain error - status: \(status)")
throw AppError.keystoreKeyNotFound
}
diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
index 66a4debfa..d2367aa8c 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
@@ -39,7 +39,7 @@ using Microsoft.Extensions.Caching.Memory;
using SecureRemotePassword;
/// <summary>
-/// Auth controller for handling authentication.
+/// Login, registration, password change, session tokens, Login with Mobile and account deletion.
/// </summary>
/// <param name="dbContextFactory">AliasServerDbContext instance.</param>
/// <param name="userManager">UserManager instance.</param>
@@ -126,7 +126,6 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
var (user, serverSession, unlockMethodId, error) = await ValidateUserAndPassword(model);
if (error is not null)
{
- // Error occured during validation, return the error.
return error;
}
@@ -163,13 +162,11 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
var (user, serverSession, unlockMethodId, error) = await ValidateUserAndPassword(model);
if (error is not null)
{
- // Error occured during validation, return the error.
return error;
}
if (user == null || serverSession == null)
{
- // Expected variables are not set, return generic error.
return ApiError.Result(ApiErrorCode.USER_NOT_FOUND, 400);
}
@@ -211,13 +208,11 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
var (user, serverSession, unlockMethodId, error) = await ValidateUserAndPassword(model);
if (error is not null)
{
- // Error occured during validation, return the error.
return error;
}
if (user == null || serverSession == null)
{
- // Expected variables are not set, return generic error.
return ApiError.Result(ApiErrorCode.USER_NOT_FOUND, 400);
}
@@ -975,7 +970,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
return ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_EXPIRED, 410);
}
- // Sanity check: check if user exists using UserId FK
+ // The approving user must still exist, be unblocked and not locked out.
var user = await userManager.FindByIdAsync(loginRequest.UserId!);
if (user == null)
{
@@ -983,14 +978,12 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
return ApiError.Result(ApiErrorCode.USER_NOT_FOUND, 400);
}
- // Sanity check: check if the account is blocked.
if (user.Blocked)
{
await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.MobileLogin, AuthFailureReason.AccountBlocked);
return ApiError.Result(ApiErrorCode.ACCOUNT_BLOCKED, 400);
}
- // Sanity check: check if the account is locked out.
if (await userManager.IsLockedOutAsync(user))
{
await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.MobileLogin, AuthFailureReason.AccountLocked);
@@ -1079,7 +1072,6 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
{
await using var context = await dbContextFactory.CreateDbContextAsync();
- // Get the authenticated user
var user = await userManager.GetUserAsync(User);
if (user == null)
{
diff --git a/apps/server/Utilities/AliasVault.Cryptography/EmailEncryption.cs b/apps/server/Utilities/AliasVault.Cryptography/EmailEncryption.cs
index b6768f2e8..7cbb1d48f 100644
--- a/apps/server/Utilities/AliasVault.Cryptography/EmailEncryption.cs
+++ b/apps/server/Utilities/AliasVault.Cryptography/EmailEncryption.cs
@@ -18,15 +18,13 @@ public static class EmailEncryption
/// <summary>
/// Encrypt the email contents with a fresh symmetric key, encrypted once per recipient manifest's delivery key.
/// </summary>
- /// <param name="email">The plain text email object to encrypt.</param>
- /// <param name="deliveryKeys">The delivery keys of every manifest that claims the alias; each gets its own encrypted copy of the same symmetric key.</param>
- /// <returns>Email object with all sensitive fields encrypted.</returns>
+ /// <param name="email">The plaintext email.</param>
+ /// <param name="deliveryKeys">The delivery keys of every manifest that claims the alias.</param>
+ /// <returns>The email with every sensitive field encrypted.</returns>
public static Email EncryptEmail(Email email, IReadOnlyCollection<VaultManifestDeliveryKey> deliveryKeys)
{
- // Generate symmetric key for email encryption.
var symmetricKey = Encryption.GenerateRandomSymmetricKey();
- // Encrypt all email contents with the symmetric key.
if (email.MessageHtml is not null)
{
email.MessageHtml = Encryption.SymmetricEncrypt(email.MessageHtml, symmetricKey);
@@ -57,19 +55,18 @@ public static class EmailEncryption
email.FromLocal = Encryption.SymmetricEncrypt(email.FromLocal, symmetricKey);
email.FromDomain = Encryption.SymmetricEncrypt(email.FromDomain, symmetricKey);
- // Encrypt all attachments with the symmetric key.
foreach (var attachment in email.Attachments)
{
attachment.Bytes = Encryption.SymmetricEncrypt(attachment.Bytes, symmetricKey);
}
- // Encrypt the attachment bodies that were detached from the source with the same symmetric key.
+ // The attachment bodies detached from the source.
foreach (var part in email.Parts)
{
part.Bytes = Encryption.SymmetricEncrypt(part.Bytes, symmetricKey);
}
- // Encrypt the same symmetric key once per recipient manifest's delivery key.
+ // The symmetric key, once per recipient manifest's delivery key.
foreach (var deliveryKey in deliveryKeys)
{
var encryptedSymmetricKey = deliveryKey.Algorithm switch
diff --git a/apps/server/Utilities/AliasVault.Cryptography/Encryption.cs b/apps/server/Utilities/AliasVault.Cryptography/Encryption.cs
index ebcfd13de..546543ef2 100644
--- a/apps/server/Utilities/AliasVault.Cryptography/Encryption.cs
+++ b/apps/server/Utilities/AliasVault.Cryptography/Encryption.cs
@@ -30,17 +30,16 @@ public static class Encryption
public const string MobileLoginPayloadKeyLabel = "aliasvault/v1/mobile-login/payload-key";
/// <summary>
- /// Generates a random symmetric key for use with AES-256.
+ /// Generates a random AES-256 key.
/// </summary>
- /// <returns>A 256-bit (32-byte) random key as a byte array.</returns>
+ /// <returns>The 32-byte key.</returns>
public static byte[] GenerateRandomSymmetricKey()
{
- return RandomNumberGenerator.GetBytes(32); // 256 bits
+ return RandomNumberGenerator.GetBytes(32);
}
/// <summary>
- /// Encrypts a symmetric key for the holder of an RSA public key with RSA-OAEP-SHA256 and no label: the format every
- /// email key is stored in.
+ /// Encrypts a symmetric key for the holder of an RSA public key with RSA-OAEP-SHA256 and no label (every email key).
/// </summary>
/// <param name="symmetricKey">The symmetric key to encrypt.</param>
/// <param name="publicKey">The RSA public key in JWK format.</param>
@@ -52,7 +51,7 @@ public static class Encryption
/// <summary>
/// Encrypts a symmetric key for the holder of an RSA public key with RSA-OAEP-SHA256 under an OAEP label, which
- /// decryption must present as-is. An empty label is plain RSA-OAEP-SHA256.
+ /// decryption must present as-is.
/// </summary>
/// <param name="symmetricKey">The symmetric key to encrypt.</param>
/// <param name="publicKey">The RSA public key in JWK format.</param>
@@ -68,35 +67,33 @@ public static class Encryption
}
/// <summary>
- /// SymmetricEncrypt a plaintext string using AES-256 GCM.
+ /// Encrypts a UTF-8 string with AES-256-GCM.
/// </summary>
/// <param name="plaintext">The plaintext string.</param>
- /// <param name="key">Key to use for encryption (must be 32 bytes for AES-256).</param>
- /// <returns>The encrypted string (ciphertext).</returns>
+ /// <param name="key">The 32-byte key.</param>
+ /// <returns>Base64 of nonce | ciphertext | tag.</returns>
public static string SymmetricEncrypt(string plaintext, byte[] key)
{
- var encryptedBytes = SymmetricEncrypt(Encoding.UTF8.GetBytes(plaintext), key);
- return Convert.ToBase64String(encryptedBytes);
+ return Convert.ToBase64String(SymmetricEncrypt(Encoding.UTF8.GetBytes(plaintext), key));
}
/// <summary>
- /// SymmetricEncrypt a byte array using AES-256 GCM.
+ /// Encrypts bytes with AES-256-GCM (random 12-byte nonce, 16-byte tag, no AAD).
/// </summary>
- /// <param name="plainBytes">The plain byte array.</param>
- /// <param name="key">Key to use for encryption (must be 32 bytes for AES-256).</param>
- /// <returns>The encrypted string (ciphertext).</returns>
+ /// <param name="plainBytes">The plaintext bytes.</param>
+ /// <param name="key">The 32-byte key.</param>
+ /// <returns>nonce | ciphertext | tag.</returns>
public static byte[] SymmetricEncrypt(byte[] plainBytes, byte[] key)
{
- byte[] nonce = new byte[AesGcm.NonceByteSizes.MaxSize]; // 12 bytes
+ byte[] nonce = new byte[AesGcm.NonceByteSizes.MaxSize];
RandomNumberGenerator.Fill(nonce);
byte[] ciphertext = new byte[plainBytes.Length];
- byte[] tag = new byte[AesGcm.TagByteSizes.MaxSize]; // 16 bytes
+ byte[] tag = new byte[AesGcm.TagByteSizes.MaxSize];
using var aesGcm = new AesGcm(key, AesGcm.TagByteSizes.MaxSize);
aesGcm.Encrypt(nonce, plainBytes, ciphertext, tag);
- // Combine nonce + ciphertext + tag
byte[] result = new byte[nonce.Length + ciphertext.Length + tag.Length];
Buffer.BlockCopy(nonce, 0, result, 0, nonce.Length);
Buffer.BlockCopy(ciphertext, 0, result, nonce.Length, ciphertext.Length);
@@ -106,11 +103,11 @@ public static class Encryption
}
/// <summary>
- /// SymmetricDecrypt a ciphertext string using AES-256 GCM.
+ /// Decrypts base64 nonce | ciphertext | tag with AES-256-GCM into a UTF-8 string.
/// </summary>
- /// <param name="ciphertext">The encrypted string (ciphertext).</param>
- /// <param name="key">The key used to originally encrypt the string.</param>
- /// <returns>The original plaintext string.</returns>
+ /// <param name="ciphertext">The base64 ciphertext.</param>
+ /// <param name="key">The 32-byte key.</param>
+ /// <returns>The plaintext string.</returns>
public static string SymmetricDecrypt(string ciphertext, byte[] key)
{
var plainBytes = SymmetricDecrypt(Convert.FromBase64String(ciphertext), key);
@@ -118,11 +115,11 @@ public static class Encryption
}
/// <summary>
- /// SymmetricDecrypt a cipher byte array using AES-256 GCM.
+ /// Decrypts nonce | ciphertext | tag bytes with AES-256-GCM.
/// </summary>
- /// <param name="encryptedBytes">The encrypted byte array (cipherBytes).</param>
- /// <param name="key">The key used to originally encrypt the string.</param>
- /// <returns>The original plaintext string.</returns>
+ /// <param name="encryptedBytes">The encrypted bytes.</param>
+ /// <param name="key">The 32-byte key.</param>
+ /// <returns>The plaintext bytes.</returns>
public static byte[] SymmetricDecrypt(byte[] encryptedBytes, byte[] key)
{
int nonceSize = AesGcm.NonceByteSizes.MaxSize;
@@ -132,7 +129,6 @@ public static class Encryption
throw new CryptographicException("AES-GCM ciphertext is too short.");
}
- // Extract nonce, ciphertext, and tag
byte[] nonce = new byte[nonceSize];
byte[] tag = new byte[tagSize];
byte[] ciphertext = new byte[encryptedBytes.Length - nonceSize - tagSize];
diff --git a/apps/server/Utilities/AliasVault.Cryptography/Srp.cs b/apps/server/Utilities/AliasVault.Cryptography/Srp.cs
index 4c8afee06..d84cfe8e5 100644
--- a/apps/server/Utilities/AliasVault.Cryptography/Srp.cs
+++ b/apps/server/Utilities/AliasVault.Cryptography/Srp.cs
@@ -16,50 +16,39 @@ using SecureRemotePassword;
public static class Srp
{
/// <summary>
- /// Generate an ephemeral value for the server.
+ /// Generate the server's ephemeral pair for a verifier.
/// </summary>
- /// <param name="verifier">Verifier.</param>
- /// <returns>Ephemeral as string.</returns>
+ /// <param name="verifier">The account's verifier.</param>
+ /// <returns>The ephemeral pair.</returns>
public static SrpEphemeral GenerateEphemeralServer(string verifier)
{
- var server = new SrpServer();
- return server.GenerateEphemeral(verifier);
+ return new SrpServer().GenerateEphemeral(verifier);
}
/// <summary>
- /// Derive a shared session key on the server side.
+ /// Derive the server session, which checks the client's proof.
/// </summary>
- /// <param name="serverEphemeralSecret">serverEphemeralSecret.</param>
- /// <param name="clientEphemeralPublic">clientEphemeralPublic.</param>
- /// <param name="salt">Salt.</param>
- /// <param name="username">Username.</param>
- /// <param name="verifier">Verifier.</param>
- /// <param name="clientSessionProof">Client session proof.</param>
- /// <returns>SrpSession.</returns>
+ /// <param name="serverEphemeralSecret">The server's secret ephemeral.</param>
+ /// <param name="clientEphemeralPublic">The client's public ephemeral.</param>
+ /// <param name="salt">The account's salt.</param>
+ /// <param name="username">The SRP identity; lowercased, as SRP is case sensitive.</param>
+ /// <param name="verifier">The account's verifier.</param>
+ /// <param name="clientSessionProof">The client's session proof.</param>
+ /// <returns>The session, or null when the proof is wrong or malformed.</returns>
public static SrpSession? DeriveSessionServer(string serverEphemeralSecret, string clientEphemeralPublic, string salt, string username, string verifier, string clientSessionProof)
{
- // Make sure the username is lowercase as the SRP protocol is case sensitive.
- username = username.ToLowerInvariant();
-
try
{
- var server = new SrpServer();
- return server.DeriveSession(
- serverEphemeralSecret,
- clientEphemeralPublic,
- salt,
- username,
- verifier,
- clientSessionProof);
+ return new SrpServer().DeriveSession(serverEphemeralSecret, clientEphemeralPublic, salt, username.ToLowerInvariant(), verifier, clientSessionProof);
}
catch (System.Security.SecurityException)
{
- // Incorrect password provided, return null.
+ // Wrong password.
return null;
}
catch (FormatException)
{
- // Malformed (non-hexadecimal) ephemeral or proof provided, return null.
+ // Non-hexadecimal ephemeral or proof.
return null;
}
}
diff --git a/core/client/src/auth/MasterPasswordService.ts b/core/client/src/auth/MasterPasswordService.ts
index 2255c733b..d521d7110 100644
--- a/core/client/src/auth/MasterPasswordService.ts
+++ b/core/client/src/auth/MasterPasswordService.ts
@@ -147,7 +147,7 @@ export class MasterPasswordService {
await MasterPasswordService.assertSaltUnchanged(challenge.salt);
const current = await MasterPasswordService.answerSrpChallenge(challenge, currentPassword);
- await MasterPasswordService.adoptRaisedSettings(challenge, current.unlockKeyBase64, webApi);
+ await MasterPasswordService.refreshRaisedSettings(challenge, current.unlockKeyBase64, webApi);
const encryptedAccountKey = (await getPlatform().storage.get(StorageKeys.ENCRYPTED_ACCOUNT_KEY)) as string;
const next = await SrpAuthService.prepareNewPassword(newPassword, current.srpIdentity);
@@ -201,7 +201,7 @@ export class MasterPasswordService {
await MasterPasswordService.assertSaltUnchanged(challenge.salt);
const current = await MasterPasswordService.answerSrpChallenge(challenge, currentPassword);
- await MasterPasswordService.adoptRaisedSettings(challenge, current.unlockKeyBase64, webApi);
+ await MasterPasswordService.refreshRaisedSettings(challenge, current.unlockKeyBase64, webApi);
await MasterPasswordService.assertPasswordOpensChain(current.unlockKeyBase64);
const next = await SrpAuthService.prepareNewPassword(newPassword, current.srpIdentity);
@@ -232,7 +232,7 @@ export class MasterPasswordService {
* @param webApi - the API client to use
* @throws {IncorrectPasswordError} when the unlock key does not open the server's chain.
*/
- private static async adoptRaisedSettings(challenge: SrpChallenge, unlockKeyBase64: string, webApi: WebApiService): Promise<void> {
+ private static async refreshRaisedSettings(challenge: SrpChallenge, unlockKeyBase64: string, webApi: WebApiService): Promise<void> {
const stored = await MasterPasswordService.getStoredDerivationParams();
if (!stored || stored.encryptionSettings === challenge.encryptionSettings) {
return;
diff --git a/core/client/src/auth/SrpAuthService.ts b/core/client/src/auth/SrpAuthService.ts
index 0f6f93214..614b0087b 100644
--- a/core/client/src/auth/SrpAuthService.ts
+++ b/core/client/src/auth/SrpAuthService.ts
@@ -10,7 +10,7 @@ import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
import type { LegacySrpVerifierUpgrade, LoginResponse } from '@aliasvault/models/webapi';
/**
- * Register request type for creating a new user.
+ * The register request body: the SRP credentials and the account key hierarchy.
*/
export type RegisterRequest = AccountKeyBlobs & {
username: string;
@@ -31,7 +31,7 @@ export type PreparedRegistration = {
};
/**
- * SRP client proof type.
+ * The client's SRP proof as sent in a request body.
*/
export type SrpClientProof = {
clientPublicEphemeral: string;
@@ -39,8 +39,7 @@ export type SrpClientProof = {
};
/**
- * A client proof plus the session key it was derived with. The key stays client-side and is used to check the
- * server's proof, so it is kept apart from the proof that goes into the request body.
+ * A client proof plus the session key that checks the server's proof; the key never leaves the client.
*/
export type SrpClientSession = {
proof: SrpClientProof;
@@ -48,7 +47,7 @@ export type SrpClientSession = {
};
/**
- * Login credentials prepared from password derivation.
+ * What a password derives for a login.
*/
export type PreparedCredentials = {
/** The SRP password hash (uppercase hex) for the account's encryption type. */
@@ -93,118 +92,74 @@ export const DEFAULT_ENCRYPTION = {
} as const;
/**
- * SrpAuthService provides SRP-based authentication utilities using Rust WASM.
- *
- * This service handles:
- * - User registration with SRP protocol
- * - Password hashing and key derivation
- * - SRP verifier generation
- *
- * It uses the Rust core library compiled to WASM for cross-platform consistency.
- * The WASM module must be initialized before use (handled automatically).
+ * SRP registration, login proofs and unlock key derivation, on top of the Rust core.
*/
export class SrpAuthService {
/**
- * Normalizes a username by converting to lowercase and trimming whitespace.
- *
+ * Lowercases and trims a username.
* @param username - The username to normalize
- * @returns The normalized username
*/
public static normalizeUsername(username: string): string {
return username.toLowerCase().trim();
}
/**
- * Generates a cryptographically secure SRP salt using Rust WASM.
- *
- * @returns A random salt string (uppercase hex)
+ * A random SRP salt (uppercase hex).
*/
public static async generateSalt(): Promise<string> {
return rustCore().srpGenerateSalt();
}
/**
- * Derives an SRP private key from credentials using Rust WASM.
- *
+ * The SRP private key (uppercase hex).
* @param salt - The SRP salt
- * @param username - The normalized username or SRP identity
- * @param passwordHashString - The password hash as uppercase hex string
- * @returns The SRP private key (uppercase hex)
+ * @param username - The username or SRP identity
+ * @param passwordHashString - The SRP password hash (uppercase hex)
*/
- public static async derivePrivateKey(
- salt: string,
- username: string,
- passwordHashString: string
- ): Promise<string> {
+ public static async derivePrivateKey(salt: string, username: string, passwordHashString: string): Promise<string> {
return rustCore().srpDerivePrivateKey(salt, SrpAuthService.normalizeUsername(username), passwordHashString);
}
/**
- * Derives an SRP verifier from a private key using Rust WASM.
- *
+ * The SRP verifier (uppercase hex) of a private key.
* @param privateKey - The SRP private key
- * @returns The SRP verifier (uppercase hex)
*/
public static async deriveVerifier(privateKey: string): Promise<string> {
return rustCore().srpDeriveVerifier(privateKey);
}
/**
- * Generates an SRP ephemeral key pair for client-side authentication using Rust WASM.
- *
- * @returns Object containing public and secret ephemeral values (uppercase hex)
+ * A client ephemeral pair (uppercase hex).
*/
public static async generateEphemeral(): Promise<SrpEphemeral> {
return rustCore().srpGenerateEphemeral();
}
/**
- * Derives an SRP session from the authentication exchange using Rust WASM.
- *
+ * The client session (proof and key, uppercase hex) from the server's public ephemeral.
* @param clientSecretEphemeral - Client's secret ephemeral value
* @param serverPublicEphemeral - Server's public ephemeral value
* @param salt - The SRP salt
- * @param username - The normalized username or SRP identity
+ * @param username - The username or SRP identity
* @param privateKey - The SRP private key
- * @returns The SRP session containing proof and key (uppercase hex)
*/
- public static async deriveSession(
- clientSecretEphemeral: string,
- serverPublicEphemeral: string,
- salt: string,
- username: string,
- privateKey: string
- ): Promise<SrpSession> {
- return rustCore().srpDeriveSession(
- clientSecretEphemeral,
- serverPublicEphemeral,
- salt,
- SrpAuthService.normalizeUsername(username),
- privateKey
- );
+ public static async deriveSession(clientSecretEphemeral: string, serverPublicEphemeral: string, salt: string, username: string, privateKey: string): Promise<SrpSession> {
+ return rustCore().srpDeriveSession(clientSecretEphemeral, serverPublicEphemeral, salt, SrpAuthService.normalizeUsername(username), privateKey);
}
/**
- * Derives the client's SRP proof for one server-verified master password check.
- *
+ * 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 passwordHashString - The SRP password hash (uppercase hex)
* @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> {
+ public static async deriveClientProof(salt: string, srpIdentity: string, passwordHashString: string, serverEphemeral: string): Promise<SrpClientProof> {
return (await SrpAuthService.deriveClientSession(salt, srpIdentity, passwordHashString, serverEphemeral)).proof;
}
/**
- * Derives the client's SRP proof and the session key, for exchanges where the server's proof is checked.
- *
+ * The client's SRP proof and the session key, for exchanges where the server's proof is checked.
* @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
@@ -221,7 +176,6 @@ export class SrpAuthService {
/**
* Checks the server's session proof (M2), which confirms the server holds the verifier for this password.
- *
* @param session - The client session the request was sent with
* @param serverSessionProof - The server's proof from the validate response
* @throws {Error} when the proof does not match
@@ -234,22 +188,13 @@ export class SrpAuthService {
}
/**
- * Derives the client's SRP proof for a login initiate response.
- *
+ * The client's SRP proof and session key 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 proof to submit to the validate endpoint and the session key to verify the server's proof with
+ * @param username - The username typed by the user, the SRP identity fallback on older servers
+ * @param passwordHashString - The SRP password hash (uppercase hex)
*/
- public static async deriveLoginSession(
- loginResponse: LoginResponse,
- username: string,
- passwordHashString: string
- ): Promise<SrpClientSession> {
- /*
- * Use srpIdentity from server response if available, otherwise fall back to normalized username.
- * @todo Remove fallback after 0.26.0+ has been released.
- */
+ public static async deriveLoginSession(loginResponse: LoginResponse, username: string, passwordHashString: string): Promise<SrpClientSession> {
+ // LEGACY: servers before 0.26.0 send no SRP identity. TODO: remove the fallback once the minimum server is 0.26.0+.
const srpIdentity = loginResponse.srpIdentity ?? SrpAuthService.normalizeUsername(username);
return SrpAuthService.deriveClientSession(loginResponse.salt, srpIdentity, passwordHashString, loginResponse.serverEphemeral);
@@ -257,8 +202,7 @@ export class SrpAuthService {
/**
* Derive the unlock key (the Argon2id output, base64) from the password. Refuses settings weaker than those this
- * device already derived with, so a server cannot get a cheaper-to-guess login proof out of it.
- *
+ * device already derived with.
* @param password - The user's password
* @param salt - The account's salt
* @param encryptionSettings - The encryption settings JSON string
@@ -275,7 +219,6 @@ export class SrpAuthService {
/**
* Derive the unlock key from the password and the SRP password hash the account's encryption type makes from it.
- *
* @param password - The user's password
* @param salt - The salt from the server's challenge
* @param encryptionType - The encryption type from the server's challenge
@@ -289,7 +232,6 @@ export class SrpAuthService {
/**
* The SRP password hash (uppercase hex) an account's encryption type makes from an unlock key.
- *
* @param unlockKeyBase64 - The unlock key (base64), the Argon2id output of the password
* @param encryptionType - The encryption type from the server's challenge
* @returns The SRP password hash
@@ -300,11 +242,9 @@ export class SrpAuthService {
/**
* {@link prepareCredentials} for a login: an account that still has a legacy verifier also gets its upgrade.
- *
* @param password - The user's password
* @param loginResponse - The login initiate response
- * @param username - The username typed by the user, used as SRP identity fallback on older servers
- * @returns The credentials to log in with
+ * @param username - The username typed by the user, the SRP identity fallback on older servers
*/
public static async prepareLoginCredentials(password: string, loginResponse: LoginResponse, username: string): Promise<PreparedCredentials> {
const unlockKeyBase64 = await SrpAuthService.deriveUnlockKey(password, loginResponse.salt, loginResponse.encryptionSettings);
@@ -313,11 +253,9 @@ export class SrpAuthService {
/**
* The login credentials of an unlock key derived elsewhere (natively on mobile), see {@link prepareLoginCredentials}.
- *
* @param unlockKeyBase64 - The unlock key (base64), the Argon2id output of the password
* @param loginResponse - The login initiate response
- * @param username - The username typed by the user, used as SRP identity fallback on older servers
- * @returns The credentials to log in with
+ * @param username - The username typed by the user, the SRP identity fallback on older servers
*/
public static async loginCredentials(unlockKeyBase64: string, loginResponse: LoginResponse, username: string): Promise<PreparedCredentials> {
const credentials: PreparedCredentials = { passwordHashString: await SrpAuthService.srpPasswordHash(unlockKeyBase64, loginResponse.encryptionType), unlockKeyBase64 };
@@ -332,17 +270,15 @@ export class SrpAuthService {
}
/**
- * Generates a random UUID v4 for use as SRP identity.
- *
- * @returns A random UUID string
+ * A random UUID v4 as SRP identity.
*/
public static generateSrpIdentity(): string {
return crypto.randomUUID();
}
/**
- * Derive what a new master password needs: a fresh salt, the SRP verifier the server stores, and the unlock key
- * whose derived KEK wraps the client's key material. Uses the default Argon2Id settings.
+ * Derive what a new master password needs: a fresh salt, the SRP verifier and the unlock key, with the default
+ * Argon2id settings.
* @param password - the new master password
* @param srpIdentity - the account's SRP identity the verifier is bound to
*/
@@ -355,21 +291,12 @@ export class SrpAuthService {
}
/**
- * Prepares SRP registration data for a new user.
- *
- * This generates all the cryptographic values needed to register a user:
- * - Salt for key derivation
- * - Verifier for SRP authentication
- * - SRP identity (random GUID) for immutable authentication identity
- *
+ * Prepare a registration: a fresh salt, verifier and SRP identity, and the account key hierarchy.
* @param username - The username for registration
* @param password - The password for registration
- * @returns Registration request data ready to send to the API plus the generated key material
+ * @returns The request body plus the key material the client keeps
*/
- public static async prepareRegistration(
- username: string,
- password: string
- ): Promise<PreparedRegistration> {
+ public static async prepareRegistration(username: string, password: string): Promise<PreparedRegistration> {
const normalizedUsername = SrpAuthService.normalizeUsername(username);
const srpIdentity = SrpAuthService.generateSrpIdentity();
const material = await SrpAuthService.prepareNewPassword(password, srpIdentity);
diff --git a/core/client/src/auth/VaultKeyService.ts b/core/client/src/auth/VaultKeyService.ts
index b081d76b1..540263f19 100644
--- a/core/client/src/auth/VaultKeyService.ts
+++ b/core/client/src/auth/VaultKeyService.ts
@@ -1,7 +1,3 @@
-/**
- * VaultKeyService with client-side helpers for key operations.
- */
-
import { UnlockMethodType, VaultKeyAlgorithm, type VaultKeyGetResponse, type VaultKeyResponse } from '@aliasvault/models/webapi';
import { ApiRequestError } from '../api/errors/ApiRequestError';
@@ -42,7 +38,8 @@ export type SessionKeys = {
export type KeyChainKey = { unlockKey: string } | { accountKey: string };
/**
- * Static helper for fetching, caching and opening the account-key unlock chain (KEK → AK → VEK + account keypair).
+ * Fetches, caches and opens the account key chain: the KEK opens the Account Key, which opens the VEK and the account
+ * keypair.
*/
export class VaultKeyService {
/**
@@ -107,8 +104,9 @@ export class VaultKeyService {
}
/*
- * A device holding a vault under its unlock key but no chain yet (the account was upgraded on another device) stays
- * a legacy session: its first sync caches the chain and re-encrypts the stored vault under the VEK in one step.
+ * LEGACY: a device holding a vault under its unlock key but no chain yet (the account was upgraded on another device)
+ * stays a legacy session; its first sync caches the chain and re-encrypts the stored vault under the VEK.
+ * TODO: remove once every account has upgraded to 0.31.0+.
*/
if ('unlockKey' in key && !await VaultKeyService.hasLocalVaultKey() && await getPlatform().storage.get(StorageKeys.ENCRYPTED_VAULT) !== null) {
return key.unlockKey;
@@ -119,8 +117,7 @@ export class VaultKeyService {
}
/**
- * Check offline that the unlock key derived from the typed password opens the locally cached chain (an account not yet
- * upgraded has none; its unlock key is the vault key).
+ * Check offline that the unlock key derived from the typed password opens the locally cached chain.
* @param unlockKey - the unlock key derived from the typed password
* @returns The Account Key to store for this session.
* @throws Error with {@link AppErrorCode.UNLOCK_KEY_REJECTED} when the key does not open the chain (wrong password).
@@ -140,10 +137,8 @@ export class VaultKeyService {
}
/**
- * Whether this device holds a key chain, i.e. whether the account is on the account-key model rather than a
- * legacy account whose unlock key encrypts the vault directly. The cache is written on every login and cleared
- * when the server reports no vault key, so it needs no server round-trip. A false answer is only ever stale in
- * one direction (another device migrated since the last login), which the sync resolves by accepting the remote chain.
+ * Whether this device holds a key chain, i.e. the account is on the account-key model rather than a legacy account
+ * whose unlock key encrypts the vault directly.
*/
public static async hasLocalVaultKey(): Promise<boolean> {
const platform = getPlatform();
@@ -198,8 +193,8 @@ export class VaultKeyService {
}
}
/*
- * LEGACY: the session holds an unlock key from before the account had a key chain.
- * This legacy key conversion call can be removed once all clients have updated to 0.31.0+.
+ * LEGACY: the session holds an unlock key from before the account had a key chain. TODO: remove once all clients
+ * run 0.31.0+.
*/
const keys = await VaultKeyService.openKeyChain({ unlockKey: storedKey });
await convertLegacySessionKey(storedKey, keys.accountKey);
@@ -214,8 +209,7 @@ export class VaultKeyService {
}
/**
- * The account private key of the unlocked session (JWK string), or null when the vault is locked or
- * the account has no keypair yet (legacy account, not migrated to manifest-v1 yet). Used to decrypt shared-manifest VEK grants.
+ * The account private key of the unlocked session (JWK), or null when the vault is locked or the account has no keypair yet.
*/
public static async getSessionAccountPrivateKey(): Promise<string | null> {
return (await VaultKeyService.getSessionKeys())?.accountPrivateKey ?? null;
@@ -271,8 +265,7 @@ export class VaultKeyService {
}
/**
- * Walk a chain with the unlock key or the Account Key (the Rust `open_key_chain_with_unlock_key` and
- * `open_key_chain_with_account_key`).
+ * Walk a chain with the unlock key or the Account Key.
* @param key - the unlock key or the Account Key
* @param encryptedAccountKey - the Account Key encrypted with the KEK derived from the unlock key
* @param encryptedVek - the VEK encrypted with the Account Key
diff --git a/core/client/src/crypto/EncryptionUtility.ts b/core/client/src/crypto/EncryptionUtility.ts
index ad9938e25..9ad2b3387 100644
--- a/core/client/src/crypto/EncryptionUtility.ts
+++ b/core/client/src/crypto/EncryptionUtility.ts
@@ -4,11 +4,8 @@ import { base64ToBytes } from '../utilities/Base64';
const AES_GCM_IV_LENGTH = 12;
/**
- * The WebCrypto operations the web app and the browser extension run outside the Rust core, each for a reason:
- * - AES-256-GCM over the local vault blob and email fields: hardware accelerated, where wasm AES is not
- * (the format is the Rust `aes_gcm.rs` format)
- * - RSA-OAEP decryption of email keys with an imported non-extractable private key, at WebCrypto speed
- * Everything else (Argon2id, the key chain, RSA key pair generation, SRP, signing, PIN wrap) runs in the Rust core only.
+ * The WebCrypto operations the web app and browser extension run instead of calling the Rust core because of
+ * performance reasons (no hardware acceleration via Rust WASM). Same formats as `core/rust/src/crypto/aes_gcm.rs` and `rsa_oaep.rs`.
*/
export class EncryptionUtility {
/**
@@ -38,7 +35,7 @@ export class EncryptionUtility {
}
/**
- * Decrypts data using RSA-OAEP asymmetric encryption with a CryptoKey private key.
+ * Decrypts base64 RSA-OAEP ciphertext with an imported private key.
*/
public static async decryptWithPrivateKeyObject(ciphertext: string, privateKey: CryptoKey): Promise<Uint8Array> {
return new Uint8Array(await crypto.subtle.decrypt({ name: 'RSA-OAEP' }, privateKey, base64ToBytes(ciphertext)));
diff --git a/core/client/src/crypto/VaultBlob.ts b/core/client/src/crypto/VaultBlob.ts
index a2f1a3187..a8346e80f 100644
--- a/core/client/src/crypto/VaultBlob.ts
+++ b/core/client/src/crypto/VaultBlob.ts
@@ -1,6 +1,7 @@
/**
* The locally stored vault blob: AES-GCM over the raw bytes of the SQLite database.
- * Runs on WebCrypto for performance reasons because wasm AES-GCM has no hardware acceleration.
+ * WebCrypto re-implementation of Rust `core/rust/src/crypto/vault_blob.rs`, the base format, because AES-GCM in wasm
+ * runs without hardware acceleration.
* Other platform implementations: core/rust/src/crypto/vault_blob.rs (iOS and Android through uniffi).
*/
@@ -8,10 +9,7 @@ import { base64ToBytes, bytesToBase64 } from '../utilities/Base64';
import { EncryptionUtility } from './EncryptionUtility';
-/**
- * The bytes every SQLite database file begins with. They tell the two plaintext shapes apart with no version
- * marker: base64 text cannot start with them, since the space at index 6 is not in the base64 alphabet.
- */
+/** The bytes every SQLite database file begins with. Base64 text cannot start with them. */
const SQLITE_HEADER = new TextEncoder().encode('SQLite format 3\u0000');
/**
@@ -26,11 +24,6 @@ export async function encryptVaultBlob(sqliteBytes: Uint8Array, key: string): Pr
/**
* Decrypt a stored vault blob into the plaintext SQLite database.
- *
- * Reads both shapes: the database bytes this build writes, and the base64 text older builds wrote (which is
- * also what a server still on the sqlite-blob storage format serves). A vault in the older shape is converted
- * by the next write, so nothing has to migrate it up front. TODO: the base64 fallback can be removed
- * once all users have migrated to 0.31.0+.
* @param encryptedBlob - base64 of (IV | ciphertext | tag) as stored
* @param key - the symmetric key the vault is stored under
*/
@@ -40,7 +33,10 @@ export async function decryptVaultBlob(encryptedBlob: string, key: string): Prom
return plaintext;
}
- // LEGACY: the plaintext is base64 text of the database.
+ /*
+ * LEGACY: builds before 0.31.0 stored the base64 text of the database, so a plaintext without the SQLite header is
+ * decoded as base64. TODO: remove once every vault has been written by 0.31.0+.
+ */
return base64ToBytes(new TextDecoder().decode(plaintext));
}
diff --git a/core/client/src/email/EmailDecryption.ts b/core/client/src/email/EmailDecryption.ts
index 3f3f447fe..3709c2299 100644
--- a/core/client/src/email/EmailDecryption.ts
+++ b/core/client/src/email/EmailDecryption.ts
@@ -1,14 +1,7 @@
/**
- * Email decryption logic.
- *
- * 1. Pick the email's decryption key whose public key the caller holds ({@link resolveSymmetricKey}).
- * 2. Unwrap the email's symmetric key with that keypair's RSA-OAEP-256 private key.
- * 3. Decrypt the header fields, the message source and attachments with AES-256-GCM (`IV | ciphertext | tag`).
- * 4. Hand the decrypted source to the Rust email parser for the bodies and attachment list.
- *
- * The crypto primitives run on WebCrypto in the browser extension and web app, which is about 10x faster than the Rust
- * core compiled to WebAssembly for RSA and for large sources. The mobile app has no WebCrypto and uses the native Rust
- * core (core/rust/src/crypto) instead. Both produce and read the same formats.
+ * Email decryption: the email's symmetric key is decrypted with the matching RSA-OAEP-256 private key, the fields and
+ * source with AES-256-GCM, and the Rust email parser reads the source. Runs on WebCrypto where the host has it (web app
+ * and browser extension) and on the Rust core otherwise (mobile).
*/
import { EncryptionUtility } from '../crypto/EncryptionUtility';
import { devWarn } from '../platform/Logger';
@@ -72,11 +65,8 @@ export async function decryptEmail(email: Email, encryptionKeys: EncryptionKey[]
}
/**
- * Decrypts the header fields of a page of mailbox emails. The publicKeys table is the one the API sent alongside the
- * emails; each email's decryption keys reference it by index.
- *
- * Emails that cannot be decrypted are skipped rather than failing the batch. The server only serves mail the caller
- * holds a key for, so this should not happen, but one unreadable record must not break the whole list view.
+ * Decrypts the header fields of a page of mailbox emails; each email's decryption keys name a public key by index into
+ * `publicKeys`. An email that does not decrypt is skipped, so one unreadable record does not break the list.
*/
export async function decryptEmailList(emails: MailboxEmail[], publicKeys: string[], encryptionKeys: EncryptionKey[]): Promise<MailboxEmail[]> {
const results = await Promise.all(emails.map(async (email): Promise<MailboxEmail | null> => {
@@ -118,9 +108,7 @@ export function clearEmailKeyCache(): void {
}
/**
- * The email's symmetric key (base64), unwrapped from the first decryption key whose public key the caller holds. A
- * decryption key names its public key by index into the response's publicKeys table, so the email's own list of
- * decryption keys is not aligned with the caller's keys.
+ * The email's symmetric key (base64), decrypted from the first decryption key whose public key the caller holds.
*/
async function resolveSymmetricKey(decryptionKeys: EmailDecryptionKey[], publicKeys: string[], encryptionKeys: EncryptionKey[]): Promise<string> {
for (const decryptionKey of decryptionKeys) {
@@ -134,22 +122,18 @@ async function resolveSymmetricKey(decryptionKeys: EmailDecryptionKey[], publicK
throw new Error('Encryption key not found');
}
-/*
- * Crypto primitives: WebCrypto where the host has it, the native Rust core otherwise (mobile).
- */
-
/** Imported non-extractable RSA private keys, by public key, so a page of emails imports each keypair once. */
const privateKeyCache = new Map<string, Promise<CryptoKey>>();
/**
- * Whether the host has WebCrypto; the mobile app (Hermes) has none.
+ * Whether the host has WebCrypto; the mobile app has none.
*/
function hasWebCrypto(): boolean {
return typeof crypto !== 'undefined' && typeof crypto.subtle?.importKey === 'function';
}
/**
- * RSA-OAEP-256 decrypt an email's symmetric key with the keypair's private key. Returns the key as base64.
+ * Decrypt an email's symmetric key with the keypair's RSA-OAEP-256 private key. Returns the key as base64.
*/
async function unwrapSymmetricKey(encryptedSymmetricKey: string, encryptionKey: EncryptionKey): Promise<string> {
if (!hasWebCrypto()) {
diff --git a/core/client/src/items/FaviconService.ts b/core/client/src/items/FaviconService.ts
index 350c0ad8a..5d46daa91 100644
--- a/core/client/src/items/FaviconService.ts
+++ b/core/client/src/items/FaviconService.ts
@@ -19,14 +19,14 @@ export type FaviconStore = {
};
/**
- * Favicon API calls.
+ * The part of the API client the favicon fetch needs.
*/
export type FaviconApi = {
post<TRequest, TResponse>(endpoint: string, data: TRequest): Promise<TResponse>;
};
/**
- * Result of a favicon fetch operation.
+ * Result of a favicon fetch.
*/
export type FaviconFetchResult = {
success: boolean;
@@ -39,10 +39,7 @@ export type FaviconFetchResult = {
* Options for a favicon fetch.
*/
export type FaviconFetchOptions = {
- /**
- * Fetch even when the vault already holds a favicon for the domain. Set for an explicit re-fetch,
- * where the point is to replace a favicon that has gone stale.
- */
+ /** Fetch even when the vault already holds a favicon for the domain (an explicit re-fetch). */
ignoreStored?: boolean;
/** Timeout in milliseconds (default: 5000ms). */
@@ -50,12 +47,12 @@ export type FaviconFetchOptions = {
};
/**
- * Default timeout for favicon fetch operations (5 seconds).
+ * Default timeout of a favicon fetch.
*/
const FAVICON_FETCH_TIMEOUT_MS = 5000;
/**
- * Centralized service for favicon/logo operations, shared by every client.
+ * Favicon lookup and fetching, shared by every client.
*/
export class FaviconService {
/**
@@ -78,18 +75,15 @@ export class FaviconService {
}
/**
- * Fetch the favicon for a resolved target from the server API.
- * Includes deduplication check and timeout handling.
+ * Fetch the favicon of a resolved target from the server, unless the vault already holds one for its domain.
* @param target The favicon target to fetch
- * @param logos The vault's logo repository, for the deduplication check
- * @param webApi The WebAPI service for making the request
+ * @param logos The vault's logo repository
+ * @param webApi The API client
* @param options Optional fetch options
- * @returns FaviconFetchResult with success status and image data
*/
public static async fetchFavicon(target: FaviconTarget, logos: FaviconStore, webApi: FaviconApi, options: FaviconFetchOptions = {}): Promise<FaviconFetchResult> {
const timeoutMs = options.timeoutMs ?? FAVICON_FETCH_TIMEOUT_MS;
- // Check if logo already exists (deduplication)
if (!options.ignoreStored && await logos.hasFaviconForSource(target.source)) {
return { success: false, skipped: true };
}
@@ -109,7 +103,6 @@ export class FaviconService {
return { success: false, error: 'No favicon returned from server' };
} catch (err) {
- // Favicon extraction failed or timed out - not critical
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
logExpected('[Favicon] Extracting the favicon failed', errorMessage);
return { success: false, error: errorMessage };
@@ -119,17 +112,14 @@ export class FaviconService {
}
/**
- * Fetch and attach a favicon to an item if needed.
- * @param item The item to potentially update with a logo
- * @param urlFieldValue The value of the URL field (can be string or string[])
- * @param logos The vault's logo repository, for the deduplication check
- * @param webApi The WebAPI service for making the request
- * @returns The updated item with Logo attached (if favicon was fetched), or cleared when nothing was fetched
+ * The item with the favicon of its URL as Logo, or without a Logo when none was fetched.
+ * @param item The item to update
+ * @param urlFieldValue The value of the URL field (single string or multi-value array)
+ * @param logos The vault's logo repository
+ * @param webApi The API client
*/
public static async fetchAndAttachFavicon(item: Item, urlFieldValue: string | string[] | undefined | null, logos: FaviconStore, webApi: FaviconApi): Promise<Item> {
const target = await FaviconService.resolveTarget(urlFieldValue);
-
- // No valid URL found: clear any existing logo.
if (!target) {
return { ...item, Logo: undefined };
}
diff --git a/core/rust/src/crypto/aad.rs b/core/rust/src/crypto/aad.rs
index c04192ea7..46fb77b29 100644
--- a/core/rust/src/crypto/aad.rs
+++ b/core/rust/src/crypto/aad.rs
@@ -1,8 +1,5 @@
//! Associated data for ciphertext to bind it to the slot it belongs in.
-/// Versions the AAD label scheme, not the API or the vault format: this should not be bumped to match either.
-const PREFIX: &str = "aliasvault/v1";
-
/// The Account Key under the KEK.
pub const ACCOUNT_KEY: &[u8] = b"aliasvault/v1/account-key";
@@ -23,38 +20,37 @@ pub const MOBILE_LOGIN_PAYLOAD_KEY: &[u8] = b"aliasvault/v1/mobile-login/payload
/// A manifest payload under its manifest's VEK.
pub fn manifest(manifest_id: &str) -> Vec<u8> {
- format!("{}/manifest/{}", PREFIX, normalize(manifest_id)).into_bytes()
+ format!("aliasvault/v1/manifest/{}", normalize(manifest_id)).into_bytes()
}
/// A data bucket payload under its manifest's VEK.
pub fn bucket(manifest_id: &str, category: &str) -> Vec<u8> {
- format!("{}/bucket/{}/{}", PREFIX, normalize(manifest_id), category).into_bytes()
+ format!("aliasvault/v1/bucket/{}/{}", normalize(manifest_id), category).into_bytes()
}
/// A shared manifest's name under its manifest's VEK.
pub fn manifest_name(manifest_id: &str) -> Vec<u8> {
- format!("{}/manifest-name/{}", PREFIX, normalize(manifest_id)).into_bytes()
+ format!("aliasvault/v1/manifest-name/{}", normalize(manifest_id)).into_bytes()
}
/// A blob's bytes under its own blob key.
pub fn blob_data(manifest_id: &str, hash: &str) -> Vec<u8> {
- format!("{}/blob/{}/{}", PREFIX, normalize(manifest_id), normalize(hash)).into_bytes()
+ format!("aliasvault/v1/blob/{}/{}", normalize(manifest_id), normalize(hash)).into_bytes()
}
/// A blob key under its manifest's VEK.
pub fn blob_key(manifest_id: &str, hash: &str) -> Vec<u8> {
- format!("{}/blob-key/{}/{}", PREFIX, normalize(manifest_id), normalize(hash)).into_bytes()
+ format!("aliasvault/v1/blob-key/{}/{}", normalize(manifest_id), normalize(hash)).into_bytes()
}
-/// The RSA-OAEP label of a grant: a manifest's VEK encrypted for one recipient key. The recipient is not in the label,
-/// since only the matching private key can decrypt the grant anyway.
+/// The RSA-OAEP label of a grant: a manifest's VEK encrypted for one recipient key.
pub fn grant(manifest_id: &str) -> Vec<u8> {
- format!("{}/grant/{}", PREFIX, normalize(manifest_id)).into_bytes()
+ format!("aliasvault/v1/grant/{}", normalize(manifest_id)).into_bytes()
}
/// The RSA-OAEP label of a shared manifest's name encrypted into an invitation for its recipient.
pub fn invitation_name(manifest_id: &str) -> Vec<u8> {
- format!("{}/invitation-name/{}", PREFIX, normalize(manifest_id)).into_bytes()
+ format!("aliasvault/v1/invitation-name/{}", normalize(manifest_id)).into_bytes()
}
/// An id as it appears in a label: lowercased, as the server prints a GUID.
diff --git a/core/rust/src/crypto/argon2.rs b/core/rust/src/crypto/argon2.rs
index f8d0ba20b..b047f3239 100644
--- a/core/rust/src/crypto/argon2.rs
+++ b/core/rust/src/crypto/argon2.rs
@@ -8,9 +8,9 @@ use zeroize::Zeroizing;
const ARGON2_OUTPUT_LENGTH: usize = 32;
/*
- * The weakest Argon2id parameters a client accepts from the server, to prevent KDF downgrade scenarios issued by the server.
- * The minimum parameters reflect the defaults of the first public release (0.9.0), which accounts keep until a password change
- * in 0.31.0+.
+ * The weakest Argon2id parameters a client accepts from the server, to prevent a KDF downgrade by the server. They match the
+ * defaults of the first public release (0.9.0). Clients from 0.32.0 upgrade older accounts at login, so this floor can be
+ * raised once all users run 0.32.0+.
*/
const MIN_MEMORY_KIB: u32 = 19456;
const MIN_ITERATIONS: u32 = 2;
diff --git a/core/rust/src/crypto/mod.rs b/core/rust/src/crypto/mod.rs
index 101232a10..0d623f3c4 100644
--- a/core/rust/src/crypto/mod.rs
+++ b/core/rust/src/crypto/mod.rs
@@ -1,20 +1,4 @@
-//! Cryptographic modules used by the clients. Every AAD string and RSA-OAEP label lives in [`aad`].
-//!
-//! - [`aad`]: the associated-data and OAEP-label registry that binds each ciphertext to its slot.
-//! - [`aes_gcm`]: AES-256-GCM (`aes-gcm`), random 96-bit nonce, `IV | ciphertext | tag`; every vault payload and every key encrypted with another key.
-//! - [`argon2`]: Argon2id (`argon2`) with a parameter floor; turns the master password into the unlock key.
-//! - [`avex`]: the .avex encrypted vault export, a JSON header and the .avux bytes under AES-256-GCM with an Argon2id key of the export password.
-//! - `jwk`: RSA keys to and from JWK JSON (`rsa`), for the OAEP keys and the RS256 passkey keys.
-//! - [`key_chain`]: HKDF-SHA256 (`hkdf`) KEK and SRP input from the unlock key; KEK > Account Key > VEK, private keys.
-//! - [`mobile_login`]: SHA-256 public key hash and verification code of the mobile login (QR unlock) handshake.
-//! - [`pin`]: PIN unlock: the key the host stores, encrypted with AES-256-GCM under an Argon2id key of the PIN, with the failed-attempt policy.
-//! - [`rsa_oaep`]: RSA-2048 OAEP-SHA256 (`rsa`, blinded decryption); grants, invitation names and delivery keys.
-//! - [`signing`]: Ed25519 (`ed25519-dalek`) account signatures over grants, public keys and invitation names.
-//! - [`srp`]: SRP-6a client (`srp`, SHA-256, 2048-bit group); login without sending the password.
-//! - [`tokens`]: the algorithm, key-type and KDF tokens stored or sent on the wire.
-//! - [`vault_blob`]: the locally stored vault, AES-256-GCM over the SQLite database bytes.
-//!
-//! Randomness comes from `getrandom` via `common::rng`; `rsa` and `p256` use `rand_core` `OsRng`.
+//! Cryptographic modules used by the clients.
pub mod aad;
pub mod aes_gcm;
diff --git a/core/rust/src/crypto/pin.rs b/core/rust/src/crypto/pin.rs
index 559663ce0..1eaa01e12 100644
--- a/core/rust/src/crypto/pin.rs
+++ b/core/rust/src/crypto/pin.rs
@@ -38,8 +38,6 @@ pub fn pin_generate_salt() -> Vec<u8> {
}
/// The salt the browser extension derives its PIN key with: the UTF-8 characters of base64(`salt` || SHA-256(`extension_id`)).
-///
-/// The base64 characters are hashed, not the bytes they decode to: every extension PIN ever set was derived that way.
pub fn pin_extension_salt(salt: &[u8], extension_id: &str) -> Vec<u8> {
let mut combined = salt.to_vec();
combined.extend_from_slice(&Sha256::digest(extension_id.as_bytes()));
diff --git a/core/rust/src/crypto/rsa_oaep.rs b/core/rust/src/crypto/rsa_oaep.rs
index 98f87d19d..1da88f603 100644
--- a/core/rust/src/crypto/rsa_oaep.rs
+++ b/core/rust/src/crypto/rsa_oaep.rs
@@ -1,4 +1,4 @@
-//! RSA-OAEP (SHA-256) with keys carried as JWK JSON strings compatible with the WebCrypto API.
+//! RSA-OAEP (SHA-256) with keys carried as JWK JSON strings.
use rsa::traits::PublicKeyParts;
use rsa::{BigUint, Oaep, RsaPrivateKey, RsaPublicKey};
diff --git a/core/rust/src/crypto/signing.rs b/core/rust/src/crypto/signing.rs
index db157129d..368aea268 100644
--- a/core/rust/src/crypto/signing.rs
+++ b/core/rust/src/crypto/signing.rs
@@ -1,7 +1,4 @@
//! Ed25519 account signing keys, which let a client check what another client published.
-//!
-//! A signature always covers a [`signed_message`]: a fixed label plus length-prefixed fields, so a signature made for
-//! one purpose never verifies for another. The server builds the same bytes to check signatures.
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey, PUBLIC_KEY_LENGTH, SECRET_KEY_LENGTH, SIGNATURE_LENGTH};
use serde::{Deserialize, Serialize};
diff --git a/core/rust/src/crypto/srp.rs b/core/rust/src/crypto/srp.rs
index eb70a9669..aa4fc0493 100644
--- a/core/rust/src/crypto/srp.rs
+++ b/core/rust/src/crypto/srp.rs
@@ -1,9 +1,7 @@
//! SRP-6a (Secure Remote Password), client side only; the server side lives in the .NET API.
//!
//! Uses RustCrypto `srp` crate for most operations, except certain places
-//! where the format must stay compatible with the `SecureRemotePassword` .NET package
-//! used by the API server and the `secure-remote-password` library used in the JS test suite.
-//! `tests/srp.rs` carries a server side of the handshake to test the client-server flow locally.
+//! where the format must stay compatible with the `SecureRemotePassword` .NET package used by the API server.
use num_bigint::BigUint;
use serde::{Deserialize, Serialize};
@@ -177,7 +175,7 @@ pub fn srp_verify_session(client_public: &str, client_proof: &str, session_key:
}
/*
- * Wire format primitives that deviate from the `srp` crate on purpose: the SecureRemotePassword (.NET/JS) format hashes
+ * Wire format primitives that deviate from the `srp` crate on purpose: the SecureRemotePassword (.NET) format hashes
* the padded premaster secret into K and uses the RFC 2945 M1, while the crate uses raw S and M1 = H(A|B|S).
*/
diff --git a/core/rust/src/crypto/tokens.rs b/core/rust/src/crypto/tokens.rs
index b75493053..636201bc6 100644
--- a/core/rust/src/crypto/tokens.rs
+++ b/core/rust/src/crypto/tokens.rs
@@ -1,4 +1,4 @@
-//! Const tokens that name an algorithm, key type or KDF; each is stored or sent as-is and never changes.
+//! String constants for algorithm, key type and encryption type fields, stored and sent to the server as-is.
/// AES-256-GCM: the algorithm every Account Key and personal VEK is encrypted with (VaultKeyAlgorithm).
pub const ALGORITHM_AES256_GCM: &str = "aes256-gcm";
diff --git a/core/rust/src/crypto/vault_blob.rs b/core/rust/src/crypto/vault_blob.rs
index cbaf753a3..cca53341b 100644
--- a/core/rust/src/crypto/vault_blob.rs
+++ b/core/rust/src/crypto/vault_blob.rs
@@ -1,7 +1,7 @@
//! The locally stored vault blob: base64 of AES-256-GCM `IV | ciphertext | tag` (no AAD) over the SQLite database bytes.
//!
-//! The mobile apps call these through uniffi. The web app and the browser extension keep their own WebCrypto copy
-//! (`core/client/src/crypto/VaultBlob.ts`) because wasm AES-GCM has no hardware acceleration.
+//! This is the base format; the mobile apps call it through uniffi. The web app and browser extension use a WebCrypto
+//! native re-implementation (`core/client/src/crypto/VaultBlob.ts`) for performance reasons.
use crate::common::encoding::{base64_decode, base64_encode};
use crate::common::error::{VaultError, VaultResult};
@@ -16,13 +16,15 @@ pub fn vault_blob_encrypt(sqlite_bytes: &[u8], key_base64: &str) -> VaultResult<
Ok(base64_encode(&aes_gcm::encrypt(sqlite_bytes, key_base64, &[])?))
}
-/// Decrypt a stored vault blob into the SQLite database bytes. Also reads the base64 text of the database that builds
-/// before 0.31.0 stored; the next write converts such a vault.
+/// Decrypt a stored vault blob into the SQLite database bytes.
pub fn vault_blob_decrypt(encrypted_blob: &str, key_base64: &str) -> VaultResult<Vec<u8>> {
let plaintext = aes_gcm::decrypt(&base64_decode(encrypted_blob.trim())?, key_base64, &[])?;
if plaintext.starts_with(SQLITE_HEADER) {
return Ok(plaintext);
}
+
+ // LEGACY: builds before 0.31.0 stored the base64 text of the database, so a plaintext without the SQLite header is
+ // decoded as base64. TODO: remove once every vault has been written by 0.31.0+.
let not_a_database = || VaultError::General("vault blob plaintext is neither a database nor base64 text".to_string());
let text = String::from_utf8(plaintext).map_err(|_| not_a_database())?;
base64_decode(text.trim()).map_err(|_| not_a_database())
diff --git a/core/rust/src/vault_sync/legacy.rs b/core/rust/src/vault_sync/legacy.rs
index 420fc75d9..bf02ec118 100644
--- a/core/rust/src/vault_sync/legacy.rs
+++ b/core/rust/src/vault_sync/legacy.rs
@@ -1,5 +1,5 @@
//! LEGACY: what old sqlite-blob accounts need, including their one-time upgrade from sqlite-blob to manifest-v1
-//! ([`upgrade_account_to_manifest_v1`]). Remove this module once every account has upgraded, together with the
+//! ([`upgrade_account_to_manifest_v1`]). TODO: remove this module once every account has upgraded, together with the
//! `Snapshot::LegacySqliteBlob` arm in `pull.rs` and `merge.rs`, `db::schema_state`'s frozen chain check, the
//! branch without a vault key in `migration::migrate_manifest` and the upgrade-elsewhere check in `migration::migration_status`.