Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Move login with mobile crypto verification code logic to Rust core
Leendert de Borsta16c776aeff4
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex b28643365..fc4d60a0a 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -5,7 +5,6 @@ import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/Vauimport { WebApiService } from '@aliasvault/client/api/WebApiService';import { MasterPasswordService } from '@aliasvault/client/auth/MasterPasswordService';import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';-import { EncryptionUtility } from '@aliasvault/client/crypto/EncryptionUtility';import { decryptVaultBlob, encryptVaultBlob } from '@aliasvault/client/crypto/VaultBlob';import { isSameItem, manifestForItemIn, scopedKey, type ItemRef } from '@aliasvault/client/database/ItemRef';import { SqliteClient } from '@aliasvault/client/database/SqliteClient';@@ -13,7 +12,7 @@ import { FaviconService } from '@aliasvault/client/items/FaviconService';import { applySearchFilter } from '@aliasvault/client/items/ItemFilters';import { generateTotpCode } from '@aliasvault/client/items/TotpUtility';import { getOrCreateDeviceId } from '@aliasvault/client/platform/DeviceId';-import { filterItems, AutofillMatchingMode, extractRootDomain, isUrlAlreadyLinked } from '@aliasvault/client/rust/RustCore';+import { filterItems, AutofillMatchingMode, extractRootDomain, isUrlAlreadyLinked, rustCore } from '@aliasvault/client/rust/RustCore';import { sharingText } from '@aliasvault/client/sharing/SharingView';import { clearDirtyScopes, getDirtyScopes } from '@aliasvault/client/sync/VaultDirtyState';import { vaultRequiresManifestMigration, VaultMigrationKind } from '@aliasvault/client/sync/VaultManifestMigration';@@ -21,6 +20,7 @@ import { type VaultMutationScope, DEFAULT_VAULT_MUTATION_SCOPE, hasUserVisibleScimport { hasSyncError, syncResult, VaultSync, type FullVaultSyncResult, type SharedManifestDetails, type SharingOperationResult, type VaultManifestMigrationResult } from '@aliasvault/client/sync/VaultSync';import { type EmailClaimTransfer, type IVaultSyncEngineHost, type VaultSyncOptions, type VaultSyncPhase as EngineSyncPhase, type VaultSyncStoreOutcome, type VaultSyncStoreRequest } from '@aliasvault/client/sync/VaultSyncEngine';import { getVaultSyncHoldReason } from '@aliasvault/client/sync/VaultSyncHold';+import { bytesToBase64 } from '@aliasvault/client/utilities/Base64';import { FieldKey, ItemTypes, createSystemField, getFieldValue, itemToCredential, normalizeTotpPeriod, type Credential, type Item } from '@aliasvault/models/vault';import { clearAllSavePromptState, handleGetLastAutofilled, handleStoreLastAutofilled, isRelatedDomain } from '@/entrypoints/background/SavePromptStateHandler';@@ -562,10 +562,7 @@ export async function handlePersistFormValues(data: any): Promise<void> {// Always stringify the data properlyconst serializedData = JSON.stringify(data);- const encryptedData = await EncryptionUtility.symmetricEncrypt(- serializedData,- encryptionKey- );+ const encryptedData = bytesToBase64(await rustCore().symmetricEncryptBytes(new TextEncoder().encode(serializedData), encryptionKey));await storage.setItem(StorageKeys.PERSISTED_FORM_VALUES, encryptedData);}@@ -582,10 +579,7 @@ export async function handleGetPersistedFormValues(): Promise<any | null> {}try {- const decryptedData = await EncryptionUtility.symmetricDecrypt(- encryptedData,- encryptionKey- );+ const decryptedData = await rustCore().symmetricDecrypt(encryptedData, encryptionKey);return JSON.parse(decryptedData);} catch (error) {logFailure('Failed to decrypt or parse persisted form values', error);diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.ktindex 152226a6a..27d20019a 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt@@ -24,6 +24,8 @@ import uniffi.aliasvault_core.getIdentityLanguagesimport uniffi.aliasvault_core.getSyncableTableNamesimport uniffi.aliasvault_core.isRelatedOriginAllowedimport uniffi.aliasvault_core.isRpIdAllowedForHost+import uniffi.aliasvault_core.mobileLoginPublicKeyHash+import uniffi.aliasvault_core.mobileLoginVerificationCodeimport uniffi.aliasvault_core.openAccountKeyChainimport uniffi.aliasvault_core.parseEmailSourceimport uniffi.aliasvault_core.reencryptAccountKeyJson@@ -89,6 +91,8 @@ object RustCoreDispatcher {"symmetricDecrypt" -> json(symmetricDecrypt(args.string(0), args.string(1)))"symmetricDecryptBytes" -> json(symmetricDecryptBytes(args.bytes(0), args.string(1)))"symmetricEncryptBytes" -> json(symmetricEncryptBytes(args.bytes(0), args.string(1)))+ "mobileLoginPublicKeyHash" -> json(mobileLoginPublicKeyHash(args.string(0)))+ "mobileLoginVerificationCode" -> json(mobileLoginVerificationCode(args.string(0)))"argon2DeriveKey" -> json(argon2DeriveKey(args.string(0), args.string(1), args.string(2)))"deriveSrpPasswordHash" -> json(deriveSrpPasswordHash(args.bytes(0), args.string(1)))diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.ktindex 39cbdd92b..5e0b455de 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt@@ -25,7 +25,6 @@ import java.util.Dateimport java.util.UUIDimport kotlin.coroutines.resumeimport uniffi.aliasvault_core.decryptManifestInvitationName as rustDecryptManifestInvitationName-import uniffi.aliasvault_core.vaultBlobDecrypt as rustVaultBlobDecrypt/*** The vault store that manages the encrypted vault and all input/output operations on it.@@ -332,15 +331,10 @@ class VaultStore(// Derive the unlock key from the password and open the chain; a wrong password fails to open it.val derivedKey = crypto.deriveKeyFromPassword(password, salt, encryptionType, encryptionSettings)- val vaultEncryptionKey = crypto.openAccountKeyChain(derivedKey).vaultEncryptionKey-- // Try to decrypt the vault to verify the password is correct- rustVaultBlobDecrypt(database.getEncryptedDatabase(), vaultEncryptionKey)-- // If decryption succeeded, return the unlock key as base64+ crypto.openAccountKeyChain(derivedKey)android.util.Base64.encodeToString(derivedKey, android.util.Base64.NO_WRAP)} catch (e: Exception) {- // Password incorrect or decryption failed - intentionally return null+ // Password incorrect or the key chain did not open - intentionally return null// We don't log the error as this is expected when password is incorrectnull}diff --git a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swiftindex 303274884..b27296fa7 100644--- a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift+++ b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift@@ -1579,6 +1579,8 @@ private enum RustCoreDispatcher {case "symmetricDecrypt": return try json(try RustCoreFramework.symmetricDecrypt(base64Ciphertext: try args.string(0), keyBase64: try args.string(1)))case "symmetricDecryptBytes": return try json(bytes: try RustCoreFramework.symmetricDecryptBytes(encrypted: try args.data(0), keyBase64: try args.string(1)))case "symmetricEncryptBytes": return try json(bytes: try RustCoreFramework.symmetricEncryptBytes(plaintext: try args.data(0), keyBase64: try args.string(1)))+ case "mobileLoginPublicKeyHash": return try json(RustCoreFramework.mobileLoginPublicKeyHash(publicKeyJwk: try args.string(0)))+ case "mobileLoginVerificationCode": return try json(RustCoreFramework.mobileLoginVerificationCode(publicKeyJwk: try args.string(0)))case "argon2DeriveKey":return try json(bytes: try RustCoreFramework.argon2DeriveKey(password: try args.string(0), salt: try args.string(1), encryptionSettings: try args.string(2)))diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swiftindex f3a57bf1f..52893a29c 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift@@ -174,18 +174,10 @@ extension VaultStore {// 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)- let vaultEncryptionKey = try openAccountKeyChain(with: derivedKey).vaultEncryptionKey-- // Try to decrypt the vault to verify the password is correct- guard let encryptedDbBase64 = getEncryptedDatabase() else {- return nil- }- _ = try RustCoreFramework.vaultBlobDecrypt(encryptedBlob: encryptedDbBase64, key: vaultEncryptionKey)-- // If decryption succeeded, return the unlock key as base64+ _ = try openAccountKeyChain(with: derivedKey)return derivedKey.base64EncodedString()} catch {- // Password incorrect or decryption failed+ // Password incorrect or the key chain did not openreturn nil}}diff --git a/apps/mobile-app/package-lock.json b/apps/mobile-app/package-lock.jsonindex 0aeadbde3..ee1c79b83 100644--- a/apps/mobile-app/package-lock.json+++ b/apps/mobile-app/package-lock.json@@ -15,7 +15,6 @@"@aliasvault/vault": "file:../../core/vault","@expo/vector-icons": "^15.0.2","@hookform/resolvers": "^5.0.1",- "@noble/hashes": "^2.4.0","@react-native-async-storage/async-storage": "2.2.0","@react-native-community/slider": "5.2.0","@types/jsrsasign": "^10.5.15",@@ -2833,18 +2832,6 @@"@emnapi/runtime": "^1.7.1"}},- "node_modules/@noble/hashes": {- "version": "2.4.0",- "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz",- "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==",- "license": "MIT",- "engines": {- "node": ">= 20.19.0"- },- "funding": {- "url": "https://paulmillr.com/funding/"- }- },"node_modules/@nodable/entities": {"version": "3.1.0","resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-3.1.0.tgz",diff --git a/apps/mobile-app/package.json b/apps/mobile-app/package.jsonindex 7238bf0d4..9d8e3784a 100644--- a/apps/mobile-app/package.json+++ b/apps/mobile-app/package.json@@ -33,7 +33,6 @@"@aliasvault/vault": "file:../../core/vault","@expo/vector-icons": "^15.0.2","@hookform/resolvers": "^5.0.1",- "@noble/hashes": "^2.4.0","@react-native-async-storage/async-storage": "2.2.0","@react-native-community/slider": "5.2.0","@types/jsrsasign": "^10.5.15",diff --git a/apps/mobile-app/platform/CryptoPolyfill.ts b/apps/mobile-app/platform/CryptoPolyfill.tsindex 6831a1e02..375ba9739 100644--- a/apps/mobile-app/platform/CryptoPolyfill.ts+++ b/apps/mobile-app/platform/CryptoPolyfill.ts@@ -1,14 +1,12 @@import 'react-native-get-random-values';-import { sha256 } from '@noble/hashes/sha2.js';/*- * The part of Web Crypto the client core calls that Hermes lacks: randomUUID and the SHA-256 digest.+ * The part of Web Crypto the client core calls that Hermes lacks: randomUUID.* getRandomValues comes from react-native-get-random-values.*/type MobileCrypto = {getRandomValues<T extends ArrayBufferView | null>(array: T): T;randomUUID?: () => string;- subtle?: { digest: (algorithm: AlgorithmIdentifier, data: BufferSource) => Promise<ArrayBuffer> };};const mobileCrypto = globalThis.crypto as unknown as MobileCrypto;@@ -24,17 +22,4 @@ function randomUUID(): string {return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;}-/**- * The SHA-256 digest of `data`; other algorithms are not supported.- */-async function digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise<ArrayBuffer> {- const name = typeof algorithm === 'string' ? algorithm : algorithm.name;- if (name.toUpperCase() !== 'SHA-256') {- throw new Error(`Unsupported digest algorithm: ${name}`);- }- const bytes = ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : new Uint8Array(data);- return sha256(bytes).buffer as ArrayBuffer;-}-mobileCrypto.randomUUID ??= randomUUID;-mobileCrypto.subtle ??= { digest };diff --git a/apps/mobile-app/platform/NativeRustCore.ts b/apps/mobile-app/platform/NativeRustCore.tsindex ebcbe9d5b..cbc52700f 100644--- a/apps/mobile-app/platform/NativeRustCore.ts+++ b/apps/mobile-app/platform/NativeRustCore.ts@@ -73,6 +73,8 @@ export const nativeRustCore: IRustCore = {rsaDecrypt: (base64Ciphertext, privateKeyJwk) => callForBytes('rsaDecrypt', base64Ciphertext, privateKeyJwk),decryptManifestInvitationName: () => notImplementedOnMobile('decryptManifestInvitationName', 'the account private key stays in the native VaultStore, use NativeVaultManager.decryptManifestInvitationName'),accountSigningKeyFingerprint: () => notImplementedOnMobile('accountSigningKeyFingerprint', 'the Account Key stays in the native VaultStore, use NativeVaultManager.getSigningKeyFingerprint'),+ mobileLoginPublicKeyHash: (publicKeyJwk) => call('mobileLoginPublicKeyHash', publicKeyJwk),+ mobileLoginVerificationCode: (publicKeyJwk) => call('mobileLoginVerificationCode', publicKeyJwk),pinGenerateSalt: () => notImplementedOnMobile('pinGenerateSalt', PIN_IS_NATIVE),pinEncrypt: () => notImplementedOnMobile('pinEncrypt', PIN_IS_NATIVE),diff --git a/apps/web/src/utils/WebAuthnService.ts b/apps/web/src/utils/WebAuthnService.tsindex ab5c30fc3..c588e6a0f 100644--- a/apps/web/src/utils/WebAuthnService.ts+++ b/apps/web/src/utils/WebAuthnService.ts@@ -1,7 +1,7 @@import { AppErrorCode, extractErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';-import { EncryptionUtility } from '@aliasvault/client/crypto/EncryptionUtility';import { getPlatform } from '@aliasvault/client/platform';+import { rustCore } from '@aliasvault/client/rust/RustCore';import { base64ToBytes, bytesToBase64 } from '@aliasvault/client/utilities/Base64';import { getLocalPreference, removeLocalPreference, setLocalPreference } from '@/utils/LocalPreferences';@@ -136,7 +136,7 @@ export const WebAuthnService = {const credential = await createCredentialDerivedKey(username);setLocalPreference(KEYS.credentialId, credential.credentialId);setLocalPreference(KEYS.salt, credential.salt);- setLocalPreference(KEYS.encryptedAccountKey, await EncryptionUtility.symmetricEncrypt(accountKey, credential.derivedKey));+ setLocalPreference(KEYS.encryptedAccountKey, bytesToBase64(await rustCore().symmetricEncryptBytes(new TextEncoder().encode(accountKey), credential.derivedKey)));setLocalPreference(KEYS.enabled, 'true');},@@ -161,7 +161,7 @@ export const WebAuthnService = {throw new Error('WebAuthn encrypted encryption key is not set or WebAuthn credential ID is not set.');}const derivedKey = await getCredentialDerivedKey(credentialId, salt);- const accountKey = await EncryptionUtility.symmetricDecrypt(encrypted, derivedKey);+ const accountKey = await rustCore().symmetricDecrypt(encrypted, derivedKey);try {await VaultKeyService.verifyUnlockKey(accountKey);} catch (error) {diff --git a/core/client/src/auth/MobileLoginProtocol.ts b/core/client/src/auth/MobileLoginProtocol.tsindex f55671f22..681648587 100644--- a/core/client/src/auth/MobileLoginProtocol.ts+++ b/core/client/src/auth/MobileLoginProtocol.ts@@ -1,4 +1,4 @@-import { bytesToBase64Url } from '../utilities/Base64';+import { rustCore } from '../rust/RustCore';/*** What the QR code of a mobile login request carries.@@ -15,6 +15,7 @@ export type MobileLoginQrPayload = {export class MobileLoginProtocol {public static readonly QR_PREFIX = 'aliasvault://open/mobile-unlock/';+ /** Matches `VERIFICATION_CODE_DIGITS` in `core/rust/src/crypto/mobile_login.rs`. */public static readonly VERIFICATION_CODE_LENGTH = 2;/** RSA-OAEP label of the Account Key the mobile app encrypts; matches `MOBILE_LOGIN_ACCOUNT_KEY` in `core/rust/src/crypto/aad.rs`. */@@ -23,8 +24,6 @@ export class MobileLoginProtocol {/** RSA-OAEP label of the payload key the server encrypts; matches `MOBILE_LOGIN_PAYLOAD_KEY` in `core/rust/src/crypto/aad.rs`. */public static readonly PAYLOAD_KEY_LABEL = 'aliasvault/v1/mobile-login/payload-key';- private static readonly VERIFICATION_CODE_CONTEXT = 'AliasVault.MobileLogin.VerificationCode.v1:';-private static readonly REQUEST_ID_PATTERN = /^[0-9a-f]{32}$/;private static readonly PUBLIC_KEY_HASH_PATTERN = /^[A-Za-z0-9_-]{43}$/;@@ -33,18 +32,14 @@ export class MobileLoginProtocol {* SHA-256 hash of the public key JWK string, base64url encoded without padding (43 characters).*/public static async computePublicKeyHash(publicKeyJwk: string): Promise<string> {- const digest = await MobileLoginProtocol.sha256(publicKeyJwk);- return bytesToBase64Url(digest);+ return rustCore().mobileLoginPublicKeyHash(publicKeyJwk);}/*** The verification code for a public key: a fixed number of digits, zero padded.*/public static async computeVerificationCode(publicKeyJwk: string): Promise<string> {- const digest = await MobileLoginProtocol.sha256(MobileLoginProtocol.VERIFICATION_CODE_CONTEXT + publicKeyJwk);- const value = new DataView(digest.buffer, digest.byteOffset, 4).getUint32(0, false);- const modulus = 10 ** MobileLoginProtocol.VERIFICATION_CODE_LENGTH;- return (value % modulus).toString().padStart(MobileLoginProtocol.VERIFICATION_CODE_LENGTH, '0');+ return rustCore().mobileLoginVerificationCode(publicKeyJwk);}/**@@ -85,11 +80,4 @@ export class MobileLoginProtocol {return { requestId, publicKeyHash };}-- /**- * SHA-256 of a UTF-8 string.- */- private static async sha256(data: string): Promise<Uint8Array> {- return new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(data)));- }}diff --git a/core/client/src/auth/MobileLoginService.ts b/core/client/src/auth/MobileLoginService.tsindex 665cfab14..3eef47029 100644--- a/core/client/src/auth/MobileLoginService.ts+++ b/core/client/src/auth/MobileLoginService.ts@@ -1,6 +1,7 @@import { VaultKeyAlgorithm, type MobileLoginInitiateResponse, type MobileLoginPayload, type MobileLoginPollResponse } from '@aliasvault/models/webapi';import EncryptionUtility from '../crypto/EncryptionUtility';+import { rustCore } from '../rust/RustCore';import { bytesToBase64 } from '../utilities/Base64';import { MobileLoginProtocol } from './MobileLoginProtocol';@@ -159,7 +160,7 @@ export class MobileLoginService {// The server encrypted the session payload with a symmetric key, which is encrypted with our public key.const symmetricKey = bytesToBase64(await EncryptionUtility.decryptWithPrivateKeyObject(data.encryptedSymmetricKey, privateKey, MobileLoginProtocol.PAYLOAD_KEY_LABEL));- const payload = JSON.parse(await EncryptionUtility.symmetricDecrypt(data.encryptedPayload, symmetricKey)) as MobileLoginPayload;+ const payload = JSON.parse(await rustCore().symmetricDecrypt(data.encryptedPayload, symmetricKey)) as MobileLoginPayload;onSuccess({username: payload.username,diff --git a/core/client/src/crypto/EncryptionUtility.ts b/core/client/src/crypto/EncryptionUtility.tsindex 969db7eea..2b96ea4ca 100644--- a/core/client/src/crypto/EncryptionUtility.ts+++ b/core/client/src/crypto/EncryptionUtility.ts@@ -28,17 +28,6 @@ export class EncryptionUtility {}}- /**- * Encrypts a UTF-8 string with AES-256-GCM into base64 `IV | ciphertext | tag`. An empty string stays empty.- */- public static async symmetricEncrypt(plaintext: string, base64Key: string): Promise<string> {- if (!plaintext) {- return plaintext;- }-- return EncryptionUtility.symmetricEncryptBytes(new TextEncoder().encode(plaintext), base64Key);- }-/*** Encrypts bytes with AES-256-GCM (random 12-byte IV, no AAD) into base64 `IV | ciphertext | tag`.*/@@ -54,17 +43,6 @@ export class EncryptionUtility {return bytesToBase64(combined);}- /**- * Decrypts base64 `IV | ciphertext | tag` with AES-256-GCM into a UTF-8 string.- */- public static async symmetricDecrypt(base64Ciphertext: string, base64Key: string): Promise<string> {- if (!base64Ciphertext) {- return base64Ciphertext;- }-- return new TextDecoder().decode(await EncryptionUtility.symmetricDecryptBytes(base64ToBytes(base64Ciphertext), base64Key));- }-/*** Decrypts `IV | ciphertext | tag` bytes with AES-256-GCM (no AAD).*/diff --git a/core/client/src/email/EmailDecryption.ts b/core/client/src/email/EmailDecryption.tsindex 7ef82beea..3f3f447fe 100644--- a/core/client/src/email/EmailDecryption.ts+++ b/core/client/src/email/EmailDecryption.ts@@ -142,7 +142,7 @@ async function resolveSymmetricKey(decryptionKeys: EmailDecryptionKey[], publicKconst privateKeyCache = new Map<string, Promise<CryptoKey>>();/**- * Whether the host has full WebCrypto; the mobile app polyfills only `subtle.digest`.+ * Whether the host has WebCrypto; the mobile app (Hermes) has none.*/function hasWebCrypto(): boolean {return typeof crypto !== 'undefined' && typeof crypto.subtle?.importKey === 'function';diff --git a/core/client/src/rust/RustCoreBinding.ts b/core/client/src/rust/RustCoreBinding.tsindex 665458f9b..5188159d7 100644--- a/core/client/src/rust/RustCoreBinding.ts+++ b/core/client/src/rust/RustCoreBinding.ts@@ -51,6 +51,8 @@ export interface IRustCore {rsaDecrypt(base64Ciphertext: string, privateKeyJwk: string): Promise<Uint8Array>;decryptManifestInvitationName(encryptedName: string, manifestId: string, privateKeyJwk: string): Promise<string>;accountSigningKeyFingerprint(encryptedSigningPrivateKey: string, accountKeyBase64: string): Promise<string>;+ mobileLoginPublicKeyHash(publicKeyJwk: string): Promise<string>;+ mobileLoginVerificationCode(publicKeyJwk: string): Promise<string>;pinGenerateSalt(): Promise<Uint8Array>;pinEncrypt(pin: string, salt: Uint8Array, secret: Uint8Array): Promise<Uint8Array>;diff --git a/core/client/src/rust/WasmRustCore.ts b/core/client/src/rust/WasmRustCore.tsindex d1eae6980..775721fd5 100644--- a/core/client/src/rust/WasmRustCore.ts+++ b/core/client/src/rust/WasmRustCore.ts@@ -76,6 +76,8 @@ export function createWasmRustCore(loadWasm: WasmLoader): IRustCore {rsaDecrypt: (base64Ciphertext, privateKeyJwk): Promise<Uint8Array> => ready(() => core.rsaDecrypt(base64Ciphertext, privateKeyJwk)),decryptManifestInvitationName: (encryptedName, manifestId, privateKeyJwk): Promise<string> => ready(() => core.decryptManifestInvitationName(encryptedName, manifestId, privateKeyJwk)),accountSigningKeyFingerprint: (encryptedSigningPrivateKey, accountKeyBase64): Promise<string> => ready(() => core.accountSigningKeyFingerprint(encryptedSigningPrivateKey, accountKeyBase64)),+ mobileLoginPublicKeyHash: (publicKeyJwk): Promise<string> => ready(() => core.mobileLoginPublicKeyHash(publicKeyJwk)),+ mobileLoginVerificationCode: (publicKeyJwk): Promise<string> => ready(() => core.mobileLoginVerificationCode(publicKeyJwk)),/** Argon2 (also behind pinEncrypt and pinDecrypt) blocks the thread it runs on for up to a few seconds on slowdiff --git a/core/rust/src/bindings/uniffi_api.rs b/core/rust/src/bindings/uniffi_api.rsindex a59c0f11c..79db1ad52 100644--- a/core/rust/src/bindings/uniffi_api.rs+++ b/core/rust/src/bindings/uniffi_api.rs@@ -362,6 +362,18 @@ pub fn mobile_login_encrypt_account_key(account_key: Vec<u8>, public_key_jwk: Stcrate::crypto::encrypt_with_public_key_and_label(&account_key, &public_key_jwk, crate::crypto::aad::MOBILE_LOGIN_ACCOUNT_KEY)}+/// SHA-256 of a mobile login request's public key JWK string, unpadded base64url; the QR code carries it.+#[uniffi::export]+pub fn mobile_login_public_key_hash(public_key_jwk: String) -> String {+ crate::crypto::mobile_login_public_key_hash(&public_key_jwk)+}++/// The verification code both devices show for a mobile login request's public key JWK string.+#[uniffi::export]+pub fn mobile_login_verification_code(public_key_jwk: String) -> String {+ crate::crypto::mobile_login_verification_code(&public_key_jwk)+}+/// One engine operation. The host loops on `next_command` / `resume` until the command is `done`; see the/// `vault_sync` module docs for the command and response shapes.#[derive(uniffi::Object)]diff --git a/core/rust/src/bindings/wasm.rs b/core/rust/src/bindings/wasm.rsindex b3ca8bb0e..f310d345d 100644--- a/core/rust/src/bindings/wasm.rs+++ b/core/rust/src/bindings/wasm.rs@@ -216,6 +216,18 @@ pub fn symmetric_encrypt_bytes_js(plaintext: &[u8], key_base64: &str) -> Result<crate::crypto::symmetric_encrypt_raw_with_aad(plaintext, key_base64, &[]).map_err(js_err)}+/// SHA-256 of a mobile login request's public key JWK string, unpadded base64url; the QR code carries it.+#[wasm_bindgen(js_name = mobileLoginPublicKeyHash)]+pub fn mobile_login_public_key_hash_js(public_key_jwk: &str) -> String {+ crate::crypto::mobile_login_public_key_hash(public_key_jwk)+}++/// The verification code both devices show for a mobile login request's public key JWK string.+#[wasm_bindgen(js_name = mobileLoginVerificationCode)]+pub fn mobile_login_verification_code_js(public_key_jwk: &str) -> String {+ crate::crypto::mobile_login_verification_code(public_key_jwk)+}+/// The fingerprint of the account's own signing key, derived from its private key encrypted with the Account Key.#[wasm_bindgen(js_name = accountSigningKeyFingerprint)]pub fn account_signing_key_fingerprint_js(encrypted_signing_private_key: &str, account_key_base64: &str) -> Result<String, JsValue> {diff --git a/core/rust/src/crypto/mobile_login.rs b/core/rust/src/crypto/mobile_login.rsnew file mode 100644index 000000000..d47b4e9ac--- /dev/null+++ b/core/rust/src/crypto/mobile_login.rs@@ -0,0 +1,40 @@+//! The hashes of the mobile login (QR unlock) handshake: the public key hash the QR code carries and the verification+//! code both devices show.++use sha2::{Digest, Sha256};++use crate::common::encoding::base64url_encode;++/// The domain separator hashed in front of the public key for the verification code.+const VERIFICATION_CODE_CONTEXT: &[u8] = b"AliasVault.MobileLogin.VerificationCode.v1:";++/// The number of digits in the verification code.+const VERIFICATION_CODE_DIGITS: u32 = 2;++/// SHA-256 of the public key JWK string, unpadded base64url (43 characters).+pub fn mobile_login_public_key_hash(public_key_jwk: &str) -> String {+ base64url_encode(&Sha256::digest(public_key_jwk.as_bytes()))+}++/// The verification code for a public key JWK string: [`VERIFICATION_CODE_DIGITS`] decimal digits, zero padded.+pub fn mobile_login_verification_code(public_key_jwk: &str) -> String {+ let digest = Sha256::new().chain_update(VERIFICATION_CODE_CONTEXT).chain_update(public_key_jwk.as_bytes()).finalize();+ let value = u32::from_be_bytes([digest[0], digest[1], digest[2], digest[3]]);+ format!("{:0width$}", value % 10u32.pow(VERIFICATION_CODE_DIGITS), width = VERIFICATION_CODE_DIGITS as usize)+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Known-answer vectors from the former TypeScript implementation, which released clients still run. A changed+ /// output means an old and a new client no longer agree on the QR code or the code they show. Never regenerate them.+ #[test]+ fn known_answers() {+ let jwk = r#"{"kty":"RSA","n":"abc","e":"AQAB"}"#;+ assert_eq!(mobile_login_public_key_hash(jwk), "1Dew3uCqsSjh4UPhSxj4DAT-YUO3M3XGzR2594gSIYw");+ assert_eq!(mobile_login_verification_code(jwk), "07");+ assert_eq!(mobile_login_public_key_hash("héllo ✓"), "VlfN74qFpYTg6WHm-CR89dP47SFJbtb9vP1Dp2HpQkU");+ assert_eq!(mobile_login_verification_code("héllo ✓"), "39");+ }+}diff --git a/core/rust/src/crypto/mod.rs b/core/rust/src/crypto/mod.rsindex f9227996a..916496f52 100644--- a/core/rust/src/crypto/mod.rs+++ b/core/rust/src/crypto/mod.rs@@ -5,6 +5,7 @@//! - [`argon2`]: Argon2id (`argon2`) with a parameter floor; turns the master password into the unlock key.//! - `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: Argon2id + AES-256-GCM wrap of the key the host stores, 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.@@ -19,6 +20,7 @@ pub mod aes_gcm;pub mod argon2;pub(crate) mod jwk;pub mod key_chain;+pub mod mobile_login;pub mod pin;pub mod rsa_oaep;pub mod signing;@@ -34,6 +36,7 @@ pub use key_chain::{account_signing_key_fingerprint, create_account_key_hierarchy, create_account_key_hierarchy_with_key_pair, derive_srp_password_hash, open_account_key_chain, open_account_private_key, open_account_signing_private_key,reencrypt_account_key, rotate_account_keys, unwrap_account_key, unwrap_key, wrap_key, AccountKeyBlobs, AccountKeyHierarchy, KeyChainError, RotatedAccountKeys, SrpInputError,};+pub use mobile_login::{mobile_login_public_key_hash, mobile_login_verification_code};pub use pin::{pin_decrypt, pin_encrypt, pin_generate_salt, pin_is_locked, pin_register_failure, PinFailure};pub use rsa_oaep::{decrypt_manifest_invitation_name, decrypt_with_private_key, decrypt_with_private_key_and_label, encrypt_with_public_key_and_label, generate_rsa_key_pair, RsaKeyPair};pub use signing::generate_signing_key_pair;diff --git a/docs/docs/security-whitepaper.mdx b/docs/docs/security-whitepaper.mdxindex 53e1aa448..abfefe1c4 100644--- a/docs/docs/security-whitepaper.mdx+++ b/docs/docs/security-whitepaper.mdx@@ -516,6 +516,7 @@ Where each part of this document lives in the repository, for reviewers.| Ed25519 signing and verification | `core/rust/src/crypto/signing.rs`, `apps/server/Utilities/AliasVault.Cryptography/Signing.cs` || Key rotation | `core/rust/src/crypto/key_chain.rs`, `core/rust/src/crypto/signing.rs`, `core/rust/src/vault_sync/rotation.rs`, `apps/server/AliasVault.Api/Controllers/V2/KeyRotationController.cs` || PIN encryption and attempt policy | `core/rust/src/crypto/pin.rs` |+| Login with Mobile public key hash and verification code | `core/rust/src/crypto/mobile_login.rs` || Local vault copy | `core/rust/src/crypto/vault_blob.rs` (mobile), `core/client/src/crypto/VaultBlob.ts` (web app and extensions, WebCrypto) || Vault format: canonicalize, materialize, integrity | `core/rust/src/vault_codec/` || Sync engine: pull, push, grants, sharing, delivery keys | `core/rust/src/vault_sync/` |