Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add AliasVault format export functions ported from .NET (#2413)
Leendert de Borstb2b2016141eb
diff --git a/core/client/src/transfer/export/AvexConstants.ts b/core/client/src/transfer/export/AvexConstants.tsnew file mode 100644index 000000000..10e3c2f56--- /dev/null+++ b/core/client/src/transfer/export/AvexConstants.ts@@ -0,0 +1,23 @@+/**+ * 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.tsnew file mode 100644index 000000000..4c19659f4--- /dev/null+++ b/core/client/src/transfer/export/AvexExportService.ts@@ -0,0 +1,61 @@+import { DEFAULT_ENCRYPTION } from '../../auth/SrpAuthService';+import { EncryptionUtility } from '../../crypto/EncryptionUtility';+import { AppInfo } from '../../platform/AppInfo';+import { argon2DeriveKey } from '../../rust/RustCore';+import { base64ToBytes, bytesToBase64 } from '../../utilities/Base64';+import { formatIsoDateTime } from '../shared/DateTimeUtils';++import { AvexConstants } from './AvexConstants';++import type { AvexHeader } from './AvexHeader';++/** The Argon2id parameters a new export is encrypted with: the vault key derivation defaults. */+const ARGON2_KDF_PARAMS: Record<string, number> = JSON.parse(DEFAULT_ENCRYPTION.settings);++/**+ * 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.+ */+export class AvexExportService {+ /**+ * Encrypt .avux bytes to an .avex file.+ * @param avuxBytes - The unencrypted .avux bytes+ * @param exportPassword - The password to encrypt with+ * @param username - The username creating the export+ * @returns The .avex file bytes+ */+ public static async encryptToAvex(avuxBytes: Uint8Array, exportPassword: string, username: string): Promise<Uint8Array> {+ // 1. A random salt and a key derived from it with Argon2id, as for the vault encryption.+ const salt = crypto.getRandomValues(new Uint8Array(32));+ const saltBase64 = bytesToBase64(salt);+ const key = await argon2DeriveKey(exportPassword, saltBase64, DEFAULT_ENCRYPTION.settings);++ // 2. AES-256-GCM over the .avux bytes.+ const encryptedPayload = base64ToBytes(await EncryptionUtility.symmetricEncryptBytes(avuxBytes, bytesToBase64(key)));++ // 3. The header.+ const header: AvexHeader = {+ format: AvexConstants.FormatIdentifier,+ version: AvexConstants.FormatVersion,+ kdf: { type: DEFAULT_ENCRYPTION.type, salt: saltBase64, params: { ...ARGON2_KDF_PARAMS } },+ encryption: { algorithm: 'AES-256-GCM', encryptedDataOffset: 0 },+ metadata: { exportedAt: formatIsoDateTime(new Date()), exportedBy: username, 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;+ }+}diff --git a/core/client/src/transfer/export/AvexHeader.ts b/core/client/src/transfer/export/AvexHeader.tsnew file mode 100644index 000000000..2a4a3846f--- /dev/null+++ b/core/client/src/transfer/export/AvexHeader.ts@@ -0,0 +1,46 @@+/*+ * 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;+ exportedBy: 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/AvuxExportService.ts b/core/client/src/transfer/export/AvuxExportService.tsnew file mode 100644index 000000000..5a9ff180f--- /dev/null+++ b/core/client/src/transfer/export/AvuxExportService.ts@@ -0,0 +1,285 @@+import { bytesToBase64 } from '../../utilities/Base64';+import { formatIsoDateTime } from '../shared/DateTimeUtils';+import { createZipArchive, textToZipBytes } from '../shared/ZipArchive';++import type { AvuxAttachment, AvuxFieldDefinition, AvuxFieldValue, AvuxFolder, AvuxItem, AvuxItemTag, AvuxLogo, AvuxManifest, AvuxPasskey, AvuxTag, AvuxTotpCode } from './AvuxManifest';+import type { AttachmentEntity, FieldDefinitionEntity, FieldValueEntity, FolderEntity, ItemEntity, ItemTagEntity, LogoEntity, PasskeyEntity, TagEntity, TotpCodeEntity } from '../shared/VaultEntities';++/** The .avux manifest format version this service writes. */+export const AVUX_FORMAT_VERSION = '1.0.0';++/**+ * Exports vault data to the .avux (AliasVault Unencrypted eXport) format: a ZIP archive with a manifest.json, all+ * attachments and all logos.+ */+export class AvuxExportService {+ /**+ * Export vault data to .avux.+ * @param items - The items to export+ * @param folders - The folders to export+ * @param tags - The tags to export+ * @param itemTags - The item-tag associations to export+ * @param fieldDefinitions - The custom field definitions to export+ * @param logos - The logos to export+ * @param username - The username creating the export+ * @returns The .avux ZIP file bytes+ */+ public static exportToAvux(items: ItemEntity[], folders: FolderEntity[], tags: TagEntity[], itemTags: ItemTagEntity[], fieldDefinitions: FieldDefinitionEntity[], logos: LogoEntity[], username: string): Uint8Array {+ const manifest = AvuxExportService.createManifest(items, folders, tags, itemTags, fieldDefinitions, logos, username);+ const attachmentMap = AvuxExportService.extractAttachments(items);+ const logoMap = AvuxExportService.extractLogos(logos);++ return AvuxExportService.packageAsZip(manifest, attachmentMap, logoMap);+ }++ /**+ * Build the manifest from the vault entities; deleted rows are left out.+ * @param items - The items+ * @param folders - The folders+ * @param tags - The tags+ * @param itemTags - The item-tag associations+ * @param fieldDefinitions - The custom field definitions+ * @param logos - The logos+ * @param username - The username creating the export+ * @returns The manifest+ */+ private static createManifest(items: ItemEntity[], folders: FolderEntity[], tags: TagEntity[], itemTags: ItemTagEntity[], fieldDefinitions: FieldDefinitionEntity[], logos: LogoEntity[], username: string): AvuxManifest {+ return {+ version: AVUX_FORMAT_VERSION,+ exportedAt: formatIsoDateTime(new Date()),+ exportedBy: username,+ items: items.filter(i => !i.IsDeleted).map(AvuxExportService.mapItemToAvux),+ folders: folders.filter(f => !f.IsDeleted).map(AvuxExportService.mapFolderToAvux),+ tags: tags.filter(t => !t.IsDeleted).map(AvuxExportService.mapTagToAvux),+ itemTags: itemTags.filter(it => !it.IsDeleted).map(AvuxExportService.mapItemTagToAvux),+ fieldDefinitions: fieldDefinitions.filter(fd => !fd.IsDeleted).map(AvuxExportService.mapFieldDefinitionToAvux),+ logos: logos.filter(l => !l.IsDeleted).map(AvuxExportService.mapLogoToAvux),+ };+ }++ /**+ * Map an item.+ * @param item - The item+ * @returns The manifest item+ */+ private static mapItemToAvux(item: ItemEntity): AvuxItem {+ return {+ id: item.Id,+ name: item.Name,+ itemType: item.ItemType,+ createdAt: formatIsoDateTime(item.CreatedAt),+ updatedAt: formatIsoDateTime(item.UpdatedAt),+ folderId: item.FolderId,+ logoId: item.LogoId,+ fieldValues: item.FieldValues.filter(fv => !fv.IsDeleted).map(AvuxExportService.mapFieldValueToAvux),+ attachments: item.Attachments.filter(a => !a.IsDeleted).map(AvuxExportService.mapAttachmentToAvux),+ totpCodes: item.TotpCodes.filter(tc => !tc.IsDeleted).map(AvuxExportService.mapTotpCodeToAvux),+ passkeys: item.Passkeys.filter(p => !p.IsDeleted).map(AvuxExportService.mapPasskeyToAvux),+ };+ }++ /**+ * Map a field value.+ * @param fieldValue - The field value+ * @returns The manifest field value+ */+ private static mapFieldValueToAvux(fieldValue: FieldValueEntity): AvuxFieldValue {+ return {+ id: fieldValue.Id,+ fieldKey: fieldValue.FieldKey,+ fieldDefinitionId: fieldValue.FieldDefinitionId,+ value: fieldValue.Value,+ weight: fieldValue.Weight,+ };+ }++ /**+ * Map an attachment.+ * @param attachment - The attachment+ * @returns The manifest attachment+ */+ private static mapAttachmentToAvux(attachment: AttachmentEntity): AvuxAttachment {+ return {+ id: attachment.Id,+ filename: attachment.Filename,+ relativePath: AvuxExportService.attachmentPath(attachment),+ };+ }++ /**+ * Map a TOTP code.+ * @param totpCode - The TOTP code+ * @returns The manifest TOTP code+ */+ private static mapTotpCodeToAvux(totpCode: TotpCodeEntity): AvuxTotpCode {+ return {+ id: totpCode.Id,+ name: totpCode.Name,+ secretKey: totpCode.SecretKey,+ algorithm: totpCode.Algorithm,+ digits: totpCode.Digits,+ period: totpCode.Period,+ };+ }++ /**+ * Map a passkey.+ * @param passkey - The passkey+ * @returns The manifest passkey+ */+ private static mapPasskeyToAvux(passkey: PasskeyEntity): AvuxPasskey {+ return {+ id: passkey.Id,+ rpId: passkey.RpId,+ userHandle: passkey.UserHandle ? bytesToBase64(passkey.UserHandle) : null,+ publicKey: passkey.PublicKey,+ privateKey: passkey.PrivateKey,+ prfKey: passkey.PrfKey ? bytesToBase64(passkey.PrfKey) : null,+ displayName: passkey.DisplayName,+ };+ }++ /**+ * Map a folder.+ * @param folder - The folder+ * @returns The manifest folder+ */+ private static mapFolderToAvux(folder: FolderEntity): AvuxFolder {+ return {+ id: folder.Id,+ name: folder.Name,+ parentFolderId: folder.ParentFolderId,+ weight: folder.Weight,+ createdAt: formatIsoDateTime(folder.CreatedAt),+ updatedAt: formatIsoDateTime(folder.UpdatedAt),+ };+ }++ /**+ * Map a tag.+ * @param tag - The tag+ * @returns The manifest tag+ */+ private static mapTagToAvux(tag: TagEntity): AvuxTag {+ return {+ id: tag.Id,+ name: tag.Name,+ color: tag.Color,+ displayOrder: tag.DisplayOrder,+ createdAt: formatIsoDateTime(tag.CreatedAt),+ updatedAt: formatIsoDateTime(tag.UpdatedAt),+ };+ }++ /**+ * Map an item-tag association.+ * @param itemTag - The association+ * @returns The manifest association+ */+ private static mapItemTagToAvux(itemTag: ItemTagEntity): AvuxItemTag {+ return {+ id: crypto.randomUUID(),+ itemId: itemTag.ItemId,+ tagId: itemTag.TagId,+ };+ }++ /**+ * Map a custom field definition.+ * @param fieldDefinition - The definition+ * @returns The manifest definition+ */+ private static mapFieldDefinitionToAvux(fieldDefinition: FieldDefinitionEntity): AvuxFieldDefinition {+ return {+ id: fieldDefinition.Id,+ fieldType: fieldDefinition.FieldType,+ label: fieldDefinition.Label,+ isMultiValue: fieldDefinition.IsMultiValue,+ isHidden: fieldDefinition.IsHidden,+ enableHistory: fieldDefinition.EnableHistory,+ weight: fieldDefinition.Weight,+ applicableToTypes: fieldDefinition.ApplicableToTypes,+ };+ }++ /**+ * Map a logo.+ * @param logo - The logo+ * @returns The manifest logo+ */+ private static mapLogoToAvux(logo: LogoEntity): AvuxLogo {+ return {+ id: logo.Id,+ source: logo.Source,+ mimeType: logo.MimeType,+ fetchedAt: logo.FetchedAt ? formatIsoDateTime(logo.FetchedAt) : null,+ relativePath: AvuxExportService.logoPath(logo),+ };+ }++ /**+ * The archive path of an attachment.+ * @param attachment - The attachment+ * @returns The path+ */+ private static attachmentPath(attachment: AttachmentEntity): string {+ return `attachments/${attachment.ItemId}_${attachment.Id}_${attachment.Filename}`;+ }++ /**+ * The archive path of a logo.+ * @param logo - The logo+ * @returns The path+ */+ private static logoPath(logo: LogoEntity): string {+ return `logos/${logo.Source}_${logo.Id}.png`;+ }++ /**+ * Collect the attachment blobs of the live items, keyed by archive path.+ * @param items - The items+ * @returns Archive paths to blob data+ */+ private static extractAttachments(items: ItemEntity[]): Map<string, Uint8Array> {+ const attachmentMap = new Map<string, Uint8Array>();+ for (const item of items.filter(i => !i.IsDeleted)) {+ for (const attachment of item.Attachments.filter(a => !a.IsDeleted && a.Blob)) {+ attachmentMap.set(`attachments/${item.Id}_${attachment.Id}_${attachment.Filename}`, attachment.Blob as Uint8Array);+ }+ }+ return attachmentMap;+ }++ /**+ * Collect the logo images, keyed by archive path.+ * @param logos - The logos+ * @returns Archive paths to image data+ */+ private static extractLogos(logos: LogoEntity[]): Map<string, Uint8Array> {+ const logoMap = new Map<string, Uint8Array>();+ for (const logo of logos.filter(l => !l.IsDeleted && l.FileData !== null)) {+ logoMap.set(AvuxExportService.logoPath(logo), logo.FileData!);+ }+ return logoMap;+ }++ /**+ * Package the manifest, attachments and logos into a ZIP archive.+ * @param manifest - The manifest+ * @param attachments - Archive paths to attachment data+ * @param logos - Archive paths to logo data+ * @returns The ZIP bytes+ */+ private static packageAsZip(manifest: AvuxManifest, attachments: Map<string, Uint8Array>, logos: Map<string, Uint8Array>): Uint8Array {+ const files: Record<string, Uint8Array> = {+ 'manifest.json': textToZipBytes(JSON.stringify(manifest, null, 2)),+ };+ for (const [path, data] of attachments) {+ files[path] = data;+ }+ for (const [path, data] of logos) {+ files[path] = data;+ }+ return createZipArchive(files);+ }+}diff --git a/core/client/src/transfer/export/AvuxManifest.ts b/core/client/src/transfer/export/AvuxManifest.tsnew file mode 100644index 000000000..ff1a9b9cd--- /dev/null+++ b/core/client/src/transfer/export/AvuxManifest.ts@@ -0,0 +1,149 @@+/*+ * The manifest.json of an .avux (AliasVault Unencrypted eXport) archive. Property names are the JSON wire names+ * (camelCase); dates are ISO 8601 strings. Readers match property names case-insensitively.+ */++/**+ * A field value in an item.+ */+export type AvuxFieldValue = {+ id: string;+ /** The system field key (e.g. "login.username"), null for custom fields. */+ fieldKey: string | null;+ /** The custom field definition id, null for system fields. */+ fieldDefinitionId: string | null;+ value: string | null;+ weight: number;+};++/**+ * An attachment in an item.+ */+export type AvuxAttachment = {+ id: string;+ filename: string;+ /** The relative path in the .avux archive. */+ relativePath: string;+};++/**+ * A TOTP code in an item.+ */+export type AvuxTotpCode = {+ id: string;+ name: string;+ secretKey: string;+ /** HMAC algorithm: SHA1, SHA256 or SHA512. */+ algorithm: string;+ digits: number;+ period: number;+};++/**+ * A passkey in an item.+ */+export type AvuxPasskey = {+ /** The passkey id; the WebAuthn credential id is derived from it at runtime. */+ id: string;+ rpId: string;+ /** The user handle (base64-encoded). */+ userHandle: string | null;+ publicKey: string;+ privateKey: string;+ /** The PRF key (base64-encoded). */+ prfKey: string | null;+ displayName: string;+};++/**+ * An item in the .avux export.+ */+export type AvuxItem = {+ id: string;+ name: string | null;+ /** Login, Alias, CreditCard or Note. */+ itemType: string;+ createdAt: string;+ updatedAt: string;+ folderId: string | null;+ logoId: string | null;+ fieldValues: AvuxFieldValue[];+ attachments: AvuxAttachment[];+ totpCodes: AvuxTotpCode[];+ passkeys: AvuxPasskey[];+};++/**+ * A folder.+ */+export type AvuxFolder = {+ id: string;+ name: string;+ parentFolderId: string | null;+ weight: number;+ createdAt: string;+ updatedAt: string;+};++/**+ * A tag.+ */+export type AvuxTag = {+ id: string;+ name: string;+ color: string | null;+ displayOrder: number;+ createdAt: string;+ updatedAt: string;+};++/**+ * An item-tag association.+ */+export type AvuxItemTag = {+ id: string;+ itemId: string;+ tagId: string;+};++/**+ * A custom field definition.+ */+export type AvuxFieldDefinition = {+ id: string;+ fieldType: string;+ label: string;+ isMultiValue: boolean;+ isHidden: boolean;+ enableHistory: boolean;+ weight: number;+ /** The item types this field applies to (JSON array), null for all. */+ applicableToTypes: string | null;+};++/**+ * A logo in the .avux export, deduplicated by source domain.+ */+export type AvuxLogo = {+ id: string;+ source: string;+ mimeType: string | null;+ fetchedAt: string | null;+ /** The relative path to the logo file in the .avux archive. */+ relativePath: string;+};++/**+ * The complete manifest of an .avux export.+ */+export type AvuxManifest = {+ version: string;+ exportedAt: string;+ exportedBy: string;+ items: AvuxItem[];+ folders: AvuxFolder[];+ tags: AvuxTag[];+ itemTags: AvuxItemTag[];+ fieldDefinitions: AvuxFieldDefinition[];+ logos: AvuxLogo[];+};diff --git a/core/client/src/importexport/csv/CsvWriter.ts b/core/client/src/transfer/export/CsvWriter.tssimilarity index 100%rename from core/client/src/importexport/csv/CsvWriter.tsrename to core/client/src/transfer/export/CsvWriter.tsdiff --git a/core/client/src/transfer/export/ItemCsvExportService.ts b/core/client/src/transfer/export/ItemCsvExportService.tsnew file mode 100644index 000000000..b9587d3ed--- /dev/null+++ b/core/client/src/transfer/export/ItemCsvExportService.ts@@ -0,0 +1,144 @@+import { FieldKey, normalizeTotpAlgorithm, normalizeTotpDigits, normalizeTotpPeriod, TOTP_DEFAULT_ALGORITHM, TOTP_DEFAULT_DIGITS, TOTP_DEFAULT_PERIOD } from '@aliasvault/models/vault';++import { formatInvariantDateTime, parseDateExact } from '../shared/DateTimeUtils';+import { buildFolderPath } from '../shared/FolderPaths';++import { writeCsv } from './CsvWriter';++import type { FolderEntity, ItemEntity, TotpCodeEntity } from '../shared/VaultEntities';++/** The columns of the AliasVault CSV export. */+export const ITEM_CSV_COLUMNS = [+ 'ServiceName',+ 'FolderPath',+ 'ServiceUrl',+ 'Username',+ 'CurrentPassword',+ 'AliasEmail',+ 'TwoFactorSecret',+ 'AliasGender',+ 'AliasFirstName',+ 'AliasLastName',+ 'AliasBirthDate',+ 'CardholderName',+ 'CardNumber',+ 'CardExpiryMonth',+ 'CardExpiryYear',+ 'CardCvv',+ 'CardPin',+ 'Notes',+ 'CreatedAt',+ 'UpdatedAt',+] as const;++/** One column of the AliasVault CSV export. */+export type ItemCsvColumn = (typeof ITEM_CSV_COLUMNS)[number];++/**+ * Exports items to the AliasVault CSV format.+ */+export class ItemCsvExportService {+ /**+ * Export items to CSV.+ * @param items - The items to export+ * @param folders - The vault's folders, to resolve each item's folder path+ * @returns The CSV file as UTF-8 bytes+ */+ public static exportItemsToCsv(items: ItemEntity[], folders: FolderEntity[] = []): Uint8Array {+ const foldersById = new Map(folders.map(folder => [folder.Id, folder]));++ const rows = items.map((item): string[] => {+ const record: Record<ItemCsvColumn, string | Date | null> = {+ ServiceName: item.Name ?? '',+ FolderPath: buildFolderPath(item.FolderId, foldersById),+ ServiceUrl: ItemCsvExportService.getJoinedFieldValues(item, FieldKey.LoginUrl),+ Username: ItemCsvExportService.getFieldValue(item, FieldKey.LoginUsername),+ CurrentPassword: ItemCsvExportService.getFieldValue(item, FieldKey.LoginPassword),+ AliasEmail: ItemCsvExportService.getFieldValue(item, FieldKey.LoginEmail),+ TwoFactorSecret: ItemCsvExportService.formatTwoFactorSecret(item.TotpCodes.find(t => !t.IsDeleted) ?? null),+ AliasGender: ItemCsvExportService.getFieldValue(item, FieldKey.AliasGender),+ AliasFirstName: ItemCsvExportService.getFieldValue(item, FieldKey.AliasFirstName),+ AliasLastName: ItemCsvExportService.getFieldValue(item, FieldKey.AliasLastName),+ AliasBirthDate: ItemCsvExportService.parseBirthDate(ItemCsvExportService.getFieldValue(item, FieldKey.AliasBirthdate)),+ Notes: ItemCsvExportService.getFieldValue(item, FieldKey.NotesContent),+ CardholderName: ItemCsvExportService.getFieldValue(item, FieldKey.CardCardholderName),+ CardNumber: ItemCsvExportService.getFieldValue(item, FieldKey.CardNumber),+ CardExpiryMonth: ItemCsvExportService.getFieldValue(item, FieldKey.CardExpiryMonth),+ CardExpiryYear: ItemCsvExportService.getFieldValue(item, FieldKey.CardExpiryYear),+ CardCvv: ItemCsvExportService.getFieldValue(item, FieldKey.CardCvv),+ CardPin: ItemCsvExportService.getFieldValue(item, FieldKey.CardPin),+ CreatedAt: item.CreatedAt,+ UpdatedAt: item.UpdatedAt,+ };++ return ITEM_CSV_COLUMNS.map(header => {+ const value = record[header];+ if (value instanceof Date) {+ return formatInvariantDateTime(value);+ }+ return value ?? '';+ });+ });++ return new TextEncoder().encode(writeCsv([...ITEM_CSV_COLUMNS], rows));+ }++ /**+ * Format an item's TOTP code for the single CSV secret column.+ * @param totpCode - The item's first live TOTP code, if any+ * @returns The secret or an otpauth:// URI+ */+ private static formatTwoFactorSecret(totpCode: TotpCodeEntity | null): string {+ if (!totpCode) {+ return '';+ }++ const algorithm = normalizeTotpAlgorithm(totpCode.Algorithm);+ const digits = normalizeTotpDigits(totpCode.Digits);+ const period = normalizeTotpPeriod(totpCode.Period);++ if (algorithm === TOTP_DEFAULT_ALGORITHM && digits === TOTP_DEFAULT_DIGITS && period === TOTP_DEFAULT_PERIOD) {+ return totpCode.SecretKey;+ }++ const label = encodeURIComponent(totpCode.Name.trim().length === 0 ? 'AliasVault' : totpCode.Name);+ return `otpauth://totp/${label}?secret=${totpCode.SecretKey}&algorithm=${algorithm}&digits=${digits}&period=${period}`;+ }++ /**+ * A single field value of an item.+ * @param item - The item+ * @param fieldKey - The field key+ * @returns The value, or the empty string when absent+ */+ private static getFieldValue(item: ItemEntity, fieldKey: string): string {+ return item.FieldValues.find(fv => fv.FieldKey === fieldKey && !fv.IsDeleted)?.Value ?? '';+ }++ /**+ * All values of a multi-value field as one comma separated string, ordered by weight.+ * @param item - The item+ * @param fieldKey - The field key+ * @returns The joined values, or the empty string when there are none+ */+ private static getJoinedFieldValues(item: ItemEntity, fieldKey: string): string {+ return item.FieldValues+ .filter(fv => fv.FieldKey === fieldKey && !fv.IsDeleted && !!fv.Value && fv.Value.trim().length > 0)+ .sort((a, b) => a.Weight - b.Weight)+ .map(fv => fv.Value!.trim())+ .join(',');+ }++ /**+ * Parse a "yyyy-MM-dd" birth date.+ * @param birthDate - The birth date text+ * @returns The date, or null when empty or invalid+ */+ private static parseBirthDate(birthDate: string): Date | null {+ if (birthDate.length === 0) {+ return null;+ }+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(birthDate.trim());+ return match ? parseDateExact(`${match[2]}/${match[3]}/${match[1]}`, 'MM/dd/yyyy') : null;+ }+}