Skip to content

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

Update test helpers (#2159)

Leendert de Borstc01aabdbd68f
diff --git a/apps/browser-extension/tests/helpers/client-platform.ts b/apps/browser-extension/tests/helpers/client-platform.ts
new file mode 100644
index 000000000..a81944533
--- /dev/null
+++ b/apps/browser-extension/tests/helpers/client-platform.ts
@@ -0,0 +1,28 @@
+/**
+ * Node-side platform registration for the shared client core (`@aliasvault/client`).
+ *
+ * Import this module for its side effect from any helper that touches the core.
+ */
+
+import { readFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { setPlatform } from '@aliasvault/client/platform';
+import { createInMemoryPlatform } from '@aliasvault/client/platform/InMemoryPlatform';
+
+const clientCoreDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../core/client');
+const requireFromClientCore = createRequire(path.join(clientCoreDir, 'package.json'));
+
+setPlatform(createInMemoryPlatform({
+ /**
+ * Load the Rust core WASM from the client core build output.
+ */
+ loadRustCoreWasm: async (): Promise<BufferSource> => readFileSync(path.join(clientCoreDir, 'wasm/aliasvault_core_bg.wasm')),
+ /**
+ * Locate a sql.js support file in the client core's node_modules.
+ * @param file - the file name sql.js asks for
+ */
+ locateSqlJsFile: (file: string): string => path.join(path.dirname(requireFromClientCore.resolve('sql.js')), file),
+}));
diff --git a/apps/browser-extension/tests/helpers/manifest-v2-api.ts b/apps/browser-extension/tests/helpers/manifest-v2-api.ts
index c482c56c9..fcd784195 100644
--- a/apps/browser-extension/tests/helpers/manifest-v2-api.ts
+++ b/apps/browser-extension/tests/helpers/manifest-v2-api.ts
@@ -3,17 +3,16 @@
*
* Lets a test act as a second, "newer" client against the v2 Vault API: pull the snapshot,
* decrypt + unpack the personal manifest, modify it (e.g. inject columns/tables an older client's
- * schema doesn't know), and push it back as a new revision. Pack/unpack goes through the real
- * Rust WASM codec so the integrity envelope's canonical content hash matches exactly what the
- * extension verifies on pull.
+ * schema doesn't know), and push it back as a new revision. Everything below the wire format goes
+ * through the shared client core the extension itself ships.
*/
import { createHash } from 'crypto';
-import { vaultCodecPackPayload, vaultCodecUnpackPayload } from '@aliasvault/client/wasm/aliasvault_core.js';
+import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
+import { getSyncableTableNames, vaultCodecCanonicalizeFromSqlite, vaultCodecGenerateManifestSalt, vaultCodecPackPayload, vaultCodecUnpackPayload } from '@aliasvault/client/rust/RustCore';
-import { ensureRustCore } from './rust-core';
-import { normalizeUsername, symmetricDecryptBytes, symmetricEncryptBytes } from './test-api';
+import { symmetricDecryptBytes, symmetricEncryptBytes } from './vault-crypto';
/** One manifest entry in the v2 GET snapshot. */
export type SnapshotManifest = {
@@ -50,6 +49,32 @@ export type DecryptedManifest = {
[key: string]: unknown;
};
+/** One manifest element of a POST /v2/Vault write. */
+type ManifestWrite = {
+ manifestId: string;
+ manifestBlob: string;
+ manifestCiphertextHash: string;
+ currentRevision: number;
+ credentialsCount: number;
+ blobReferences: Array<{ hash: string; category: string }>;
+};
+
+/** One data bucket element of a POST /v2/Vault write. */
+type BucketWrite = {
+ manifestId: string;
+ category: string;
+ blob: string;
+ ciphertextHash: string;
+ currentRevision: number;
+};
+
+/** The result of a POST /v2/Vault write. */
+type VaultWriteResult = {
+ status: number;
+ manifestRevisions?: Array<{ manifestId: string; revision: number }>;
+ missingBlobHashes?: string[];
+};
+
/**
* Fetches the v2 vault snapshot for the authenticated user.
*
@@ -118,9 +143,8 @@ export async function resolveVaultEncryptionKey(apiBaseUrl: string, token: strin
* @returns The decrypted manifest object
*/
export async function openManifest(blobBase64: string, encryptionKey: Uint8Array): Promise<DecryptedManifest> {
- ensureRustCore();
const packedBytes = await symmetricDecryptBytes(blobBase64, encryptionKey);
- return JSON.parse(vaultCodecUnpackPayload(packedBytes)) as DecryptedManifest;
+ return JSON.parse(await vaultCodecUnpackPayload(packedBytes)) as DecryptedManifest;
}
/**
@@ -147,53 +171,54 @@ export async function pushManifest(
blobReferences: Array<{ hash: string; category: string }>,
encryptionKey: Uint8Array
): Promise<number> {
- ensureRustCore();
- const packedBytes = vaultCodecPackPayload(JSON.stringify(manifest));
- const manifestBlob = await symmetricEncryptBytes(packedBytes, encryptionKey);
- const manifestCiphertextHash = createHash('sha256').update(Buffer.from(manifestBlob, 'base64')).digest('hex');
+ const write = await buildManifestWrite(manifestId, manifest, currentRevision, blobReferences, encryptionKey);
+ const result = await postVaultWrite(apiBaseUrl, token, username, [write], []);
+
+ const written = (result.manifestRevisions ?? []).find((r) => r.manifestId === manifestId);
+ if (!written) {
+ throw new Error(`Manifest push returned no revision for ${manifestId}.`);
+ }
+ return written.revision;
+}
+
+/**
+ * Writes the first manifest-v1 revision for a newly registered account.
+ *
+ * @param apiBaseUrl - The base URL of the API
+ * @param token - Bearer token
+ * @param username - The vault owner's username
+ * @param encryptionKey - The account's VEK, which the vault content is encrypted with
+ * @returns The id of the personal manifest that was written
+ */
+export async function pushInitialVault(apiBaseUrl: string, token: string, username: string, encryptionKey: Uint8Array): Promise<string> {
+ const snapshot = await getVaultSnapshot(apiBaseUrl, token);
+ const manifestId = snapshot.personalManifestId;
+ if (!manifestId) {
+ throw new Error('Freshly registered account has no personal manifest to write the initial vault into.');
+ }
/*
- * POST /v2/Vault is one atomic write over a list of manifests; every entry names the manifest it targets, so this
- * simulated "newer client" addresses the personal manifest by id exactly as a real client does.
+ * A brand-new vault is every syncable table, all empty. Taking the list from the shared table registry keeps
+ * this in step with the schema: canonicalize refuses a manifest that carries no tables at all.
*/
- const payload = {
- username: normalizeUsername(username),
- manifests: [{
- manifestId,
- manifestBlob,
- manifestCiphertextHash,
- currentRevision,
- credentialsCount: (manifest.tables.Items ?? []).length,
- blobReferences,
- }],
- buckets: [],
- newBlobs: [],
- emailRouting: null,
- };
-
- const response = await fetch(`${apiBaseUrl.replace(/\/$/, '')}/v2/Vault`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
- body: JSON.stringify(payload),
+ const tables = (await getSyncableTableNames()).map((name) => ({ name, records: [] }));
+ const canonicalized = await vaultCodecCanonicalizeFromSqlite({
+ tables,
+ canonicalizedAt: new Date().toISOString(),
+ manifests: [{ manifestId, manifestSalt: await vaultCodecGenerateManifestSalt(), name: null }],
});
- if (!response.ok) {
- throw new Error(`POST /v2/Vault failed with status ${response.status}: ${await response.text()}`);
- }
- const result = (await response.json()) as {
- status: number;
- manifestRevisions?: Array<{ manifestId: string; revision: number }>;
- missingBlobHashes?: string[];
- };
- if (result.status !== 0 || (result.missingBlobHashes?.length ?? 0) > 0) {
- throw new Error(`Manifest push rejected: status=${result.status}, missingBlobs=${result.missingBlobHashes?.join(',') ?? 'none'}`);
- }
+ const manifest = canonicalized.manifests[0].manifest as DecryptedManifest;
+ const manifestWrite = await buildManifestWrite(manifestId, manifest, 0, [], encryptionKey);
- const written = (result.manifestRevisions ?? []).find((r) => r.manifestId === manifestId);
- if (!written) {
- throw new Error(`Manifest push returned no revision for ${manifestId}.`);
+ const bucketWrites: BucketWrite[] = [];
+ for (const bucket of canonicalized.dataBuckets) {
+ const { blob, ciphertextHash } = await packEncrypt(JSON.stringify(bucket), encryptionKey);
+ bucketWrites.push({ manifestId: bucket.manifestId, category: bucket.category, blob, ciphertextHash, currentRevision: 0 });
}
- return written.revision;
+
+ await postVaultWrite(apiBaseUrl, token, username, [manifestWrite], bucketWrites);
+ return manifestId;
}
/**
@@ -220,3 +245,85 @@ export async function pollUntil<T>(predicate: () => Promise<T | undefined | fals
}
throw new Error(`pollUntil timed out after ${timeoutMs}ms${lastError ? `; last error: ${lastError instanceof Error ? lastError.message : String(lastError)}` : ''}`);
}
+
+/**
+ * Packs a payload through the Rust codec and encrypts it.
+ *
+ * @param payloadJson - The payload to pack
+ * @param encryptionKey - The key the vault content is encrypted with
+ * @returns The encrypted blob and the ciphertext hash the server verifies it against
+ */
+async function packEncrypt(payloadJson: string, encryptionKey: Uint8Array): Promise<{ blob: string; ciphertextHash: string }> {
+ const packedBytes = await vaultCodecPackPayload(payloadJson);
+ const blob = await symmetricEncryptBytes(packedBytes, encryptionKey);
+ return { blob, ciphertextHash: createHash('sha256').update(Buffer.from(blob, 'base64')).digest('hex') };
+}
+
+/**
+ * Builds one manifest element of a vault write.
+ *
+ * @param manifestId - The manifest this write targets
+ * @param manifest - The manifest object to upload
+ * @param currentRevision - The revision this upload is based on
+ * @param blobReferences - Blob references to carry over to the new revision
+ * @param encryptionKey - The key the vault content is encrypted with
+ * @returns The manifest write element
+ */
+async function buildManifestWrite(
+ manifestId: string,
+ manifest: DecryptedManifest,
+ currentRevision: number,
+ blobReferences: Array<{ hash: string; category: string }>,
+ encryptionKey: Uint8Array
+): Promise<ManifestWrite> {
+ const { blob, ciphertextHash } = await packEncrypt(JSON.stringify(manifest), encryptionKey);
+ return {
+ manifestId,
+ manifestBlob: blob,
+ manifestCiphertextHash: ciphertextHash,
+ currentRevision,
+ credentialsCount: (manifest.tables.Items ?? []).length,
+ blobReferences,
+ };
+}
+
+/**
+ * Sends a atomic POST /v2/Vault write.
+ *
+ * @param apiBaseUrl - The base URL of the API
+ * @param token - Bearer token
+ * @param username - The vault owner's username
+ * @param manifests - The manifests this write targets, each addressed by id exactly as a real client does
+ * @param buckets - The data buckets this write targets
+ * @returns The write result
+ */
+async function postVaultWrite(
+ apiBaseUrl: string,
+ token: string,
+ username: string,
+ manifests: ManifestWrite[],
+ buckets: BucketWrite[]
+): Promise<VaultWriteResult> {
+ const payload = {
+ username: SrpAuthService.normalizeUsername(username),
+ manifests,
+ buckets,
+ newBlobs: [],
+ emailRouting: null,
+ };
+
+ const response = await fetch(`${apiBaseUrl.replace(/\/$/, '')}/v2/Vault`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
+ body: JSON.stringify(payload),
+ });
+ if (!response.ok) {
+ throw new Error(`POST /v2/Vault failed with status ${response.status}: ${await response.text()}`);
+ }
+
+ const result = (await response.json()) as VaultWriteResult;
+ if (result.status !== 0 || (result.missingBlobHashes?.length ?? 0) > 0) {
+ throw new Error(`Vault write rejected: status=${result.status}, missingBlobs=${result.missingBlobHashes?.join(',') ?? 'none'}`);
+ }
+ return result;
+}
diff --git a/apps/browser-extension/tests/helpers/rust-core.ts b/apps/browser-extension/tests/helpers/rust-core.ts
deleted file mode 100644
index a1aedd570..000000000
--- a/apps/browser-extension/tests/helpers/rust-core.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-/**
- * Node-side loader for the AliasVault Rust core (WASM).
- */
-
-import { readFileSync } from 'fs';
-import { join } from 'path';
-
-import { initSync } from '@aliasvault/client/wasm/aliasvault_core.js';
-
-let wasmInitialized = false;
-
-/**
- * Initializes the Rust core WASM module from the linked client core package (idempotent).
- */
-export function ensureRustCore(): void {
- if (!wasmInitialized) {
- const wasmPath = join(process.cwd(), 'node_modules/@aliasvault/client/wasm/aliasvault_core_bg.wasm');
- initSync({ module: readFileSync(wasmPath) });
- wasmInitialized = true;
- }
-}
diff --git a/apps/browser-extension/tests/helpers/test-api.ts b/apps/browser-extension/tests/helpers/test-api.ts
index 093b0c5cb..4008134ee 100644
--- a/apps/browser-extension/tests/helpers/test-api.ts
+++ b/apps/browser-extension/tests/helpers/test-api.ts
@@ -1,31 +1,18 @@
/**
* Test API utilities for E2E tests.
*
- * This module provides utilities for interacting with the AliasVault API
- * during E2E tests, including user registration using SRP protocol.
+ * This module provides utilities for interacting with the AliasVault API during E2E tests.
*/
-import { webcrypto } from 'crypto';
-import { readFileSync, unlinkSync } from 'fs';
-import { tmpdir } from 'os';
-import { join } from 'path';
-
-import Database from 'better-sqlite3';
+import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
+import { base64ToBytes } from '@aliasvault/client/utilities/Base64';
import * as OTPAuth from 'otpauth';
-import { argon2DeriveKey, srpDerivePrivateKey, srpDeriveVerifier, srpGenerateSalt } from '@aliasvault/client/wasm/aliasvault_core.js';
-// Get the vault schema SQL from the core vault package
-import { COMPLETE_SCHEMA_SQL, VAULT_VERSIONS } from '../../../../core/vault/dist/index.mjs';
+import { pushInitialVault } from './manifest-v2-api';
-import { ensureRustCore } from './rust-core';
+import './client-platform';
-/**
- * Token model returned from successful registration/login.
- */
-export type TokenModel = {
- token: string;
- refreshToken: string;
-};
+import type { TokenModel } from '@aliasvault/models/webapi';
/**
* Test user credentials.
@@ -36,61 +23,10 @@ export type TestUser = {
token?: TokenModel;
/** TOTP secret if 2FA is enabled */
totpSecret?: string;
- /** Argon2Id-derived vault encryption key, for tests that decrypt/re-encrypt vault blobs API-side. */
+ /** Argon2Id password-derived key (the KEK), for tests that walk the account key chain API-side. */
encryptionKey?: Uint8Array;
};
-/**
- * Vault upload request payload.
- */
-type VaultUploadRequest = {
- username: string;
- blob: string;
- version: string;
- currentRevisionNumber: number;
- encryptionPublicKey: string;
- credentialsCount: number;
- emailAddressList: string[];
- privateEmailDomainList: string[];
- hiddenPrivateEmailDomainList: string[];
- publicEmailDomainList: string[];
- createdAt: string;
- updatedAt: string;
-};
-
-/**
- * Registration request payload.
- * This matches the server's RegisterRequest model.
- */
-type RegisterRequest = {
- username: string;
- salt: string;
- verifier: string;
- encryptionType: string;
- encryptionSettings: string;
-};
-
-/**
- * Default encryption settings for Argon2Id.
- * These match the server defaults in AliasVault.Cryptography.Client/Defaults.cs
- */
-const DEFAULT_ENCRYPTION = {
- type: 'Argon2Id',
- settings: JSON.stringify({
- DegreeOfParallelism: 1,
- MemorySize: 19456,
- Iterations: 2,
- }),
-};
-
-/**
- * Normalizes a username by converting to lowercase and trimming whitespace.
- * This matches the server's username normalization.
- */
-export function normalizeUsername(username: string): string {
- return username.toLowerCase().trim();
-}
-
/**
* Generates a random test username.
*/
@@ -113,262 +49,12 @@ export function generateTestPassword(): string {
}
/**
- * Converts a Uint8Array to an uppercase hex string.
- */
-function bytesToHexString(bytes: Uint8Array): string {
- return Array.from(bytes)
- .map((b) => b.toString(16).padStart(2, '0'))
- .join('')
- .toUpperCase();
-}
-
-/**
- * Derives a key from password using Argon2Id, through the extension's own Rust core.
- *
- * @param password - The password to derive the key from
- * @param salt - The salt string, hashed as its UTF-8 bytes
- * @returns The derived key as Uint8Array
- */
-function deriveKeyFromPassword(password: string, salt: string): Uint8Array {
- ensureRustCore();
- return argon2DeriveKey(password, salt, DEFAULT_ENCRYPTION.settings);
-}
-
-/**
- * Encrypts data using AES-GCM symmetric encryption (matching the browser extension's EncryptionUtility).
- *
- * @param plaintext - The plaintext string to encrypt
- * @param keyBytes - The 256-bit encryption key as Uint8Array
- * @returns Base64-encoded ciphertext (IV prepended to ciphertext)
- */
-async function symmetricEncrypt(plaintext: string, keyBytes: Uint8Array): Promise<string> {
- const key = await webcrypto.subtle.importKey(
- 'raw',
- keyBytes,
- { name: 'AES-GCM', length: 256 },
- false,
- ['encrypt']
- );
-
- // Generate random 12-byte IV
- const iv = webcrypto.getRandomValues(new Uint8Array(12));
-
- // Encode plaintext to bytes
- const encoder = new TextEncoder();
- const plaintextBytes = encoder.encode(plaintext);
-
- // Encrypt
- const ciphertext = await webcrypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, plaintextBytes);
-
- // Prepend IV to ciphertext
- const combined = new Uint8Array(iv.length + ciphertext.byteLength);
- combined.set(iv);
- combined.set(new Uint8Array(ciphertext), iv.length);
-
- // Convert to base64
- return Buffer.from(combined).toString('base64');
-}
-
-/**
- * Encrypts raw bytes using AES-GCM (matching the browser extension's `symmetricEncryptBytes`).
- *
- * @param plaintextBytes - The plaintext bytes to encrypt
- * @param keyBytes - The 256-bit encryption key as Uint8Array
- * @returns Base64-encoded ciphertext (IV prepended to ciphertext)
- */
-export async function symmetricEncryptBytes(plaintextBytes: Uint8Array, keyBytes: Uint8Array): Promise<string> {
- const key = await webcrypto.subtle.importKey('raw', keyBytes, { name: 'AES-GCM', length: 256 }, false, ['encrypt']);
- const iv = webcrypto.getRandomValues(new Uint8Array(12));
- const ciphertext = await webcrypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, plaintextBytes);
-
- const combined = new Uint8Array(iv.length + ciphertext.byteLength);
- combined.set(iv);
- combined.set(new Uint8Array(ciphertext), iv.length);
- return Buffer.from(combined).toString('base64');
-}
-
-/**
- * Decrypts an AES-GCM ciphertext produced by the extension's `symmetricEncrypt(Bytes)` (IV-prefixed).
- *
- * @param base64Ciphertext - Base64-encoded ciphertext (12-byte IV prepended)
- * @param keyBytes - The 256-bit encryption key as Uint8Array
- * @returns The decrypted plaintext bytes
- */
-export async function symmetricDecryptBytes(base64Ciphertext: string, keyBytes: Uint8Array): Promise<Uint8Array> {
- const combined = new Uint8Array(Buffer.from(base64Ciphertext, 'base64'));
- const key = await webcrypto.subtle.importKey('raw', keyBytes, { name: 'AES-GCM', length: 256 }, false, ['decrypt']);
- const plaintext = await webcrypto.subtle.decrypt({ name: 'AES-GCM', iv: combined.slice(0, 12) }, key, combined.slice(12));
- return new Uint8Array(plaintext);
-}
-
-/**
- * Creates an empty vault database with the latest schema.
- *
- * @returns Base64-encoded SQLite database
- */
-function createEmptyVaultDatabase(): string {
- // Create a temporary file for the database
- const tempPath = join(tmpdir(), `vault_${Date.now()}_${Math.random().toString(36).substring(2)}.db`);
-
- try {
- // Create a new SQLite database
- const db = new Database(tempPath);
-
- // Execute the complete schema SQL to create all tables
- // The schema is a series of SQL statements separated by semicolons
- db.exec(COMPLETE_SCHEMA_SQL);
-
- // Close the database
- db.close();
-
- // Read the database file and convert to base64
- const dbBytes = readFileSync(tempPath);
- return Buffer.from(dbBytes).toString('base64');
- } finally {
- // Clean up the temp file
- try {
- unlinkSync(tempPath);
- } catch {
- // Ignore cleanup errors
- }
- }
-}
-
-/**
- * Generates an RSA key pair for the vault's encryption key.
- *
- * @returns Object with public and private keys as JSON strings
- */
-async function generateRsaKeyPair(): Promise<{ publicKey: string; privateKey: string }> {
- const keyPair = await webcrypto.subtle.generateKey(
- {
- name: 'RSA-OAEP',
- modulusLength: 2048,
- publicExponent: new Uint8Array([1, 0, 1]),
- hash: 'SHA-256',
- },
- true,
- ['encrypt', 'decrypt']
- );
-
- const publicKey = await webcrypto.subtle.exportKey('jwk', keyPair.publicKey);
- const privateKey = await webcrypto.subtle.exportKey('jwk', keyPair.privateKey);
-
- return {
- publicKey: JSON.stringify(publicKey),
- privateKey: JSON.stringify(privateKey),
- };
-}
-
-/**
- * Prepares SRP registration data for a new user.
- *
- * @param username - The username for registration
- * @param password - The password for registration
- * @returns Registration request data and the encryption key
- */
-async function prepareRegistration(
- username: string,
- password: string
-): Promise<{ request: RegisterRequest; salt: string; encryptionKey: Uint8Array }> {
- const normalizedUsername = normalizeUsername(username);
-
- ensureRustCore();
-
- // Generate salt and derive key from password
- const salt = srpGenerateSalt();
- const encryptionKey = deriveKeyFromPassword(password, salt);
-
- // Convert to uppercase hex string (expected by server)
- const passwordHashString = bytesToHexString(encryptionKey);
-
- // Generate SRP private key and verifier
- const privateKey = srpDerivePrivateKey(salt, normalizedUsername, passwordHashString);
- const verifier = srpDeriveVerifier(privateKey);
-
- return {
- request: {
- username: normalizedUsername,
- salt,
- verifier,
- encryptionType: DEFAULT_ENCRYPTION.type,
- encryptionSettings: DEFAULT_ENCRYPTION.settings,
- },
- salt,
- encryptionKey,
- };
-}
-
-/**
- * Uploads an initial empty vault to the server.
- *
- * @param apiBaseUrl - The base URL of the API
- * @param token - The authentication token
- * @param username - The username
- * @param encryptionKey - The encryption key as Uint8Array
- */
-async function uploadInitialVault(
- apiBaseUrl: string,
- token: string,
- username: string,
- encryptionKey: Uint8Array
-): Promise<void> {
- /*
- * Intentionally the v1 endpoint: the initial vault is a legacy sqlite-blob (the v2 endpoint is
- * manifest-only). This mirrors a pre-manifest account, so the first login lands on the extension's
- * upgrade gate; `completeVaultUpgrade` in the fixtures clicks it through to manifest-v1.
- */
- const baseUrl = apiBaseUrl.replace(/\/$/, '') + '/v1/';
-
- // Create an empty vault database
- const vaultBase64 = createEmptyVaultDatabase();
-
- // Encrypt the vault
- const encryptedVault = await symmetricEncrypt(vaultBase64, encryptionKey);
-
- // Generate RSA key pair for the vault
- const rsaKeyPair = await generateRsaKeyPair();
-
- // Prepare the vault upload request
- const now = new Date().toISOString();
- const vaultRequest: VaultUploadRequest = {
- username: normalizeUsername(username),
- blob: encryptedVault,
- version: VAULT_VERSIONS[VAULT_VERSIONS.length - 1].version,
- currentRevisionNumber: 1,
- encryptionPublicKey: rsaKeyPair.publicKey,
- credentialsCount: 0,
- emailAddressList: [],
- privateEmailDomainList: [],
- hiddenPrivateEmailDomainList: [],
- publicEmailDomainList: [],
- createdAt: now,
- updatedAt: now,
- };
-
- // Upload the vault
- const response = await fetch(`${baseUrl}Vault`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${token}`,
- },
- body: JSON.stringify(vaultRequest),
- });
-
- if (!response.ok) {
- const errorText = await response.text();
- throw new Error(`Failed to upload initial vault: ${response.status} ${errorText}`);
- }
-}
-
-/**
- * Registers a new test user via the API using SRP protocol and initializes their vault.
+ * Registers a new test user via the API and writes the first revision of their vault.
*
* @param apiBaseUrl - The base URL of the API (e.g., 'http://localhost:5100')
* @param username - The username for the new account
* @param password - The password for the new account
- * @returns The token model on success
+ * @returns The token model and the password-derived key (KEK) on success
* @throws Error if registration fails
*/
export async function registerTestUser(
@@ -376,39 +62,14 @@ export async function registerTestUser(
username: string,
password: string
): Promise<{ tokenModel: TokenModel; encryptionKey: Uint8Array }> {
- // Normalize the API URL
- const baseUrl = apiBaseUrl.replace(/\/$/, '') + '/v2/';
-
- // Prepare registration data
- const { request: registerRequest, encryptionKey } = await prepareRegistration(username, password);
-
- // Send registration request to API
- const response = await fetch(`${baseUrl}Auth/register`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(registerRequest),
- });
-
- if (!response.ok) {
- const errorText = await response.text();
- let errorMessage = `Registration failed with status ${response.status}`;
- try {
- const errorJson = JSON.parse(errorText);
- errorMessage = errorJson.title || errorJson.message || errorMessage;
- } catch {
- errorMessage = errorText || errorMessage;
- }
- throw new Error(errorMessage);
+ const result = await SrpAuthService.registerUser(apiBaseUrl, username, password);
+ if (!result.success || !result.token || !result.derivedKey || !result.encryptionKey) {
+ throw new Error(result.error ?? 'Registration failed without an error message.');
}
- const tokenModel = (await response.json()) as TokenModel;
-
- // Upload initial empty vault
- await uploadInitialVault(apiBaseUrl, tokenModel.token, username, encryptionKey);
+ await pushInitialVault(apiBaseUrl, result.token.token, username, base64ToBytes(result.encryptionKey));
- return { tokenModel, encryptionKey };
+ return { tokenModel: result.token, encryptionKey: base64ToBytes(result.derivedKey) };
}
/**
diff --git a/apps/browser-extension/tests/helpers/vault-crypto.ts b/apps/browser-extension/tests/helpers/vault-crypto.ts
new file mode 100644
index 000000000..4679b8705
--- /dev/null
+++ b/apps/browser-extension/tests/helpers/vault-crypto.ts
@@ -0,0 +1,30 @@
+/**
+ * AES-GCM helpers for tests that read or write vault ciphertext API-side.
+ */
+
+import { EncryptionUtility } from '@aliasvault/client/crypto/EncryptionUtility';
+import { base64ToBytes, bytesToBase64 } from '@aliasvault/client/utilities/Base64';
+
+import './client-platform';
+
+/**
+ * Encrypts raw bytes, returning base64(IV | ciphertext | authTag).
+ *
+ * @param plaintextBytes - The plaintext bytes to encrypt
+ * @param keyBytes - The 256-bit encryption key
+ * @returns Base64-encoded ciphertext
+ */
+export async function symmetricEncryptBytes(plaintextBytes: Uint8Array, keyBytes: Uint8Array): Promise<string> {
+ return EncryptionUtility.symmetricEncryptBytes(plaintextBytes, bytesToBase64(keyBytes));
+}
+
+/**
+ * Decrypts a ciphertext produced by {@link symmetricEncryptBytes}.
+ *
+ * @param base64Ciphertext - Base64-encoded ciphertext (12-byte IV prepended)
+ * @param keyBytes - The 256-bit encryption key
+ * @returns The decrypted plaintext bytes
+ */
+export async function symmetricDecryptBytes(base64Ciphertext: string, keyBytes: Uint8Array): Promise<Uint8Array> {
+ return EncryptionUtility.symmetricDecryptBytes(base64ToBytes(base64Ciphertext), bytesToBase64(keyBytes));
+}
diff --git a/core/client/src/sync/LegacyStorageModelMigration.ts b/core/client/src/sync/LegacyStorageModelMigration.ts
index 7543d7338..592dacd8d 100644
--- a/core/client/src/sync/LegacyStorageModelMigration.ts
+++ b/core/client/src/sync/LegacyStorageModelMigration.ts
@@ -8,7 +8,7 @@ import { ApiRequestError } from '../api/errors/ApiRequestError';
import { ServerUpdateRequiredError } from '../api/errors/ServerUpdateRequiredError';
import { VaultKeyService } from '../auth/VaultKeyService';
import { StorageKeys } from '../constants/StorageKeys';
-import { mintAccountKeyHierarchy, type AccountKeyBlobs } from '../crypto/AccountKeys';
+import { createAccountKeyHierarchy, type AccountKeyBlobs } from '../crypto/AccountKeys';
import { getPlatform } from '../platform/ClientPlatform';
import { devLog } from '../platform/Logger';
@@ -193,7 +193,7 @@ export async function requiresLegacyAccountKeyMigration(): Promise<boolean> {
* @param kek - the password-derived key this vault is currently encrypted with, which becomes the KEK
*/
export async function prepareLegacyAccountKeyMigration(kek: string): Promise<LegacyAccountKeyMigration> {
- const hierarchy = await mintAccountKeyHierarchy(kek);
+ const hierarchy = await createAccountKeyHierarchy(kek);
return { contentKey: hierarchy.vaultEncryptionKey, accountKeys: hierarchy.accountKeys, accountPrivateKey: hierarchy.accountPrivateKey };
}