Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor avex export to Rust core
Leendert de Borstd606ad804da7
diff --git a/apps/browser-extension/src/utils/PinUnlockService.ts b/apps/browser-extension/src/utils/PinUnlockService.tsindex 10c53bf71..07fbc1ee7 100644--- a/apps/browser-extension/src/utils/PinUnlockService.ts+++ b/apps/browser-extension/src/utils/PinUnlockService.ts@@ -1,4 +1,4 @@-import { pinDecrypt, pinEncrypt, pinGenerateSalt, pinIsLocked, pinRegisterFailure } from '@aliasvault/client/rust/RustCore';+import { pinDecrypt, pinEncrypt, pinExtensionSalt, pinGenerateSalt, pinIsLocked, pinRegisterFailure } from '@aliasvault/client/rust/RustCore';import { base64ToBytes, bytesToBase64 } from '@aliasvault/client/utilities/Base64';import { PIN_STORAGE_KEYS, StorageKeys } from '@/utils/constants/storageKeys';@@ -12,26 +12,6 @@ import { browser, storage } from '#imports';* 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.- *- * Security features:- * - 4 failed attempts maximum before requiring full password- * - PIN must be 6-64 characters- * - Encryption key derived using Argon2id (memory-hard, GPU-resistant)- * - Extension ID pepper adds friction for naive attacks- * - Failed attempts counter stored separately- * - Encrypted data automatically deleted after max failed attempts- *- * Security model- * - Random salt: Stored locally (prevents rainbow tables)- * - Extension ID pepper: Derived from browser.runtime.id- * - Argon2id memory cost: 64 MB makes each attempt expensive- * - Attempt limiting: 4 attempts max before PIN is disabled- *- * Recommendation: Use PIN unlock only on trusted devices. For high-security scenarios, always- * use full master password unlock.- *- * The key wrap and the attempt policy live in the Rust core (crypto/pin.rs); this file only stores them.- * Other platform implementations: VaultStore+Pin.swift (iOS), VaultPin.kt (Android).*//**@@ -270,37 +250,12 @@ export async function resetFailedAttempts(): Promise<void> {}/**- * Get extension ID pepper component- *- * This provides a device-bound value that is NOT stored in chrome.storage.- * The extension ID is unique per installation and accessible via browser.runtime.id.- *- * Security benefits:- * - Not stored in chrome.storage directly (however still stored elsewhere on filesystem)- * - Adds friction for attackers who only copy storage directory- * - Unique per extension installation- *- * @returns SHA-256 hash of extension ID as Uint8Array- */-async function getExtensionPepper(): Promise<Uint8Array> {- const extensionId = browser.runtime.id;- const pepperSource = new TextEncoder().encode(extensionId);- const pepperHash = await crypto.subtle.digest('SHA-256', pepperSource);- return new Uint8Array(pepperHash);-}--/**- * The Argon2id salt for the PIN key: the UTF-8 characters of base64(random salt || extension ID pepper).+ * The Argon2id salt for the PIN key: the stored random salt with the extension ID as pepper, composed in the Rust core.*- * The salt is hashed as the characters of this base64 string, not as the bytes it decodes to.- * Every PIN ever set was derived that way, so decoding here would lock users out of their vault.+ * 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*/async function argon2Salt(randomSalt: Uint8Array): Promise<Uint8Array> {- const pepper = await getExtensionPepper();- const combinedSalt = new Uint8Array(randomSalt.length + pepper.length);- combinedSalt.set(randomSalt, 0);- combinedSalt.set(pepper, randomSalt.length);- return new TextEncoder().encode(bytesToBase64(combinedSalt));+ return pinExtensionSalt(randomSalt, browser.runtime.id);}diff --git a/apps/browser-extension/tests/e2e/50-export.spec.ts b/apps/browser-extension/tests/e2e/50-export.spec.tsindex 2864fb9e3..1f028d256 100644--- a/apps/browser-extension/tests/e2e/50-export.spec.ts+++ b/apps/browser-extension/tests/e2e/50-export.spec.ts@@ -81,7 +81,7 @@ test.describe.serial('50. Vault export', () => {await expect(popup.getByText('exported successfully')).toBeVisible({ timeout: Timeouts.LONG });const avexBytes = new Uint8Array(readFileSync(await download.path()));- expect(AvexImportService.parseAvexHeader(avexBytes).header.format).toBe('avex');+ expect((await AvexImportService.parseAvexHeader(avexBytes)).format).toBe('avex');await expect(AvexImportService.decryptAvex(avexBytes, 'not-the-export-password')).rejects.toThrow();const avuxBytes = await AvexImportService.decryptAvex(avexBytes, exportPassword);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 699ba39f5..7e6940cda 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@@ -6,6 +6,7 @@ import org.json.JSONObjectimport uniffi.aliasvault_core.KeyChainExceptionimport uniffi.aliasvault_core.KeyChainKeysimport uniffi.aliasvault_core.argon2DeriveKey+import uniffi.aliasvault_core.avexEncryptimport uniffi.aliasvault_core.createAccountKeyHierarchyJsonimport uniffi.aliasvault_core.decodeEmailSourceimport uniffi.aliasvault_core.deriveSrpPasswordHash@@ -92,6 +93,7 @@ object RustCoreDispatcher {"rsaDecrypt" -> json(rsaDecrypt(args.string(0), args.string(1)))"symmetricDecrypt" -> json(symmetricDecrypt(args.string(0), args.string(1)))"symmetricDecryptBytes" -> json(symmetricDecryptBytes(args.bytes(0), args.string(1)))+ "avexEncrypt" -> json(avexEncrypt(args.bytes(0), args.string(1), args.string(2), args.string(3)))"symmetricEncryptBytes" -> json(symmetricEncryptBytes(args.bytes(0), args.string(1)))"mobileLoginPublicKeyHash" -> json(mobileLoginPublicKeyHash(args.string(0)))"mobileLoginVerificationCode" -> json(mobileLoginVerificationCode(args.string(0)))diff --git a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swiftindex 4d03bac16..63e8b5b69 100644--- a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift+++ b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift@@ -1566,6 +1566,7 @@ private enum RustCoreDispatcher {case "rsaDecrypt": return try json(bytes: try RustCoreFramework.rsaDecrypt(base64Ciphertext: try args.string(0), privateKeyJwk: try args.string(1)))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 "avexEncrypt": return try json(bytes: try RustCoreFramework.avexEncrypt(avux: try args.data(0), password: try args.string(1), exportedAt: try args.string(2), appVersion: try args.string(3)))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)))diff --git a/apps/mobile-app/platform/NativeRustCore.ts b/apps/mobile-app/platform/NativeRustCore.tsindex edb4977ae..ed107fa32 100644--- a/apps/mobile-app/platform/NativeRustCore.ts+++ b/apps/mobile-app/platform/NativeRustCore.ts@@ -34,6 +34,7 @@ function notImplementedOnMobile(name: string, reason: string): Promise<never> {}const PIN_IS_NATIVE = 'PIN unlock runs in the native VaultStore';+const AVEX_IMPORT_IS_WEB = 'the mobile app exports .avex files, only the web app imports them';const MOBILE_LOGIN_IS_WEB = 'the mobile app approves a mobile login, only the web app and the browser extension request one';/*@@ -80,11 +81,16 @@ export const nativeRustCore: IRustCore = {mobileLoginOpenApproval: () => notImplementedOnMobile('mobileLoginOpenApproval', MOBILE_LOGIN_IS_WEB),pinGenerateSalt: () => notImplementedOnMobile('pinGenerateSalt', PIN_IS_NATIVE),+ pinExtensionSalt: () => notImplementedOnMobile('pinExtensionSalt', 'only the browser extension peppers its PIN salt'),pinEncrypt: () => notImplementedOnMobile('pinEncrypt', PIN_IS_NATIVE),pinDecrypt: () => notImplementedOnMobile('pinDecrypt', PIN_IS_NATIVE),pinIsLocked: () => notImplementedOnMobile('pinIsLocked', PIN_IS_NATIVE),pinRegisterFailure: () => notImplementedOnMobile('pinRegisterFailure', PIN_IS_NATIVE),+ avexEncrypt: (avux, password, exportedAt, appVersion) => callForBytes('avexEncrypt', base64(avux), password, exportedAt, appVersion),+ avexParseHeader: () => notImplementedOnMobile('avexParseHeader', AVEX_IMPORT_IS_WEB),+ avexDecrypt: () => notImplementedOnMobile('avexDecrypt', AVEX_IMPORT_IS_WEB),+argon2DeriveKey: (password, salt, encryptionSettings) => callForBytes('argon2DeriveKey', password, salt, encryptionSettings),deriveSrpPasswordHash: (unlockKeyBase64, encryptionType) => call('deriveSrpPasswordHash', unlockKeyBase64, encryptionType),openKeyChainWithUnlockKey: (unlockKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey) => call('openKeyChainWithUnlockKey', unlockKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey),diff --git a/core/client/src/rust/RustCore.ts b/core/client/src/rust/RustCore.tsindex 7caea14ad..08bed10b3 100644--- a/core/client/src/rust/RustCore.ts+++ b/core/client/src/rust/RustCore.ts@@ -181,6 +181,13 @@ export async function pinGenerateSalt(): Promise<Uint8Array> {return rustCore().pinGenerateSalt();}+/**+ * The salt the browser extension derives its PIN key with, from the stored random salt and the extension id.+ */+export async function pinExtensionSalt(salt: Uint8Array, extensionId: string): Promise<Uint8Array> {+ return rustCore().pinExtensionSalt(salt, extensionId);+}+/*** Encrypt `secret` with a key derived from the PIN and salt, as `IV | ciphertext | tag`.*/diff --git a/core/client/src/rust/RustCoreBinding.ts b/core/client/src/rust/RustCoreBinding.tsindex d91631bba..b6b54b065 100644--- a/core/client/src/rust/RustCoreBinding.ts+++ b/core/client/src/rust/RustCoreBinding.ts@@ -1,4 +1,4 @@-import type { AccountKeyHierarchy, CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, KeyChainOpenResult, MobileLoginApproval, ParsedEmail, PinFailure, ReencryptedAccountKey, RsaKeyPair, SrpEphemeral, SrpSession } from './RustCoreTypes';+import type { AccountKeyHierarchy, AvexHeader, CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, KeyChainOpenResult, MobileLoginApproval, ParsedEmail, PinFailure, ReencryptedAccountKey, RsaKeyPair, SrpEphemeral, SrpSession } from './RustCoreTypes';/*** One running operation of the Rust vault sync engine.@@ -57,11 +57,16 @@ export interface IRustCore {mobileLoginOpenApproval(privateKeyJwk: string, encryptedAccountKey: string, encryptedPayloadKey: string, encryptedPayload: string): Promise<MobileLoginApproval>;pinGenerateSalt(): Promise<Uint8Array>;+ pinExtensionSalt(salt: Uint8Array, extensionId: string): Promise<Uint8Array>;pinEncrypt(pin: string, salt: Uint8Array, secret: Uint8Array): Promise<Uint8Array>;pinDecrypt(pin: string, salt: Uint8Array, encrypted: Uint8Array): Promise<Uint8Array>;pinIsLocked(failedAttempts: number): Promise<boolean>;pinRegisterFailure(failedAttempts: number): Promise<PinFailure>;+ avexEncrypt(avux: Uint8Array, password: string, exportedAt: string, appVersion: string): Promise<Uint8Array>;+ avexParseHeader(avex: Uint8Array): Promise<AvexHeader>;+ avexDecrypt(avex: Uint8Array, password: string): Promise<Uint8Array>;+argon2DeriveKey(password: string, salt: string, encryptionSettings: string): Promise<Uint8Array>;deriveSrpPasswordHash(unlockKeyBase64: string, encryptionType: string): Promise<string>;openKeyChainWithUnlockKey(unlockKey: string, encryptedAccountKey: string, encryptedVek: string, encryptedAccountPrivateKey: string | null): Promise<KeyChainOpenResult>;diff --git a/core/client/src/rust/RustCoreTypes.ts b/core/client/src/rust/RustCoreTypes.tsindex 4ec69779d..a680e175c 100644--- a/core/client/src/rust/RustCoreTypes.ts+++ b/core/client/src/rust/RustCoreTypes.ts@@ -80,6 +80,21 @@ export type SrpSession = {key: string;};+/** The header of an .avex encrypted export (the Rust `AvexHeader`), with its JSON wire names. */+export type AvexHeader = {+ format: string;+ /** The .avex container format version (not the app version). */+ version: string;+ kdf: {+ type: string;+ /** The base64 salt. */+ salt: string;+ params: { DegreeOfParallelism: number; MemorySize: number; Iterations: number };+ };+ encryption: { algorithm: string; encryptedDataOffset: number };+ metadata: { exportedAt: string; appVersion: string | null };+};+/** The PIN attempt counter after a failed attempt (the Rust `pin_register_failure`). */export type PinFailure = {/** The failed-attempt count to store. */diff --git a/core/client/src/rust/WasmRustCore.ts b/core/client/src/rust/WasmRustCore.tsindex a2f85228b..3a0d0288b 100644--- a/core/client/src/rust/WasmRustCore.ts+++ b/core/client/src/rust/WasmRustCore.ts@@ -7,7 +7,7 @@ import initWasm, * as core from '#wasm/aliasvault_core.js';import { yieldToPaint } from '../utilities/YieldToPaint';import type { IRustCore, IVaultSyncSession } from './RustCoreBinding';-import type { AccountKeyHierarchy, CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, KeyChainOpenResult, MobileLoginApproval, ParsedEmail, PinFailure, ReencryptedAccountKey, RsaKeyPair, SrpEphemeral, SrpSession } from './RustCoreTypes';+import type { AccountKeyHierarchy, AvexHeader, CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, KeyChainOpenResult, MobileLoginApproval, ParsedEmail, PinFailure, ReencryptedAccountKey, RsaKeyPair, SrpEphemeral, SrpSession } from './RustCoreTypes';/*** Where the host gets the `.wasm` binary from: bytes, or a fetch response for streaming instantiation.@@ -87,6 +87,7 @@ export function createWasmRustCore(loadWasm: WasmLoader): IRustCore {* devices, so let the caller's loading indicator paint first before proceeding with the expensive operation.*/pinGenerateSalt: (): Promise<Uint8Array> => ready(() => core.pinGenerateSalt()),+ pinExtensionSalt: (salt, extensionId): Promise<Uint8Array> => ready(() => core.pinExtensionSalt(salt, extensionId)),pinEncrypt: async (pin, salt, secret): Promise<Uint8Array> => {await yieldToPaint();return ready(() => core.pinEncrypt(pin, salt, secret));@@ -98,6 +99,16 @@ export function createWasmRustCore(loadWasm: WasmLoader): IRustCore {pinIsLocked: (failedAttempts): Promise<boolean> => ready(() => core.pinIsLocked(failedAttempts)),pinRegisterFailure: (failedAttempts): Promise<PinFailure> => ready(() => core.pinRegisterFailure(failedAttempts) as PinFailure),+ avexEncrypt: async (avux, password, exportedAt, appVersion): Promise<Uint8Array> => {+ await yieldToPaint();+ return ready(() => core.avexEncrypt(avux, password, exportedAt, appVersion));+ },+ avexParseHeader: (avex): Promise<AvexHeader> => ready(() => core.avexParseHeader(avex) as AvexHeader),+ avexDecrypt: async (avex, password): Promise<Uint8Array> => {+ await yieldToPaint();+ return ready(() => core.avexDecrypt(avex, password));+ },+argon2DeriveKey: async (password, salt, encryptionSettings): Promise<Uint8Array> => {await yieldToPaint();return ready(() => core.argon2DeriveKey(password, salt, encryptionSettings));diff --git a/core/client/src/transfer/export/AvexConstants.ts b/core/client/src/transfer/export/AvexConstants.tsdeleted file mode 100644index 10e3c2f56..000000000--- a/core/client/src/transfer/export/AvexConstants.ts+++ /dev/null@@ -1,23 +0,0 @@-/**- * Constants for the .avex (AliasVault Encrypted eXport) file format.- */-export const AvexConstants = {- /**- * The delimiter that separates the JSON header from the encrypted payload in .avex files.- */- HeaderDelimiter: '\n-----BEGIN ENCRYPTED DATA-----\n',-- /**- * The .avex file format identifier.- */- FormatIdentifier: 'avex',-- /*- * The .avex format version. This is the structure version of the container itself, independent of the- * AliasVault application version that created the export. When changing it, also update the import logic- * to support both the old and the new version, as all current logic checks for 1.0.0 explicitly.- * Version history:- * - 1.0.0: Initial .avex format with Argon2id KDF + AES-256-GCM encryption.- */- FormatVersion: '1.0.0',-} as const;diff --git a/core/client/src/transfer/export/AvexExportService.ts b/core/client/src/transfer/export/AvexExportService.tsindex 430ae44df..64cae6a9f 100644--- a/core/client/src/transfer/export/AvexExportService.ts+++ b/core/client/src/transfer/export/AvexExportService.ts@@ -1,22 +1,8 @@import { AppInfo } from '../../platform/AppInfo';-import { argon2DeriveKey, rustCore } from '../../rust/RustCore';-import { bytesToBase64 } from '../../utilities/Base64';--import { AvexConstants } from './AvexConstants';--import type { AvexHeader } from './AvexHeader';--/**- * The Argon2id parameters a new export is encrypted with.- */-const ARGON2_KDF_PARAMS = { DegreeOfParallelism: 1, MemorySize: 262144, Iterations: 3 };--/** The KDF the export key is derived with: plain Argon2id, independent of the account's login encryption type. */-const AVEX_KDF_TYPE = 'Argon2Id';+import { rustCore } from '../../rust/RustCore';/**- * Writes the .avex encrypted vault export format: a JSON header, a PEM-style delimiter and the encrypted .avux payload- * keyed with Argon2id from the export password.+ * Writes the .avex encrypted vault export format; the container lives in the Rust core (crypto/avex.rs).*/export class AvexExportService {/**@@ -26,37 +12,6 @@ export class AvexExportService {* @returns The .avex file bytes*/public static async encryptToAvex(avuxBytes: Uint8Array, exportPassword: string): Promise<Uint8Array> {- // 1. A random salt and a key derived from it with Argon2id.- const salt = crypto.getRandomValues(new Uint8Array(32));- const saltBase64 = bytesToBase64(salt);- const key = await argon2DeriveKey(exportPassword, saltBase64, JSON.stringify(ARGON2_KDF_PARAMS));-- // 2. AES-256-GCM over the .avux bytes.- const encryptedPayload = await rustCore().symmetricEncryptBytes(avuxBytes, bytesToBase64(key));-- // 3. The header.- const header: AvexHeader = {- format: AvexConstants.FormatIdentifier,- version: AvexConstants.FormatVersion,- kdf: { type: AVEX_KDF_TYPE, salt: saltBase64, params: { ...ARGON2_KDF_PARAMS } },- encryption: { algorithm: 'AES-256-GCM', encryptedDataOffset: 0 },- metadata: { exportedAt: new Date().toISOString(), appVersion: AppInfo.VERSION },- };-- const encoder = new TextEncoder();- const delimiterBytes = encoder.encode(AvexConstants.HeaderDelimiter);-- // 4. The offset of the payload is recorded in the header, so serialize, measure and serialize again.- let headerBytes = encoder.encode(JSON.stringify(header, null, 2));- header.encryption.encryptedDataOffset = headerBytes.length + delimiterBytes.length;- headerBytes = encoder.encode(JSON.stringify(header, null, 2));-- // 5. header + delimiter + payload.- const avexFile = new Uint8Array(headerBytes.length + delimiterBytes.length + encryptedPayload.length);- avexFile.set(headerBytes, 0);- avexFile.set(delimiterBytes, headerBytes.length);- avexFile.set(encryptedPayload, headerBytes.length + delimiterBytes.length);-- return avexFile;+ return rustCore().avexEncrypt(avuxBytes, exportPassword, new Date().toISOString(), AppInfo.VERSION);}}diff --git a/core/client/src/transfer/export/AvexHeader.ts b/core/client/src/transfer/export/AvexHeader.tsdeleted file mode 100644index 232f628fd..000000000--- a/core/client/src/transfer/export/AvexHeader.ts+++ /dev/null@@ -1,45 +0,0 @@-/*- * The header of an .avex (encrypted export) file. Property names are the JSON wire names (camelCase).- */--/**- * Key derivation function parameters.- */-export type AvexKdfParams = {- /** The KDF algorithm type. */- type: string;- /** The salt value (base64-encoded). */- salt: string;- /** Algorithm-specific parameters, keyed as the Rust core expects them (DegreeOfParallelism, MemorySize, Iterations). */- params: Record<string, number>;-};--/**- * Encryption algorithm parameters.- */-export type AvexEncryptionParams = {- algorithm: string;- /** The byte offset where the encrypted data begins. */- encryptedDataOffset: number;-};--/**- * Metadata about the export.- */-export type AvexMetadata = {- exportedAt: string;- /** The AliasVault application version that created this export. */- appVersion?: string | null;-};--/**- * The header for an .avex file.- */-export type AvexHeader = {- format: string;- /** The .avex container format version (not the app version). */- version: string;- kdf: AvexKdfParams;- encryption: AvexEncryptionParams;- metadata: AvexMetadata;-};diff --git a/core/client/src/transfer/export/__tests__/AvexExportService.test.ts b/core/client/src/transfer/export/__tests__/AvexExportService.test.tsindex 931c15b10..e6d63937b 100644--- a/core/client/src/transfer/export/__tests__/AvexExportService.test.ts+++ b/core/client/src/transfer/export/__tests__/AvexExportService.test.ts@@ -15,10 +15,10 @@ describe('AvexExportService', () => {const avuxBytes = exportItems([createTestItem('Encrypted item', ItemTypes.Login, { [FieldKey.LoginUsername]: 'user' })]);const avexBytes = await AvexExportService.encryptToAvex(avuxBytes, 'export-password');- const { header, payloadOffset } = AvexImportService.parseAvexHeader(avexBytes);+ const header = await AvexImportService.parseAvexHeader(avexBytes);const key = await argon2DeriveKey('export-password', header.kdf.salt, JSON.stringify(header.kdf.params));- const decrypted = await EncryptionUtility.symmetricDecryptBytes(avexBytes.subarray(payloadOffset), bytesToBase64(key));+ const decrypted = await EncryptionUtility.symmetricDecryptBytes(avexBytes.subarray(header.encryption.encryptedDataOffset), bytesToBase64(key));expect(Array.from(decrypted)).toEqual(Array.from(avuxBytes));});@@ -26,7 +26,7 @@ describe('AvexExportService', () => {const avuxBytes = exportItems([createTestItem('Encrypted item', ItemTypes.Login, { [FieldKey.LoginUsername]: 'user' })]);const avexBytes = await AvexExportService.encryptToAvex(avuxBytes, 'export-password');- const { header } = AvexImportService.parseAvexHeader(avexBytes);+ const header = await AvexImportService.parseAvexHeader(avexBytes);expect(header.format).toBe('avex');expect(header.version).toBe('1.0.0');expect(header.kdf.type.toLowerCase()).toBe('argon2id');diff --git a/core/client/src/transfer/import/importers/aliasvault/AvexImportService.ts b/core/client/src/transfer/import/importers/aliasvault/AvexImportService.tsindex d249cf823..52a4abb25 100644--- a/core/client/src/transfer/import/importers/aliasvault/AvexImportService.ts+++ b/core/client/src/transfer/import/importers/aliasvault/AvexImportService.ts@@ -1,9 +1,6 @@-import { argon2DeriveKey, rustCore } from '../../../../rust/RustCore';-import { bytesToBase64 } from '../../../../utilities/Base64';-import { AvexConstants } from '../../../export/AvexConstants';-import { getProperty, isJsonObject, parseJson, readNumber, readObject, readString, requireObject } from '../../readers/JsonReader';+import { rustCore } from '../../../../rust/RustCore';-import type { AvexHeader } from '../../../export/AvexHeader';+import type { AvexHeader } from '../../../../rust/RustCoreTypes';/*** Thrown when an .avex file cannot be decrypted; most likely the password is wrong.@@ -21,7 +18,7 @@ export class AvexDecryptionError extends Error {}/**- * Reads the .avex encrypted vault export format written by AvexExportService.+ * Reads the .avex encrypted vault export format; the container lives in the Rust core (crypto/avex.rs).*/export class AvexImportService {/**@@ -33,94 +30,26 @@ export class AvexImportService {* @throws {AvexDecryptionError} When the payload does not decrypt (wrong password or corrupt file).*/public static async decryptAvex(avexBytes: Uint8Array, exportPassword: string): Promise<Uint8Array> {- const { header, payloadOffset } = AvexImportService.parseAvexHeader(avexBytes);-- if (header.version !== AvexConstants.FormatVersion) {- throw new Error(`Unsupported .avex version: ${header.version}. Expected ${AvexConstants.FormatVersion}.`);- }-- const encryptedPayload = avexBytes.subarray(payloadOffset);-- if (header.kdf.type.toLowerCase() !== 'argon2id') {- throw new Error(`Unsupported KDF type: ${header.kdf.type}. Only Argon2id is supported.`);- }-- const key = await argon2DeriveKey(exportPassword, header.kdf.salt, JSON.stringify(header.kdf.params));+ await AvexImportService.parseAvexHeader(avexBytes);try {- return await rustCore().symmetricDecryptBytes(encryptedPayload, bytesToBase64(key));+ return await rustCore().avexDecrypt(avexBytes, exportPassword);} catch (error) {throw new AvexDecryptionError(error);}}/**- * Parse the header of an .avex file.+ * Parse and check the header of an .avex file.* @param avexBytes - The .avex file bytes- * @returns The header and the byte offset of the payload- * @throws {Error} When the delimiter is missing or the header is not an .avex header.- */- public static parseAvexHeader(avexBytes: Uint8Array): { header: AvexHeader; payloadOffset: number } {- const delimiterBytes = new TextEncoder().encode(AvexConstants.HeaderDelimiter);- const delimiterIndex = AvexImportService.indexOf(avexBytes, delimiterBytes);-- if (delimiterIndex === -1) {- throw new Error('Invalid .avex file: header delimiter not found');- }-- const headerJson = new TextDecoder('utf-8').decode(avexBytes.subarray(0, delimiterIndex));- const root = requireObject(parseJson(headerJson), '.avex header');- const format = readString(root, 'format');- if (format !== AvexConstants.FormatIdentifier) {- throw new Error(`Invalid .avex file: expected format '${AvexConstants.FormatIdentifier}', got '${format ?? 'null'}'`);- }-- const kdf = readObject(root, 'kdf');- const encryption = readObject(root, 'encryption');- const metadata = readObject(root, 'metadata');- const params = kdf ? getProperty(kdf, 'params') : undefined;-- const header: AvexHeader = {- format,- version: readString(root, 'version') ?? '',- kdf: {- type: (kdf ? readString(kdf, 'type') : null) ?? '',- salt: (kdf ? readString(kdf, 'salt') : null) ?? '',- params: isJsonObject(params) ? Object.fromEntries(Object.entries(params).filter((entry): entry is [string, number] => typeof entry[1] === 'number')) : {},- },- encryption: {- algorithm: (encryption ? readString(encryption, 'algorithm') : null) ?? '',- encryptedDataOffset: (encryption ? readNumber(encryption, 'encryptedDataOffset') : null) ?? 0,- },- metadata: {- exportedAt: (metadata ? readString(metadata, 'exportedAt') : null) ?? '',- appVersion: metadata ? readString(metadata, 'appVersion') : null,- },- };-- return { header, payloadOffset: delimiterIndex + delimiterBytes.length };- }-- /**- * Find a byte pattern in a byte array.- * @param source - The bytes to search- * @param pattern - The pattern- * @returns The index of the first match, or -1+ * @returns The header+ * @throws {Error} When the file is not a supported .avex file.*/- private static indexOf(source: Uint8Array, pattern: Uint8Array): number {- if (pattern.length > source.length) {- return -1;- }-- outer: for (let i = 0; i <= source.length - pattern.length; i++) {- for (let j = 0; j < pattern.length; j++) {- if (source[i + j] !== pattern[j]) {- continue outer;- }- }- return i;+ public static async parseAvexHeader(avexBytes: Uint8Array): Promise<AvexHeader> {+ try {+ return await rustCore().avexParseHeader(avexBytes);+ } catch (error) {+ throw new Error(String(error));}-- return -1;}}diff --git a/core/rust/src/bindings/uniffi_api.rs b/core/rust/src/bindings/uniffi_api.rsindex 7af3ceb9a..851d965e4 100644--- a/core/rust/src/bindings/uniffi_api.rs+++ b/core/rust/src/bindings/uniffi_api.rs@@ -225,6 +225,13 @@ pub fn account_signing_key_fingerprint(encrypted_signing_private_key: String, accrate::crypto::account_signing_key_fingerprint(&encrypted_signing_private_key, &account_key)}+/// Encrypt .avux bytes into an .avex file under the export password.+#[uniffi::export]+pub fn avex_encrypt(avux: Vec<u8>, password: String, exported_at: String, app_version: String) -> Result<Vec<u8>, VaultError> {+ let (avux, password) = (zeroize::Zeroizing::new(avux), zeroize::Zeroizing::new(password));+ crate::crypto::avex_encrypt(&avux, &password, &exported_at, &app_version)+}+/// A fresh random salt for a new PIN key.#[uniffi::export]pub fn pin_generate_salt() -> Vec<u8> {diff --git a/core/rust/src/bindings/wasm.rs b/core/rust/src/bindings/wasm.rsindex 51d313f50..a18da483a 100644--- a/core/rust/src/bindings/wasm.rs+++ b/core/rust/src/bindings/wasm.rs@@ -259,12 +259,38 @@ pub fn decrypt_manifest_invitation_name_js(encrypted_name: &str, manifest_id: &scrate::crypto::decrypt_manifest_invitation_name(encrypted_name, manifest_id, private_key_jwk).map_err(js_err)}+/// Encrypt .avux bytes into an .avex file under the export password.+#[wasm_bindgen(js_name = avexEncrypt)]+pub fn avex_encrypt_js(avux: Vec<u8>, password: String, exported_at: &str, app_version: &str) -> Result<Vec<u8>, JsValue> {+ let (avux, password) = (zeroize::Zeroizing::new(avux), zeroize::Zeroizing::new(password));+ crate::crypto::avex_encrypt(&avux, &password, exported_at, app_version).map_err(js_err)+}++/// Read and check the header of an .avex file.+#[wasm_bindgen(js_name = avexParseHeader)]+pub fn avex_parse_header_js(avex: &[u8]) -> Result<JsValue, JsValue> {+ to_js(&crate::crypto::avex_parse_header(avex).map_err(js_err)?)+}++/// Decrypt an .avex file into its .avux bytes. Fails for a wrong password.+#[wasm_bindgen(js_name = avexDecrypt)]+pub fn avex_decrypt_js(avex: &[u8], password: String) -> Result<js_sys::Uint8Array, JsValue> {+ let password = zeroize::Zeroizing::new(password);+ crate::crypto::avex_decrypt(avex, &password).map(|avux| js_sys::Uint8Array::from(&avux[..])).map_err(js_err)+}+/// A fresh random salt for a new PIN key.#[wasm_bindgen(js_name = pinGenerateSalt)]pub fn pin_generate_salt_js() -> Vec<u8> {crate::crypto::pin_generate_salt()}+/// The salt the browser extension derives its PIN key with, from the stored random salt and the extension id.+#[wasm_bindgen(js_name = pinExtensionSalt)]+pub fn pin_extension_salt_js(salt: &[u8], extension_id: &str) -> Vec<u8> {+ crate::crypto::pin_extension_salt(salt, extension_id)+}+/// Encrypt `secret` with a key derived from the PIN and salt. Returns `IV | ciphertext | tag`.#[wasm_bindgen(js_name = pinEncrypt)]pub fn pin_encrypt_js(pin: String, salt: &[u8], secret: Vec<u8>) -> Result<Vec<u8>, JsValue> {diff --git a/core/rust/src/crypto/avex.rs b/core/rust/src/crypto/avex.rsnew file mode 100644index 000000000..ac8a92e17--- /dev/null+++ b/core/rust/src/crypto/avex.rs@@ -0,0 +1,185 @@+//! The .avex encrypted vault export: a JSON header, a delimiter, then the .avux bytes encrypted with AES-256-GCM under an+//! Argon2id key of the export password.++use serde::{Deserialize, Serialize};+use thiserror::Error;+use zeroize::Zeroizing;++use crate::common::encoding::base64_encode;+use crate::common::error::{VaultError, VaultResult};+use crate::common::rng::random_bytes;+use crate::crypto::aes_gcm;+use crate::crypto::argon2::{argon2_derive_key, Argon2Error, Argon2Params};++/// Separates the JSON header from the encrypted payload.+pub const AVEX_HEADER_DELIMITER: &str = "\n-----BEGIN ENCRYPTED DATA-----\n";++/// The `format` of every .avex header.+pub const AVEX_FORMAT: &str = "avex";++/*+ * The version of the container itself, independent of the app version that wrote it. A new version must keep+ * reading the old one.+ * Version history:+ * - 1.0.0: Initial .avex format with Argon2id KDF + AES-256-GCM encryption.+ */+pub const AVEX_FORMAT_VERSION: &str = "1.0.0";++/// The KDF a new export is written with: plain Argon2id, independent of the account's login encryption type.+const AVEX_KDF_TYPE: &str = "Argon2Id";++const AVEX_ENCRYPTION_ALGORITHM: &str = "AES-256-GCM";++/// Length of the random salt; the KDF hashes the UTF-8 characters of its base64 string.+const AVEX_SALT_LENGTH: usize = 32;++/// The Argon2id parameters a new export is encrypted with.+const AVEX_KDF_PARAMS: AvexKdfParams = AvexKdfParams { degree_of_parallelism: 1, memory_size: 262144, iterations: 3 };++/// Why an .avex file could not be read.+#[derive(Error, Debug, Clone, PartialEq, Eq)]+pub enum AvexError {+ /// The bytes are not an .avex file this version reads.+ #[error("Invalid .avex file: {0}")]+ InvalidFile(String),++ /// The payload did not decrypt: a wrong password or a corrupt payload.+ #[error("Failed to decrypt .avex file. The password may be incorrect or the file may be corrupted.")]+ Decryption,+}++/// The header of an .avex file, with its JSON wire names.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AvexHeader {+ /// Always [`AVEX_FORMAT`].+ pub format: String,+ /// The container format version (not the app version).+ pub version: String,+ /// How the key is derived from the export password.+ pub kdf: AvexKdf,+ /// How the payload is encrypted.+ #[serde(default)]+ pub encryption: AvexEncryption,+ /// When and by which app version the export was written.+ #[serde(default)]+ pub metadata: AvexMetadata,+}++/// Key derivation of an .avex file.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct AvexKdf {+ /// The KDF name; only Argon2id is read.+ #[serde(rename = "type")]+ pub kdf_type: String,+ /// The base64 salt.+ pub salt: String,+ /// The Argon2id cost parameters.+ pub params: AvexKdfParams,+}++/// Argon2id cost parameters, keyed like the account's `EncryptionSettings`.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "PascalCase")]+pub struct AvexKdfParams {+ /// Number of lanes.+ pub degree_of_parallelism: u32,+ /// Memory cost in KiB.+ pub memory_size: u32,+ /// Number of passes.+ pub iterations: u32,+}++/// Payload encryption of an .avex file.+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AvexEncryption {+ /// Always AES-256-GCM.+ #[serde(default)]+ pub algorithm: String,+ /// Byte offset of the payload; informative only, the reader looks for the delimiter.+ #[serde(default)]+ pub encrypted_data_offset: u64,+}++/// Export metadata of an .avex file.+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AvexMetadata {+ /// ISO 8601 time of the export.+ #[serde(default)]+ pub exported_at: String,+ /// The app version that wrote the export.+ #[serde(default)]+ pub app_version: Option<String>,+}++/// Encrypt .avux bytes into an .avex file under the export password.+pub fn avex_encrypt(avux: &[u8], password: &str, exported_at: &str, app_version: &str) -> VaultResult<Vec<u8>> {+ let salt = base64_encode(&random_bytes(AVEX_SALT_LENGTH));+ let key = derive_key(password, &salt, AVEX_KDF_PARAMS).map_err(|e| VaultError::General(e.to_string()))?;+ let payload = aes_gcm::encrypt(avux, &key, &[])?;++ let mut header = AvexHeader {+ format: AVEX_FORMAT.to_string(),+ version: AVEX_FORMAT_VERSION.to_string(),+ kdf: AvexKdf { kdf_type: AVEX_KDF_TYPE.to_string(), salt, params: AVEX_KDF_PARAMS },+ encryption: AvexEncryption { algorithm: AVEX_ENCRYPTION_ALGORITHM.to_string(), encrypted_data_offset: 0 },+ metadata: AvexMetadata { exported_at: exported_at.to_string(), app_version: Some(app_version.to_string()) },+ };++ // The header records the payload offset, which changes the header length: repeat until the offset is stable.+ let mut header_json = serde_json::to_string_pretty(&header)?;+ loop {+ let offset = (header_json.len() + AVEX_HEADER_DELIMITER.len()) as u64;+ if offset == header.encryption.encrypted_data_offset {+ break;+ }+ header.encryption.encrypted_data_offset = offset;+ header_json = serde_json::to_string_pretty(&header)?;+ }++ let mut file = Vec::with_capacity(header_json.len() + AVEX_HEADER_DELIMITER.len() + payload.len());+ file.extend_from_slice(header_json.as_bytes());+ file.extend_from_slice(AVEX_HEADER_DELIMITER.as_bytes());+ file.extend_from_slice(&payload);+ Ok(file)+}++/// Read and check the header of an .avex file.+pub fn avex_parse_header(avex: &[u8]) -> Result<AvexHeader, AvexError> {+ split(avex).map(|(header, _)| header)+}++/// Decrypt an .avex file into its .avux bytes.+pub fn avex_decrypt(avex: &[u8], password: &str) -> Result<Zeroizing<Vec<u8>>, AvexError> {+ let (header, payload) = split(avex)?;+ let key = derive_key(password, &header.kdf.salt, header.kdf.params).map_err(|e| AvexError::InvalidFile(e.to_string()))?;+ aes_gcm::decrypt(payload, &key, &[]).map(Zeroizing::new).map_err(|_| AvexError::Decryption)+}++/// The checked header and the encrypted payload.+fn split(avex: &[u8]) -> Result<(AvexHeader, &[u8]), AvexError> {+ let delimiter = AVEX_HEADER_DELIMITER.as_bytes();+ let index = avex.windows(delimiter.len()).position(|window| window == delimiter).ok_or_else(|| AvexError::InvalidFile("header delimiter not found".to_string()))?;+ let header: AvexHeader = serde_json::from_slice(&avex[..index]).map_err(|e| AvexError::InvalidFile(e.to_string()))?;++ if header.format != AVEX_FORMAT {+ return Err(AvexError::InvalidFile(format!("expected format '{}', got '{}'", AVEX_FORMAT, header.format)));+ }+ if header.version != AVEX_FORMAT_VERSION {+ return Err(AvexError::InvalidFile(format!("unsupported version {}, expected {}", header.version, AVEX_FORMAT_VERSION)));+ }+ if !header.kdf.kdf_type.eq_ignore_ascii_case(AVEX_KDF_TYPE) {+ return Err(AvexError::InvalidFile(format!("unsupported KDF type {}, only Argon2id is supported", header.kdf.kdf_type)));+ }++ Ok((header, &avex[index + delimiter.len()..]))+}++/// The base64 AES key derived from the password; the salt is hashed as the characters of its base64 string.+fn derive_key(password: &str, salt: &str, params: AvexKdfParams) -> Result<Zeroizing<String>, Argon2Error> {+ let params = Argon2Params { memory_kib: params.memory_size, iterations: params.iterations, parallelism: params.degree_of_parallelism };+ let key = argon2_derive_key(password.as_bytes(), salt.as_bytes(), params)?;+ Ok(Zeroizing::new(base64_encode(&key)))+}diff --git a/core/rust/src/crypto/mod.rs b/core/rust/src/crypto/mod.rsindex 0a5bd180d..540992874 100644--- a/core/rust/src/crypto/mod.rs+++ b/core/rust/src/crypto/mod.rs@@ -3,6 +3,7 @@//! - [`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.@@ -18,6 +19,7 @@pub mod aad;pub mod aes_gcm;pub mod argon2;+pub mod avex;pub(crate) mod jwk;pub mod key_chain;pub mod mobile_login;@@ -31,13 +33,14 @@ pub mod vault_blob;#[cfg(test)]mod tests;+pub use avex::{avex_decrypt, avex_encrypt, avex_parse_header, AvexError, AvexHeader};pub use key_chain::{account_signing_key_fingerprint, create_account_key_hierarchy, derive_srp_password_hash, open_account_private_key, open_account_signing_private_key,decrypt_account_key, decrypt_key, encrypt_key, open_key_chain_with_account_key, open_key_chain_with_unlock_key, reencrypt_account_key, rotate_account_keys, AccountKeyBlobs, AccountKeyHierarchy, KeyChainError,RotatedAccountKeys, SrpInputError,};pub use mobile_login::{mobile_login_open_approval, mobile_login_public_key_hash, mobile_login_verification_code, MobileLoginApproval};-pub use pin::{pin_decrypt, pin_encrypt, pin_generate_salt, pin_is_locked, pin_register_failure, PinFailure};+pub use pin::{pin_decrypt, pin_encrypt, pin_extension_salt, 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;pub use vault_blob::{vault_blob_decrypt, vault_blob_encrypt};diff --git a/core/rust/src/crypto/pin.rs b/core/rust/src/crypto/pin.rsindex 7f54aa742..c15361b38 100644--- a/core/rust/src/crypto/pin.rs+++ b/core/rust/src/crypto/pin.rs@@ -1,6 +1,7 @@//! PIN unlock: the key encrypted with the PIN and the failed-attempt policy.use serde::Serialize;+use sha2::{Digest, Sha256};use zeroize::Zeroizing;use crate::common::error::{VaultError, VaultResult};@@ -36,6 +37,15 @@ pub fn pin_generate_salt() -> Vec<u8> {random_bytes(PIN_SALT_LENGTH)}+/// 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()));+ base64_encode(&combined).into_bytes()+}+/// Encrypt `secret` with a key derived from the PIN and salt. Returns `IV | ciphertext | tag`.pub fn pin_encrypt(pin: &str, salt: &[u8], secret: &[u8]) -> VaultResult<Vec<u8>> {aes_gcm::encrypt(secret, &derive_pin_key(pin, salt)?, &[])diff --git a/core/rust/src/crypto/tests/avex.rs b/core/rust/src/crypto/tests/avex.rsnew file mode 100644index 000000000..c0e6448a2--- /dev/null+++ b/core/rust/src/crypto/tests/avex.rs@@ -0,0 +1,43 @@+use crate::crypto::avex::*;++/// An export written by a 0.28.0 client; a failure means released exports no longer import.+const FIXTURE: &[u8] = include_bytes!("../../../../client/src/transfer/import/importers/aliasvault/__tests__/aliasvault.avex");+const FIXTURE_PASSWORD: &str = "testexportpass123";++#[test]+fn decrypts_a_released_export() {+ let header = avex_parse_header(FIXTURE).unwrap();+ assert_eq!(header.metadata.app_version.as_deref(), Some("0.28.0-alpha-dev"));+ let avux = avex_decrypt(FIXTURE, FIXTURE_PASSWORD).unwrap();+ assert!(avux.starts_with(b"PK\x03\x04"), "the payload is the .avux zip");+}++#[test]+fn rejects_a_wrong_password() {+ assert_eq!(avex_decrypt(FIXTURE, "wrong-password"), Err(AvexError::Decryption));+}++#[test]+fn round_trips_with_the_export_parameters() {+ let avex = avex_encrypt(b"avux bytes", "export-password", "2026-10-26T10:00:00.000Z", "0.31.0").unwrap();+ let header = avex_parse_header(&avex).unwrap();+ assert_eq!((header.format.as_str(), header.version.as_str(), header.kdf.kdf_type.as_str()), (AVEX_FORMAT, AVEX_FORMAT_VERSION, "Argon2Id"));+ assert_eq!(header.kdf.params, AvexKdfParams { degree_of_parallelism: 1, memory_size: 262144, iterations: 3 });+ assert_eq!(header.metadata, AvexMetadata { exported_at: "2026-10-26T10:00:00.000Z".to_string(), app_version: Some("0.31.0".to_string()) });++ let offset = header.encryption.encrypted_data_offset as usize;+ assert_eq!(&avex[offset - AVEX_HEADER_DELIMITER.len()..offset], AVEX_HEADER_DELIMITER.as_bytes(), "the recorded offset points at the payload");+ assert_eq!(*avex_decrypt(&avex, "export-password").unwrap(), b"avux bytes");+}++#[test]+fn rejects_files_it_does_not_read() {+ let with_header = |json: &str| [json.as_bytes(), AVEX_HEADER_DELIMITER.as_bytes(), b"payload"].concat();+ let kdf = r#""kdf":{"type":"Argon2Id","salt":"c2FsdHNhbHQ=","params":{"DegreeOfParallelism":1,"MemorySize":19456,"Iterations":2}}"#;++ assert!(matches!(avex_parse_header(b"not an export"), Err(AvexError::InvalidFile(_))));+ assert!(avex_parse_header(&with_header(&format!(r#"{{"format":"avex","version":"1.0.0",{kdf}}}"#))).is_ok());+ assert!(matches!(avex_parse_header(&with_header(&format!(r#"{{"format":"avux","version":"1.0.0",{kdf}}}"#))), Err(AvexError::InvalidFile(_))));+ assert!(matches!(avex_parse_header(&with_header(&format!(r#"{{"format":"avex","version":"2.0.0",{kdf}}}"#))), Err(AvexError::InvalidFile(_))));+ assert!(matches!(avex_parse_header(&with_header(&format!(r#"{{"format":"avex","version":"1.0.0",{}}}"#, kdf.replace("Argon2Id", "Pbkdf2")))), Err(AvexError::InvalidFile(_))));+}diff --git a/core/rust/src/crypto/tests/mod.rs b/core/rust/src/crypto/tests/mod.rsindex fe18fdbb5..9d707c562 100644--- a/core/rust/src/crypto/tests/mod.rs+++ b/core/rust/src/crypto/tests/mod.rs@@ -4,6 +4,7 @@mod aad;mod aes_gcm;mod argon2;+mod avex;mod jwk;mod key_chain;mod mobile_login;diff --git a/core/rust/src/crypto/tests/pin.rs b/core/rust/src/crypto/tests/pin.rsindex 93c8cfb5f..ba84c4da4 100644--- a/core/rust/src/crypto/tests/pin.rs+++ b/core/rust/src/crypto/tests/pin.rs@@ -33,3 +33,11 @@ fn locks_after_the_maximum_attempts() {assert_eq!(pin_register_failure(3), PinFailure { failed_attempts: 4, attempts_remaining: 0, locked: true });assert_eq!(pin_register_failure(u32::MAX), PinFailure { failed_attempts: u32::MAX, attempts_remaining: 0, locked: true });}++/// Known answer: changing the composition locks every extension user out of their PIN.+#[test]+fn composes_the_extension_salt() {+ let salt: Vec<u8> = (0..16).collect();+ let extension_salt = pin_extension_salt(&salt, "kbfnbcaeplbcioakkpcpgfkobkghlhen");+ assert_eq!(String::from_utf8(extension_salt).unwrap(), "AAECAwQFBgcICQoLDA0OD4eGMIgKFBN57SzMx9wUAqplk99xzEeBHTBkcKcQ1JQ+");+}diff --git a/core/rust/src/lib.rs b/core/rust/src/lib.rsindex 17574c963..cf59cb030 100644--- a/core/rust/src/lib.rs+++ b/core/rust/src/lib.rs@@ -13,7 +13,7 @@//! - **password_generator**: Password and passphrase (Diceware) generation//! - **totp**: RFC 6238 TOTP code generation//! - **identity_generator**: Random identity (alias persona) generation-//! - **crypto**: Argon2id derivation, AES-256-GCM, RSA-OAEP, the account key hierarchy and the SRP-6a handshake+//! - **crypto**: Argon2id derivation, AES-256-GCM, the .avex export, RSA-OAEP, the account key hierarchy and the SRP-6a handshake//! - **common**: `VaultError`, byte encodings, randomness and the vault timestamp formats//! - **bindings**: the wasm-bindgen and UniFFI entry pointsdiff --git a/docs/docs/security-whitepaper.mdx b/docs/docs/security-whitepaper.mdxindex 3756ccbcf..f01ab02f8 100644--- a/docs/docs/security-whitepaper.mdx+++ b/docs/docs/security-whitepaper.mdx@@ -531,7 +531,7 @@ Where each part of this document lives in the repository, for reviewers.| API: authentication, vault, sharing, email, Login with Mobile | `apps/server/AliasVault.Api/Controllers/V2/` || Session tokens | `apps/server/AliasVault.Api/Services/TokenService.cs` || Device key storage | iOS `apps/mobile-app/ios/VaultStoreKit/`, Android `apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/`, extension `apps/browser-extension/src/utils/PinUnlockService.ts`, web app `apps/web/src/utils/WebAuthnService.ts` |-| Encrypted export | `core/client/src/transfer/export/AvexExportService.ts`, `core/client/src/transfer/import/importers/aliasvault/AvexImportService.ts` |+| Encrypted export | `core/rust/src/crypto/avex.rs` || Logo fetching | `core/client/src/items/FaviconService.ts`, `apps/server/Utilities/AliasVault.FaviconExtractor/` |## Appendix B. Glossary