Skip to content

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

Update mobile app Rust core interface (#776)

Leendert de Borst7d8f949ca3d5
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
index 371da2ea7..cc0a1ac97 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
@@ -1920,4 +1920,38 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
promise.reject("ERR_SRP_DERIVE_SESSION", "Failed to derive SRP session: ${e.message}", e)
}
}
+
+ /**
+ * Generate a password or passphrase from a JSON-serialized PasswordSettings object.
+ * The "Type" field selects the generator ("basic" or "diceware").
+ * @param settingsJson The JSON-serialized password settings.
+ * @param promise The promise to resolve with the generated password/passphrase.
+ */
+ @ReactMethod
+ override fun generatePassword(settingsJson: String, promise: Promise) {
+ try {
+ val password = uniffi.aliasvault_core.generatePassword(settingsJson)
+ promise.resolve(password)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error generating password", e)
+ promise.reject("ERR_GENERATE_PASSWORD", "Failed to generate password: ${e.message}", e)
+ }
+ }
+
+ /**
+ * List the bundled Diceware wordlist language codes (first is the default, English).
+ * @param promise The promise to resolve with the array of language codes.
+ */
+ @ReactMethod
+ override fun getDicewareLanguages(promise: Promise) {
+ try {
+ val languages = uniffi.aliasvault_core.getDicewareLanguages()
+ val result = Arguments.createArray()
+ languages.forEach { result.pushString(it) }
+ promise.resolve(result)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error getting diceware languages", e)
+ promise.reject("ERR_GET_DICEWARE_LANGUAGES", "Failed to get diceware languages: ${e.message}", e)
+ }
+ }
}
diff --git a/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx b/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx
index 311808b00..9ad50dc2d 100644
--- a/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx
@@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next';
import { StyleSheet, View, KeyboardAvoidingView, Platform } from 'react-native';
import type { DeleteAccountInitiateRequest, DeleteAccountInitiateResponse, DeleteAccountRequest } from '@/utils/dist/core/models/webapi';
+import { SrpUtility } from '@/utils/SrpUtility';
import { useColors } from '@/hooks/useColorScheme';
@@ -19,7 +20,6 @@ import { UsernameDisplay } from '@/components/ui/UsernameDisplay';
import { useApp } from '@/context/AppContext';
import { useDialog } from '@/context/DialogContext';
import { useWebApi } from '@/context/WebApiContext';
-import NativeVaultManager from '@/specs/NativeVaultManager';
/**
* Delete account screen.
@@ -165,22 +165,18 @@ export default function DeleteAccountScreen(): React.ReactNode {
// Convert base64 string to hex string
const currentPasswordHashString = Buffer.from(currentPasswordHashBase64, 'base64').toString('hex').toUpperCase();
- // Generate client ephemeral and session using native SRP
- const newClientEphemeral = await NativeVaultManager.srpGenerateEphemeral();
-
- const privateKey = await NativeVaultManager.srpDerivePrivateKey(currentSalt, srpIdentity, currentPasswordHashString);
- const newClientSession = await NativeVaultManager.srpDeriveSession(
- newClientEphemeral.secret,
- currentServerEphemeral,
+ // Derive the SRP client proof to authenticate the deletion with the server.
+ const clientProof = await SrpUtility.deriveClientProof(
currentSalt,
srpIdentity,
- privateKey
+ currentPasswordHashString,
+ currentServerEphemeral
);
const deleteAccountRequest: DeleteAccountRequest = {
username: username,
- clientPublicEphemeral: newClientEphemeral.public,
- clientSessionProof: newClientSession.proof,
+ clientPublicEphemeral: clientProof.clientPublicEphemeral,
+ clientSessionProof: clientProof.clientSessionProof,
};
setLoadingStatus(t('settings.securitySettings.deleteAccount.deletingAccount'));
diff --git a/apps/mobile-app/hooks/useVaultMutate.ts b/apps/mobile-app/hooks/useVaultMutate.ts
index cbf9bac36..323eaa6cd 100644
--- a/apps/mobile-app/hooks/useVaultMutate.ts
+++ b/apps/mobile-app/hooks/useVaultMutate.ts
@@ -8,6 +8,7 @@ import type { EncryptionKeyDerivationParams } from '@/utils/dist/core/models/met
import type { PasswordChangeInitiateResponse, Vault, VaultPasswordChangeRequest } from '@/utils/dist/core/models/webapi';
import { FieldKey, getFieldValue } from '@/utils/dist/core/models/vault';
import EncryptionUtility from '@/utils/EncryptionUtility';
+import { SrpUtility } from '@/utils/SrpUtility';
import { useVaultSync } from '@/hooks/useVaultSync';
@@ -189,8 +190,6 @@ export function useVaultMutate() : {
// Convert base64 string to hex string
const currentPasswordHashString = Buffer.from(currentPasswordHashBase64, 'base64').toString('hex').toUpperCase();
- // Generate client ephemeral and session using native SRP
- const newClientEphemeral = await NativeVaultManager.srpGenerateEphemeral();
// Get username from the auth context, always lowercase and trimmed which is required for the argon2id key derivation
const username = authContext.username?.toLowerCase().trim();
if (!username) {
@@ -200,19 +199,19 @@ export function useVaultMutate() : {
/**
* Use srpIdentity from server response if available, otherwise fall back to username.
* Note: the fallback can be removed in the future after 0.26.0+ is deployed.
- */
+ */
const srpIdentity = data.srpIdentity ?? username;
- const privateKey = await NativeVaultManager.srpDerivePrivateKey(currentSalt, srpIdentity, currentPasswordHashString);
- const newClientSession = await NativeVaultManager.srpDeriveSession(
- newClientEphemeral.secret,
- currentServerEphemeral,
+
+ // Derive the SRP client proof for the current password to authorize the change.
+ const currentClientProof = await SrpUtility.deriveClientProof(
currentSalt,
srpIdentity,
- privateKey
+ currentPasswordHashString,
+ currentServerEphemeral
);
// Generate salt and verifier for new password using native SRP
- const newSalt = await NativeVaultManager.srpGenerateSalt();
+ const newSalt = await SrpUtility.generateSalt();
const newPasswordHash = await EncryptionUtility.deriveKeyFromPassword(newPasswordPlainText, newSalt, data.encryptionType, data.encryptionSettings);
const newPasswordHashString = Buffer.from(newPasswordHash).toString('hex').toUpperCase();
@@ -242,9 +241,8 @@ export function useVaultMutate() : {
await authContext.logout(t('common.errors.unknownErrorTryAgain'));
}
- // Generate SRP password change data using native SRP
- const newPrivateKey = await NativeVaultManager.srpDerivePrivateKey(newSalt, srpIdentity, newPasswordHashString);
- const newVerifier = await NativeVaultManager.srpDeriveVerifier(newPrivateKey);
+ // Generate SRP password change data (verifier for the new password) using native SRP
+ const newVerifier = await SrpUtility.deriveVerifier(newSalt, srpIdentity, newPasswordHashString);
// Prepare vault for password change
const vault = await prepareVaultForPasswordChange();
@@ -253,8 +251,8 @@ export function useVaultMutate() : {
// Convert default vault object to password change vault object
const passwordChangeVault : VaultPasswordChangeRequest = {
...vault,
- currentClientPublicEphemeral: newClientEphemeral.public,
- currentClientSessionProof: newClientSession.proof,
+ currentClientPublicEphemeral: currentClientProof.clientPublicEphemeral,
+ currentClientSessionProof: currentClientProof.clientSessionProof,
newPasswordSalt: newSalt,
newPasswordVerifier: newVerifier
};
diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
index 775671b24..02c4c5c83 100644
--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
@@ -331,6 +331,16 @@
[vaultManager scanQRCode:prefixes statusText:statusText resolver:resolve rejecter:reject];
}
+// MARK: - Password Generator
+
+- (void)generatePassword:(NSString *)settingsJson resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager generatePassword:settingsJson resolver:resolve rejecter:reject];
+}
+
+- (void)getDicewareLanguages:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager getDicewareLanguages:resolve rejecter:reject];
+}
+
// MARK: - SRP (Secure Remote Password) Operations
- (void)srpGenerateSalt:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index 828581d7e..9d972a257 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -1283,6 +1283,30 @@ public class VaultManager: NSObject {
resolve(nil)
}
+ // MARK: - Password Generator
+
+ /// Generate a password or passphrase from a JSON-serialized PasswordSettings object.
+ /// The "Type" field selects the generator ("basic" or "diceware").
+ @objc
+ func generatePassword(_ settingsJson: String,
+ resolver resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ do {
+ let password = try RustCoreFramework.generatePassword(settingsJson: settingsJson)
+ resolve(password)
+ } catch {
+ reject("PASSWORD_GENERATOR_ERROR", "Failed to generate password: \(error.localizedDescription)", error)
+ }
+ }
+
+ /// List the bundled Diceware wordlist language codes (first is the default, English).
+ @objc
+ func getDicewareLanguages(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ let languages = RustCoreFramework.getDicewareLanguages()
+ resolve(languages)
+ }
+
// MARK: - SRP (Secure Remote Password) Operations
/// Generate a cryptographic salt for SRP.
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index 0431cf35e..d8334f578 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -135,6 +135,12 @@ export interface Spec extends TurboModule {
// statusText is the message to display on the scanner screen (defaults to "Scan QR code" if null/empty).
scanQRCode(prefixes: string[] | null, statusText: string | null): Promise<string | null>;
+ // Password generator (uses the native Rust core, shared with the other AliasVault clients)
+ // Generate a password or passphrase from a JSON-serialized PasswordSettings object.
+ generatePassword(settingsJson: string): Promise<string>;
+ // List the bundled Diceware wordlist language codes (first is the default, English).
+ getDicewareLanguages(): Promise<string[]>;
+
// SRP (Secure Remote Password) operations
// These methods use the native Rust SRP implementation for secure authentication.
// All hex values are uppercase strings.
diff --git a/apps/mobile-app/utils/PasswordGeneratorUtility.ts b/apps/mobile-app/utils/PasswordGeneratorUtility.ts
new file mode 100644
index 000000000..ad5fdafae
--- /dev/null
+++ b/apps/mobile-app/utils/PasswordGeneratorUtility.ts
@@ -0,0 +1,53 @@
+/**
+ * Typed wrapper around the native Rust core for password/passphrase generation.
+ */
+import NativeVaultManager from '@/specs/NativeVaultManager';
+import { resolveDefaultLanguage } from '@/utils/dist/core/models/defaults';
+import type { PasswordSettings } from '@/utils/dist/core/models/vault';
+
+/**
+ * Generate a password or passphrase from the given settings.
+ *
+ * @param settings The password settings.
+ * @param seed Optional 64-character hex RNG seed for deterministic generation.
+ * @returns The generated password/passphrase.
+ */
+export async function generatePassword(settings: PasswordSettings, seed?: string): Promise<string> {
+ const effective = await applyEffectiveDicewareLanguage(settings);
+ const payload = seed ? { ...effective, Seed: seed } : effective;
+ return NativeVaultManager.generatePassword(JSON.stringify(payload));
+}
+
+/**
+ * Resolve the effective Diceware passphrase language when none is explicitly chosen.
+ *
+ * @param settings The password settings.
+ * @returns The settings with a concrete Diceware language when one needed resolving.
+ */
+async function applyEffectiveDicewareLanguage(settings: PasswordSettings): Promise<PasswordSettings> {
+ if (settings.Type !== 'diceware' || (settings.Language && settings.Language.trim().length > 0)) {
+ return settings;
+ }
+ const codes = await getDicewareLanguages();
+ const { default: i18n } = await import('@/i18n');
+ return { ...settings, Language: resolveDefaultLanguage(i18n.language, codes) };
+}
+
+/**
+ * Get the list of bundled Diceware wordlist language ISO codes (first is the default, English/'en').
+ * @returns The available language codes.
+ */
+export async function getDicewareLanguages(): Promise<string[]> {
+ const languages = await NativeVaultManager.getDicewareLanguages();
+ return languages.length > 0 ? languages : ['en'];
+}
+
+/**
+ * Generate a random 32-byte seed as a 64-character hex string, suitable for the `seed` argument.
+ * @returns A 64-character hex string.
+ */
+export function generateSeed(): string {
+ const bytes = new Uint8Array(32);
+ crypto.getRandomValues(bytes);
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
+}
diff --git a/apps/mobile-app/utils/SrpUtility.ts b/apps/mobile-app/utils/SrpUtility.ts
index edcc99d49..b04f56c69 100644
--- a/apps/mobile-app/utils/SrpUtility.ts
+++ b/apps/mobile-app/utils/SrpUtility.ts
@@ -3,6 +3,15 @@ import { ApiAuthError } from '@/utils/types/errors/ApiAuthError';
import { WebApiService } from '@/utils/WebApiService';
import NativeVaultManager from '@/specs/NativeVaultManager';
+/**
+ * An SRP client proof for authenticating against the server: the client public ephemeral
+ * and the session proof (M1), both uppercase hex strings.
+ */
+export type SrpClientProof = {
+ clientPublicEphemeral: string;
+ clientSessionProof: string;
+};
+
/**
* Utility class for SRP login and validation operations.
* Uses native Rust SRP implementation via NativeVaultManager.
@@ -17,6 +26,64 @@ export class SrpUtility {
this.webApiService = webApiService;
}
+ /**
+ * Derive an SRP client proof to authenticate against the server with the current password.
+ *
+ * Wraps the native Rust SRP primitives (generate ephemeral, derive private key, derive session)
+ * that are shared used in multiple places.
+ *
+ * @param salt The user's SRP salt (uppercase hex).
+ * @param identity The SRP identity (srpIdentity from the server, or the username).
+ * @param passwordHashHex The Argon2id-derived password hash as uppercase hex.
+ * @param serverEphemeral The server's public ephemeral from the initiate response.
+ * @returns The client public ephemeral and session proof to send to the server.
+ */
+ public static async deriveClientProof(
+ salt: string,
+ identity: string,
+ passwordHashHex: string,
+ serverEphemeral: string
+ ): Promise<SrpClientProof> {
+ const clientEphemeral = await NativeVaultManager.srpGenerateEphemeral();
+ const privateKey = await NativeVaultManager.srpDerivePrivateKey(salt, identity, passwordHashHex);
+ const session = await NativeVaultManager.srpDeriveSession(
+ clientEphemeral.secret,
+ serverEphemeral,
+ salt,
+ identity,
+ privateKey
+ );
+ return {
+ clientPublicEphemeral: clientEphemeral.public,
+ clientSessionProof: session.proof,
+ };
+ }
+
+ /**
+ * Generate a fresh 32-byte SRP salt as an uppercase hex string (for a new/changed password).
+ * @returns The generated salt.
+ */
+ public static async generateSalt(): Promise<string> {
+ return NativeVaultManager.srpGenerateSalt();
+ }
+
+ /**
+ * Derive the SRP verifier for a (new) password: the value the server stores to authenticate
+ * future logins. Used when registering or changing a password.
+ * @param salt The salt the new password hash was derived against (uppercase hex).
+ * @param identity The SRP identity (srpIdentity from the server, or the username).
+ * @param passwordHashHex The Argon2id-derived password hash as uppercase hex.
+ * @returns The SRP verifier (uppercase hex).
+ */
+ public static async deriveVerifier(
+ salt: string,
+ identity: string,
+ passwordHashHex: string
+ ): Promise<string> {
+ const privateKey = await NativeVaultManager.srpDerivePrivateKey(salt, identity, passwordHashHex);
+ return NativeVaultManager.srpDeriveVerifier(privateKey);
+ }
+
/**
* Initiates the login process with the server
*/
@@ -55,14 +122,11 @@ export class SrpUtility {
*/
const srpIdentity = loginResponse.srpIdentity ?? username;
- const clientEphemeral = await NativeVaultManager.srpGenerateEphemeral();
- const privateKey = await NativeVaultManager.srpDerivePrivateKey(loginResponse.salt, srpIdentity, passwordHash);
- const sessionProof = await NativeVaultManager.srpDeriveSession(
- clientEphemeral.secret,
- loginResponse.serverEphemeral,
+ const clientProof = await SrpUtility.deriveClientProof(
loginResponse.salt,
srpIdentity,
- privateKey
+ passwordHash,
+ loginResponse.serverEphemeral
);
const response = await this.webApiService.rawFetch('Auth/validate', {
@@ -73,8 +137,8 @@ export class SrpUtility {
body: JSON.stringify({
username: username.toLowerCase().trim(),
rememberMe,
- clientPublicEphemeral: clientEphemeral.public,
- clientSessionProof: sessionProof.proof,
+ clientPublicEphemeral: clientProof.clientPublicEphemeral,
+ clientSessionProof: clientProof.clientSessionProof,
}),
});
@@ -105,21 +169,18 @@ export class SrpUtility {
*/
const srpIdentity = loginResponse.srpIdentity ?? username;
- const clientEphemeral = await NativeVaultManager.srpGenerateEphemeral();
- const privateKey = await NativeVaultManager.srpDerivePrivateKey(loginResponse.salt, srpIdentity, passwordHash);
- const sessionProof = await NativeVaultManager.srpDeriveSession(
- clientEphemeral.secret,
- loginResponse.serverEphemeral,
+ const clientProof = await SrpUtility.deriveClientProof(
loginResponse.salt,
srpIdentity,
- privateKey
+ passwordHash,
+ loginResponse.serverEphemeral
);
const model: ValidateLoginRequest2Fa = {
username: username.toLowerCase().trim(),
rememberMe,
- clientPublicEphemeral: clientEphemeral.public,
- clientSessionProof: sessionProof.proof,
+ clientPublicEphemeral: clientProof.clientPublicEphemeral,
+ clientSessionProof: clientProof.clientSessionProof,
code2Fa: twoFactorCode,
};
diff --git a/apps/mobile-app/utils/db/repositories/SettingsRepository.ts b/apps/mobile-app/utils/db/repositories/SettingsRepository.ts
index ec10b10e3..8bf714b2b 100644
--- a/apps/mobile-app/utils/db/repositories/SettingsRepository.ts
+++ b/apps/mobile-app/utils/db/repositories/SettingsRepository.ts
@@ -1,5 +1,5 @@
import type { EncryptionKey, PasswordSettings, TotpCode, Attachment } from '@/utils/dist/core/models/vault';
-import { DEFAULT_PASSWORD_LENGTH } from '@/utils/dist/core/models/defaults';
+import { DEFAULT_PASSWORD_LENGTH, DEFAULT_WORD_COUNT } from '@/utils/dist/core/models/defaults';
import { BaseRepository } from '../BaseRepository';
@@ -115,7 +115,14 @@ export class SettingsRepository extends BaseRepository {
UseUppercase: true,
UseNumbers: true,
UseSpecialChars: true,
- UseNonAmbiguousChars: false
+ UseNonAmbiguousChars: false,
+ Type: 'basic',
+ WordCount: DEFAULT_WORD_COUNT,
+ // Empty = "auto": the passphrase language is resolved from the app language at runtime.
+ Language: '',
+ Capitalization: 'Lowercase',
+ Separator: 'Dash',
+ Salt: 'None'
};
try {
@@ -129,6 +136,15 @@ export class SettingsRepository extends BaseRepository {
return defaultSettings;
}
+ /**
+ * Persist the password generator settings as a JSON blob.
+ * Mirrors the `PasswordGenerationSettings` key used by the other AliasVault clients.
+ * @param settings - The password settings to store.
+ */
+ public async setPasswordSettings(settings: PasswordSettings): Promise<void> {
+ await this.updateSetting('PasswordGenerationSettings', JSON.stringify(settings));
+ }
+
/**
* Fetch all encryption keys.
* @returns Array of encryption keys