Skip to content

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

Add AliasVault import functions ported from .NET (#2413)

Leendert de Borst3186997b93d9
diff --git a/core/client/src/transfer/import/importers/aliasvault/AvexImportService.ts b/core/client/src/transfer/import/importers/aliasvault/AvexImportService.ts
new file mode 100644
index 000000000..0f9cd3735
--- /dev/null
+++ b/core/client/src/transfer/import/importers/aliasvault/AvexImportService.ts
@@ -0,0 +1,128 @@
+import { EncryptionUtility } from '../../../../crypto/EncryptionUtility';
+import { argon2DeriveKey } 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 type { AvexHeader } from '../../../export/AvexHeader';
+
+/**
+ * Thrown when an .avex file cannot be decrypted; most likely the password is wrong.
+ */
+export class AvexDecryptionError extends Error {
+ /**
+ * Create the error.
+ * @param innerError - The error the decryption raised
+ */
+ public constructor(public readonly innerError?: unknown) {
+ super('Failed to decrypt .avex file. The password may be incorrect or the file may be corrupted.');
+ this.name = 'AvexDecryptionError';
+ Object.setPrototypeOf(this, AvexDecryptionError.prototype);
+ }
+}
+
+/**
+ * Reads the .avex encrypted vault export format written by AvexExportService.
+ */
+export class AvexImportService {
+ /**
+ * Decrypt an .avex file to .avux bytes.
+ * @param avexBytes - The .avex file bytes
+ * @param exportPassword - The password to decrypt with
+ * @returns The decrypted .avux bytes
+ * @throws {Error} When the file is not a supported .avex file.
+ * @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));
+
+ try {
+ return await EncryptionUtility.symmetricDecryptBytes(encryptedPayload, bytesToBase64(key));
+ } catch (error) {
+ throw new AvexDecryptionError(error);
+ }
+ }
+
+ /**
+ * Parse 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) ?? '',
+ exportedBy: (metadata ? readString(metadata, 'exportedBy') : 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
+ */
+ 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;
+ }
+
+ return -1;
+ }
+}
diff --git a/core/client/src/transfer/import/importers/aliasvault/AvuxImportService.ts b/core/client/src/transfer/import/importers/aliasvault/AvuxImportService.ts
new file mode 100644
index 000000000..f79772dab
--- /dev/null
+++ b/core/client/src/transfer/import/importers/aliasvault/AvuxImportService.ts
@@ -0,0 +1,235 @@
+import { FieldTypes, isItemType, ItemTypes, type FieldType } from '@aliasvault/models/vault';
+
+import { base64ToBytes } from '../../../../utilities/Base64';
+import { parseDateTime } from '../../../shared/DateTimeUtils';
+import { buildFolderPath } from '../../../shared/FolderPaths';
+import { ZipArchive } from '../../../shared/ZipArchive';
+import { parseJson } from '../../readers/JsonReader';
+
+import { parseAvuxManifest } from './AvuxManifestReader';
+
+import type { AvuxAttachment, AvuxFieldDefinition, AvuxFieldValue, AvuxManifest, AvuxPasskey } from '../../../export/AvuxManifest';
+import type { ImportedAttachment } from '../../models/ImportedAttachment';
+import type { ImportedCredential } from '../../models/ImportedCredential';
+import type { ImportedPasskey } from '../../models/ImportedPasskey';
+
+/**
+ * Imports vault data from the .avux (AliasVault Unencrypted eXport) format: a ZIP archive with a manifest.json,
+ * all attachments and all logos. Logos are embedded into the FaviconBytes of each credential.
+ */
+export class AvuxImportService {
+ /**
+ * Import an .avux file.
+ * @param zipBytes - The .avux file bytes
+ * @returns The credentials, with embedded logo data
+ * @throws {Error} When the archive is invalid or its manifest cannot be read.
+ */
+ public static importFromAvux(zipBytes: Uint8Array): ImportedCredential[] {
+ const archive = ZipArchive.open(zipBytes);
+
+ const manifestText = archive.readText('manifest.json');
+ if (manifestText === null) {
+ throw new Error('Invalid .avux file: manifest.json not found');
+ }
+
+ const manifest = parseAvuxManifest(parseJson(manifestText));
+ if (manifest.version !== '1.0.0') {
+ throw new Error(`Unsupported .avux version: ${manifest.version}. Expected 1.0.0.`);
+ }
+
+ const logoFiles = archive.filesUnder('logos/');
+ const logoDataById = new Map<string, Uint8Array>();
+ for (const logo of manifest.logos) {
+ const fileData = logoFiles.get(logo.relativePath);
+ if (fileData) {
+ logoDataById.set(logo.id, fileData);
+ }
+ }
+
+ return AvuxImportService.convertManifestToImportedCredentials(manifest, archive.filesUnder('attachments/'), logoDataById);
+ }
+
+ /**
+ * Convert the manifest and its files to credentials.
+ * @param manifest - The manifest
+ * @param attachmentMap - Attachment paths to file data
+ * @param logoDataById - Logo ids to image data
+ * @returns The credentials
+ */
+ private static convertManifestToImportedCredentials(manifest: AvuxManifest, attachmentMap: Map<string, Uint8Array>, logoDataById: Map<string, Uint8Array>): ImportedCredential[] {
+ const foldersById = new Map(manifest.folders.map(folder => [folder.id, { Name: folder.name, ParentFolderId: folder.parentFolderId }]));
+ const fieldDefinitionsById = new Map(manifest.fieldDefinitions.map(fd => [fd.id, fd]));
+
+ return manifest.items.map((item): ImportedCredential => {
+ const credential: ImportedCredential = {
+ ServiceName: item.name,
+ CreatedAt: parseDateTime(item.createdAt),
+ UpdatedAt: parseDateTime(item.updatedAt),
+ ItemType: isItemType(item.itemType) ? item.itemType : ItemTypes.Login,
+ };
+
+ if (item.logoId) {
+ const logoBytes = logoDataById.get(item.logoId);
+ if (logoBytes) {
+ credential.FaviconBytes = logoBytes;
+ }
+ }
+
+ if (item.folderId) {
+ credential.FolderPath = foldersById.has(item.folderId) ? buildFolderPath(item.folderId, foldersById) : null;
+ }
+
+ AvuxImportService.extractFieldValues(credential, item.fieldValues, fieldDefinitionsById);
+
+ // The import format carries one TOTP per item.
+ if (item.totpCodes.length > 0) {
+ credential.TwoFactorSecret = item.totpCodes[0].secretKey;
+ }
+
+ if (item.passkeys.length > 0) {
+ credential.Passkeys = item.passkeys.map(AvuxImportService.mapAvuxPasskeyToImported);
+ }
+
+ if (item.attachments.length > 0) {
+ credential.Attachments = item.attachments.map(a => AvuxImportService.mapAvuxAttachmentToImported(a, attachmentMap));
+ }
+
+ return credential;
+ });
+ }
+
+ /**
+ * Fill the credential from the item's field values: system fields map to properties, custom fields become
+ * custom field values with their definition's metadata.
+ * @param credential - The credential to fill
+ * @param fieldValues - The item's field values
+ * @param fieldDefinitionsById - The custom field definitions by id
+ */
+ private static extractFieldValues(credential: ImportedCredential, fieldValues: AvuxFieldValue[], fieldDefinitionsById: Map<string, AvuxFieldDefinition>): void {
+ for (const fieldValue of fieldValues) {
+ if (!fieldValue.fieldKey) {
+ const definition = fieldValue.fieldDefinitionId ? fieldDefinitionsById.get(fieldValue.fieldDefinitionId) : undefined;
+ if (definition) {
+ credential.CustomFieldValues ??= [];
+ credential.CustomFieldValues.push({
+ DefinitionId: definition.id,
+ Label: definition.label,
+ Value: fieldValue.value,
+ FieldType: AvuxImportService.toFieldType(definition.fieldType),
+ IsMultiValue: definition.isMultiValue,
+ IsHidden: definition.isHidden,
+ EnableHistory: definition.enableHistory,
+ Weight: definition.weight,
+ ValueWeight: fieldValue.weight,
+ ApplicableToTypes: definition.applicableToTypes,
+ });
+ }
+ continue;
+ }
+
+ switch (fieldValue.fieldKey) {
+ case 'login.username':
+ credential.Username = fieldValue.value;
+ break;
+ case 'login.password':
+ credential.Password = fieldValue.value;
+ break;
+ case 'login.email':
+ credential.Email = fieldValue.value;
+ break;
+ case 'login.url':
+ credential.ServiceUrls ??= [];
+ if (fieldValue.value) {
+ credential.ServiceUrls.push(fieldValue.value);
+ }
+ break;
+ case 'notes.content':
+ credential.Notes = fieldValue.value;
+ break;
+ case 'alias.first_name':
+ credential.Alias ??= {};
+ credential.Alias.FirstName = fieldValue.value;
+ break;
+ case 'alias.last_name':
+ credential.Alias ??= {};
+ credential.Alias.LastName = fieldValue.value;
+ break;
+ case 'alias.gender':
+ credential.Alias ??= {};
+ credential.Alias.Gender = fieldValue.value;
+ break;
+ case 'alias.birthdate': {
+ credential.Alias ??= {};
+ const birthdate = parseDateTime(fieldValue.value);
+ if (birthdate) {
+ credential.Alias.BirthDate = birthdate;
+ }
+ break;
+ }
+ case 'card.number':
+ credential.Creditcard ??= {};
+ credential.Creditcard.Number = fieldValue.value;
+ break;
+ case 'card.cardholder_name':
+ credential.Creditcard ??= {};
+ credential.Creditcard.CardholderName = fieldValue.value;
+ break;
+ case 'card.expiry_month':
+ credential.Creditcard ??= {};
+ credential.Creditcard.ExpiryMonth = fieldValue.value;
+ break;
+ case 'card.expiry_year':
+ credential.Creditcard ??= {};
+ credential.Creditcard.ExpiryYear = fieldValue.value;
+ break;
+ case 'card.cvv':
+ credential.Creditcard ??= {};
+ credential.Creditcard.Cvv = fieldValue.value;
+ break;
+ case 'card.pin':
+ credential.Creditcard ??= {};
+ credential.Creditcard.Pin = fieldValue.value;
+ break;
+ }
+ }
+ }
+
+ /**
+ * Map a field type string to a known field type, Text for anything unknown.
+ * @param value - The field type text
+ * @returns The field type
+ */
+ private static toFieldType(value: string): FieldType {
+ return (Object.values(FieldTypes) as string[]).includes(value) ? value as FieldType : FieldTypes.Text;
+ }
+
+ /**
+ * Map a manifest passkey to an imported passkey.
+ * @param avuxPasskey - The manifest passkey
+ * @returns The imported passkey
+ */
+ private static mapAvuxPasskeyToImported(avuxPasskey: AvuxPasskey): ImportedPasskey {
+ return {
+ Id: avuxPasskey.id,
+ RpId: avuxPasskey.rpId,
+ UserHandle: avuxPasskey.userHandle ? base64ToBytes(avuxPasskey.userHandle) : null,
+ PublicKey: avuxPasskey.publicKey,
+ PrivateKey: avuxPasskey.privateKey,
+ PrfKey: avuxPasskey.prfKey ? base64ToBytes(avuxPasskey.prfKey) : null,
+ DisplayName: avuxPasskey.displayName,
+ };
+ }
+
+ /**
+ * Map a manifest attachment to an imported attachment, resolving its data from the archive.
+ * @param avuxAttachment - The manifest attachment
+ * @param attachmentMap - Attachment paths to file data
+ * @returns The imported attachment; empty when the file is missing
+ */
+ private static mapAvuxAttachmentToImported(avuxAttachment: AvuxAttachment, attachmentMap: Map<string, Uint8Array>): ImportedAttachment {
+ return {
+ Filename: avuxAttachment.filename,
+ Blob: attachmentMap.get(avuxAttachment.relativePath) ?? new Uint8Array(0),
+ };
+ }
+}
diff --git a/core/client/src/transfer/import/importers/aliasvault/AvuxManifestReader.ts b/core/client/src/transfer/import/importers/aliasvault/AvuxManifestReader.ts
new file mode 100644
index 000000000..fc7a46097
--- /dev/null
+++ b/core/client/src/transfer/import/importers/aliasvault/AvuxManifestReader.ts
@@ -0,0 +1,184 @@
+import { readBoolean, readNumber, readObjectArray, readString, requireObject, type JsonObject } from '../../readers/JsonReader';
+
+import type { AvuxAttachment, AvuxFieldDefinition, AvuxFieldValue, AvuxFolder, AvuxItem, AvuxItemTag, AvuxLogo, AvuxManifest, AvuxPasskey, AvuxTag, AvuxTotpCode } from '../../../export/AvuxManifest';
+
+/**
+ * Read an .avux manifest.json, matching property names case-insensitively.
+ * @param root - The parsed manifest JSON
+ * @returns The manifest
+ * @throws {JsonException} When a value has the wrong type.
+ */
+export function parseAvuxManifest(root: unknown): AvuxManifest {
+ const obj = requireObject(root, 'manifest.json');
+ return {
+ version: readString(obj, 'version') ?? '1.0.0',
+ exportedAt: readString(obj, 'exportedAt') ?? '',
+ exportedBy: readString(obj, 'exportedBy') ?? '',
+ items: readObjectArray(obj, 'items', parseAvuxItem) ?? [],
+ folders: readObjectArray(obj, 'folders', parseAvuxFolder) ?? [],
+ tags: readObjectArray(obj, 'tags', parseAvuxTag) ?? [],
+ itemTags: readObjectArray(obj, 'itemTags', parseAvuxItemTag) ?? [],
+ fieldDefinitions: readObjectArray(obj, 'fieldDefinitions', parseAvuxFieldDefinition) ?? [],
+ logos: readObjectArray(obj, 'logos', parseAvuxLogo) ?? [],
+ };
+}
+
+/**
+ * Read an item.
+ * @param obj - The item JSON
+ * @returns The item
+ */
+function parseAvuxItem(obj: JsonObject): AvuxItem {
+ return {
+ id: readString(obj, 'id') ?? '',
+ name: readString(obj, 'name'),
+ itemType: readString(obj, 'itemType') ?? '',
+ createdAt: readString(obj, 'createdAt') ?? '',
+ updatedAt: readString(obj, 'updatedAt') ?? '',
+ folderId: readString(obj, 'folderId'),
+ logoId: readString(obj, 'logoId'),
+ fieldValues: readObjectArray(obj, 'fieldValues', parseAvuxFieldValue) ?? [],
+ attachments: readObjectArray(obj, 'attachments', parseAvuxAttachment) ?? [],
+ totpCodes: readObjectArray(obj, 'totpCodes', parseAvuxTotpCode) ?? [],
+ passkeys: readObjectArray(obj, 'passkeys', parseAvuxPasskey) ?? [],
+ };
+}
+
+/**
+ * Read a field value.
+ * @param obj - The field value JSON
+ * @returns The field value
+ */
+function parseAvuxFieldValue(obj: JsonObject): AvuxFieldValue {
+ return {
+ id: readString(obj, 'id') ?? '',
+ fieldKey: readString(obj, 'fieldKey'),
+ fieldDefinitionId: readString(obj, 'fieldDefinitionId'),
+ value: readString(obj, 'value'),
+ weight: readNumber(obj, 'weight') ?? 0,
+ };
+}
+
+/**
+ * Read an attachment.
+ * @param obj - The attachment JSON
+ * @returns The attachment
+ */
+function parseAvuxAttachment(obj: JsonObject): AvuxAttachment {
+ return {
+ id: readString(obj, 'id') ?? '',
+ filename: readString(obj, 'filename') ?? '',
+ relativePath: readString(obj, 'relativePath') ?? '',
+ };
+}
+
+/**
+ * Read a TOTP code.
+ * @param obj - The TOTP code JSON
+ * @returns The TOTP code
+ */
+function parseAvuxTotpCode(obj: JsonObject): AvuxTotpCode {
+ return {
+ id: readString(obj, 'id') ?? '',
+ name: readString(obj, 'name') ?? '',
+ secretKey: readString(obj, 'secretKey') ?? '',
+ algorithm: readString(obj, 'algorithm') ?? 'SHA1',
+ digits: readNumber(obj, 'digits') ?? 6,
+ period: readNumber(obj, 'period') ?? 30,
+ };
+}
+
+/**
+ * Read a passkey.
+ * @param obj - The passkey JSON
+ * @returns The passkey
+ */
+function parseAvuxPasskey(obj: JsonObject): AvuxPasskey {
+ return {
+ id: readString(obj, 'id') ?? '',
+ rpId: readString(obj, 'rpId') ?? '',
+ userHandle: readString(obj, 'userHandle'),
+ publicKey: readString(obj, 'publicKey') ?? '',
+ privateKey: readString(obj, 'privateKey') ?? '',
+ prfKey: readString(obj, 'prfKey'),
+ displayName: readString(obj, 'displayName') ?? '',
+ };
+}
+
+/**
+ * Read a folder.
+ * @param obj - The folder JSON
+ * @returns The folder
+ */
+function parseAvuxFolder(obj: JsonObject): AvuxFolder {
+ return {
+ id: readString(obj, 'id') ?? '',
+ name: readString(obj, 'name') ?? '',
+ parentFolderId: readString(obj, 'parentFolderId'),
+ weight: readNumber(obj, 'weight') ?? 0,
+ createdAt: readString(obj, 'createdAt') ?? '',
+ updatedAt: readString(obj, 'updatedAt') ?? '',
+ };
+}
+
+/**
+ * Read a tag.
+ * @param obj - The tag JSON
+ * @returns The tag
+ */
+function parseAvuxTag(obj: JsonObject): AvuxTag {
+ return {
+ id: readString(obj, 'id') ?? '',
+ name: readString(obj, 'name') ?? '',
+ color: readString(obj, 'color'),
+ displayOrder: readNumber(obj, 'displayOrder') ?? 0,
+ createdAt: readString(obj, 'createdAt') ?? '',
+ updatedAt: readString(obj, 'updatedAt') ?? '',
+ };
+}
+
+/**
+ * Read an item-tag association.
+ * @param obj - The association JSON
+ * @returns The association
+ */
+function parseAvuxItemTag(obj: JsonObject): AvuxItemTag {
+ return {
+ id: readString(obj, 'id') ?? '',
+ itemId: readString(obj, 'itemId') ?? '',
+ tagId: readString(obj, 'tagId') ?? '',
+ };
+}
+
+/**
+ * Read a custom field definition.
+ * @param obj - The definition JSON
+ * @returns The definition
+ */
+function parseAvuxFieldDefinition(obj: JsonObject): AvuxFieldDefinition {
+ return {
+ id: readString(obj, 'id') ?? '',
+ fieldType: readString(obj, 'fieldType') ?? '',
+ label: readString(obj, 'label') ?? '',
+ isMultiValue: readBoolean(obj, 'isMultiValue') ?? false,
+ isHidden: readBoolean(obj, 'isHidden') ?? false,
+ enableHistory: readBoolean(obj, 'enableHistory') ?? false,
+ weight: readNumber(obj, 'weight') ?? 0,
+ applicableToTypes: readString(obj, 'applicableToTypes'),
+ };
+}
+
+/**
+ * Read a logo.
+ * @param obj - The logo JSON
+ * @returns The logo
+ */
+function parseAvuxLogo(obj: JsonObject): AvuxLogo {
+ return {
+ id: readString(obj, 'id') ?? '',
+ source: readString(obj, 'source') ?? '',
+ mimeType: readString(obj, 'mimeType'),
+ fetchedAt: readString(obj, 'fetchedAt'),
+ relativePath: readString(obj, 'relativePath') ?? '',
+ };
+}
diff --git a/core/client/src/transfer/import/importers/aliasvault/ItemCsvImportService.ts b/core/client/src/transfer/import/importers/aliasvault/ItemCsvImportService.ts
new file mode 100644
index 000000000..dc2927abe
--- /dev/null
+++ b/core/client/src/transfer/import/importers/aliasvault/ItemCsvImportService.ts
@@ -0,0 +1,103 @@
+import { ItemTypes } from '@aliasvault/models/vault';
+
+import { nullIfBlank } from '../../../shared/StringUtils';
+import { dateTime, readCsvRecords, text, type CsvColumn, type CsvRecord } from '../../readers/CsvRecordMapper';
+import { parseUrls } from '../shared/CredentialHelpers';
+
+import type { ItemCsvColumn } from '../../../export/ItemCsvExportService';
+import type { ImportedCredential } from '../../models/ImportedCredential';
+
+/** How each column of the AliasVault CSV export is read. */
+const COLUMNS = {
+ ServiceName: text,
+ FolderPath: text,
+ ServiceUrl: text,
+ Username: text,
+ CurrentPassword: text,
+ AliasEmail: text,
+ TwoFactorSecret: text,
+ AliasGender: text,
+ AliasFirstName: text,
+ AliasLastName: text,
+ AliasBirthDate: dateTime,
+ CardholderName: text,
+ CardNumber: text,
+ CardExpiryMonth: text,
+ CardExpiryYear: text,
+ CardCvv: text,
+ CardPin: text,
+ Notes: text,
+ CreatedAt: dateTime,
+ UpdatedAt: dateTime,
+} satisfies Record<ItemCsvColumn, CsvColumn<unknown>>;
+
+/**
+ * A row of the AliasVault CSV export.
+ */
+type ItemCsvRecord = CsvRecord<typeof COLUMNS>;
+
+/**
+ * Imports items from the AliasVault CSV format.
+ */
+export class ItemCsvImportService {
+ /**
+ * Import items from an AliasVault CSV file.
+ * @param fileContent - The CSV file content
+ * @returns The imported credentials
+ * @throws {Error} When the file holds no records.
+ */
+ public static importItemsFromCsv(fileContent: string): ImportedCredential[] {
+ // Columns the file lacks are skipped (older exports have no card columns).
+ const records = readCsvRecords(fileContent, COLUMNS);
+
+ if (records.length === 0) {
+ throw new Error('No records found in the CSV file.');
+ }
+
+ return records.map((record): ImportedCredential => {
+ const credential: ImportedCredential = {
+ ServiceName: record.ServiceName,
+ ServiceUrls: parseUrls(record.ServiceUrl),
+ Username: record.Username,
+ Password: record.CurrentPassword,
+ Email: record.AliasEmail,
+ Notes: record.Notes,
+ Alias: {
+ Gender: record.AliasGender,
+ FirstName: record.AliasFirstName,
+ LastName: record.AliasLastName,
+ BirthDate: record.AliasBirthDate,
+ CreatedAt: record.CreatedAt,
+ UpdatedAt: record.UpdatedAt,
+ },
+ TwoFactorSecret: record.TwoFactorSecret,
+ CreatedAt: record.CreatedAt,
+ UpdatedAt: record.UpdatedAt,
+ FolderPath: nullIfBlank(record.FolderPath),
+ };
+
+ if (ItemCsvImportService.hasCardData(record)) {
+ credential.ItemType = ItemTypes.CreditCard;
+ credential.Creditcard = {
+ CardholderName: record.CardholderName,
+ Number: record.CardNumber,
+ ExpiryMonth: record.CardExpiryMonth,
+ ExpiryYear: record.CardExpiryYear,
+ Cvv: record.CardCvv,
+ Pin: record.CardPin,
+ };
+ }
+
+ return credential;
+ });
+ }
+
+ /**
+ * Whether a record has any credit card column filled.
+ * @param record - The record
+ * @returns True when a card field has a value
+ */
+ private static hasCardData(record: ItemCsvRecord): boolean {
+ return [record.CardholderName, record.CardNumber, record.CardExpiryMonth, record.CardExpiryYear, record.CardCvv, record.CardPin].some(value => value.trim().length > 0);
+ }
+}