Skip to content

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

Update all default export paths so they limit to personal manifest entries only (#2413)

Leendert de Borst687b0e63af69
diff --git a/apps/web/src/pages/settings/importexport/ImportExport.tsx b/apps/web/src/pages/settings/importexport/ImportExport.tsx
index a3672fa32..9e59346eb 100644
--- a/apps/web/src/pages/settings/importexport/ImportExport.tsx
+++ b/apps/web/src/pages/settings/importexport/ImportExport.tsx
@@ -1,4 +1,3 @@
-import { AliasVaultCsvExportService } from '@aliasvault/client/transfer/export/AliasVaultCsvExportService';
import { AvexExportService } from '@aliasvault/client/transfer/export/AvexExportService';
import { AvuxExportService } from '@aliasvault/client/transfer/export/AvuxExportService';
import { downloadBytes } from '@aliasvault/client/utilities/FileDownload';
@@ -96,8 +95,7 @@ const ImportExport: React.FC = () => {
if (!sqliteClient) {
throw new Error('Vault is not available');
}
- const items = [...sqliteClient.items.getAll(), ...sqliteClient.items.getArchived()];
- downloadBytes(getExportFileName('csv'), AliasVaultCsvExportService.exportItemsToCsv(items, item => sqliteClient.items.getTotpCodesForItem(item)), 'text/csv');
+ downloadBytes(getExportFileName('csv'), sqliteClient.importExport.exportToCsv(), 'text/csv');
notifications.addSuccessMessage(t(`${tk}.ExportSuccessMessage`), true);
} catch (error) {
console.error('[Export] Error downloading file:', error);
diff --git a/core/client/src/database/__tests__/ExportScoping.test.ts b/core/client/src/database/__tests__/ExportScoping.test.ts
new file mode 100644
index 000000000..170ccdf04
--- /dev/null
+++ b/core/client/src/database/__tests__/ExportScoping.test.ts
@@ -0,0 +1,153 @@
+import { VaultSqlGenerator } from '@aliasvault/vault';
+import { describe, expect, it } from 'vitest';
+
+import { getPlatform } from '../../platform/ClientPlatform';
+import { runSync } from '../DbOp';
+import { ImportExportRepository } from '../repositories/ImportExportRepository';
+import { LogoRepository } from '../repositories/LogoRepository';
+
+import type { ISqliteDatabase, SqliteValue } from '../../platform/SqliteEngine';
+import type { ISyncDatabaseClient, SqliteBindValue } from '../BaseRepository';
+
+const PERSONAL = '11111111-1111-4111-8111-111111111111';
+const SHARED = '22222222-2222-4222-8222-222222222222';
+
+/**
+ * A database client over an in-memory vault on the real schema.
+ */
+class TestDatabaseClient implements ISyncDatabaseClient {
+ /**
+ * Constructor for the TestDatabaseClient class.
+ * @param db - The opened database
+ * @param personalManifestId - The personal manifest this client reports
+ */
+ public constructor(private readonly db: ISqliteDatabase, private readonly personalManifestId: string | null) {}
+
+ /**
+ * Get the database.
+ * @returns The database
+ */
+ public getDb(): ISqliteDatabase {
+ return this.db;
+ }
+
+ /**
+ * Run a SELECT.
+ * @param query - The statement
+ * @param params - The bound parameters
+ * @returns The rows
+ */
+ public executeQuery<T>(query: string, params: SqliteBindValue[] = []): T[] {
+ return this.db.query<T>(query, params as SqliteValue[]);
+ }
+
+ /**
+ * Run a write.
+ * @param query - The statement
+ * @param params - The bound parameters
+ * @returns The number of rows changed
+ */
+ public executeUpdate(query: string, params: SqliteBindValue[] = []): number {
+ return this.db.run(query, params as SqliteValue[]);
+ }
+
+ /**
+ * Begin a transaction.
+ */
+ public beginTransaction(): void {}
+
+ /**
+ * Commit the transaction.
+ */
+ public async commitTransaction(): Promise<void> {}
+
+ /**
+ * Roll the transaction back.
+ */
+ public rollbackTransaction(): void {}
+
+ /**
+ * Whether a transaction is open.
+ * @returns Always false
+ */
+ public isInTransaction(): boolean {
+ return false;
+ }
+
+ /**
+ * Get the personal manifest.
+ * @returns The personal manifest id
+ */
+ public getPersonalManifestId(): string | null {
+ return this.personalManifestId;
+ }
+}
+
+/**
+ * Seed one manifest with an item and every row kind an export reads, all sharing the same ids across manifests.
+ * @param db - The database
+ * @param manifestId - The manifest to seed
+ * @param label - Tells the manifests apart in the exported values
+ */
+function seedManifest(db: ISqliteDatabase, manifestId: string, label: string): void {
+ const t = '2026-01-01 00:00:00.000';
+ db.run('INSERT INTO Folders (ManifestId, Id, Name, ParentFolderId, Weight, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, NULL, 0, ?, ?, 0)', [manifestId, 'FOLDER', `${label} folder`, t, t]);
+ db.run('INSERT INTO Logos (ManifestId, Id, Kind, Source, FileData, MimeType, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, ?, NULL, NULL, ?, ?, 0)', [manifestId, 'LOGO', 'favicon', `${label}.example`, t, t]);
+ db.run('INSERT INTO Items (ManifestId, Id, Name, ItemType, FolderId, LogoId, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)', [manifestId, 'ITEM', `${label} item`, 'Login', 'FOLDER', 'LOGO', t, t]);
+ db.run('INSERT INTO FieldDefinitions (ManifestId, Id, FieldType, Label, IsMultiValue, IsHidden, EnableHistory, Weight, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, ?, 0, 0, 0, 0, ?, ?, 0)', [manifestId, 'DEF', 'Text', `${label} field`, t, t]);
+ db.run('INSERT INTO FieldValues (ManifestId, Id, ItemId, FieldKey, Value, Weight, ValueIndex, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, ?, ?, 0, 0, ?, ?, 0)', [manifestId, 'VALUE', 'ITEM', 'login.username', `${label} user`, t, t]);
+ db.run('INSERT INTO TotpCodes (ManifestId, Id, ItemId, Name, SecretKey, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, ?, ?, ?, ?, 0)', [manifestId, 'TOTP', 'ITEM', `${label} totp`, 'SECRET', t, t]);
+ db.run('INSERT INTO Tags (ManifestId, Id, Name, DisplayOrder, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, 0, ?, ?, 0)', [manifestId, 'TAG', `${label} tag`, t, t]);
+ db.run('INSERT INTO ItemTags (ManifestId, ItemId, TagId, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, ?, ?, 0)', [manifestId, 'ITEM', 'TAG', t, t]);
+}
+
+/**
+ * Build a vault holding a personal and a shared manifest.
+ * @param personalManifestId - The personal manifest the client reports
+ * @returns The repository to export with
+ */
+async function vaultWithSharedManifest(personalManifestId: string | null): Promise<{ repository: ImportExportRepository; client: TestDatabaseClient }> {
+ const db = await getPlatform().sqlite.open();
+ db.exec('PRAGMA foreign_keys = OFF;');
+ db.exec(new VaultSqlGenerator().getCompleteSchemaSql());
+ seedManifest(db, PERSONAL, 'personal');
+ seedManifest(db, SHARED, 'shared');
+ const client = new TestDatabaseClient(db, personalManifestId);
+ return { repository: new ImportExportRepository(client, new LogoRepository(client)), client };
+}
+
+describe('vault export scoping', () => {
+ it('exports only the personal manifest, never a shared one', async () => {
+ const { repository, client } = await vaultWithSharedManifest(PERSONAL);
+
+ const data = runSync(repository.getExportData(), client);
+
+ expect(data.items.map(item => item.Name)).toEqual(['personal item']);
+ expect(data.items[0].FieldValues.map(value => value.Value)).toEqual(['personal user']);
+ expect(data.items[0].TotpCodes.map(code => code.Name)).toEqual(['personal totp']);
+ expect(data.folders.map(folder => folder.Name)).toEqual(['personal folder']);
+ expect(data.tags.map(tag => tag.Name)).toEqual(['personal tag']);
+ expect(data.itemTags).toHaveLength(1);
+ expect(data.fieldDefinitions.map(definition => definition.Label)).toEqual(['personal field']);
+ expect(data.logos.map(logo => logo.Source)).toEqual(['personal.example']);
+ });
+
+ it('writes only the personal manifest to a CSV export, archived items included', async () => {
+ const { repository, client } = await vaultWithSharedManifest(PERSONAL);
+ client.getDb().run('INSERT INTO Items (ManifestId, Id, Name, ItemType, CreatedAt, UpdatedAt, IsDeleted, ArchivedAt) VALUES (?, ?, ?, ?, ?, ?, 0, ?)', [PERSONAL, 'ARCHIVED', 'personal archived', 'Login', 't', 't', 't']);
+
+ const csv = new TextDecoder().decode(runSync(repository.exportToCsv(), client));
+
+ expect(csv).toContain('personal item');
+ expect(csv).toContain('personal archived');
+ expect(csv).toContain('SECRET');
+ expect(csv).not.toContain('shared');
+ });
+
+ it('refuses to export when no personal manifest is recorded', async () => {
+ const { repository, client } = await vaultWithSharedManifest(null);
+
+ expect(() => runSync(repository.getExportData(), client)).toThrow();
+ expect(() => runSync(repository.exportToCsv(), client)).toThrow();
+ });
+});
diff --git a/core/client/src/database/repositories/ImportExportRepository.ts b/core/client/src/database/repositories/ImportExportRepository.ts
index b7c62935b..d51bcc734 100644
--- a/core/client/src/database/repositories/ImportExportRepository.ts
+++ b/core/client/src/database/repositories/ImportExportRepository.ts
@@ -1,5 +1,6 @@
import { LogoKinds, type ItemType } from '@aliasvault/models/vault';
+import { AliasVaultCsvExportService } from '../../transfer/export/AliasVaultCsvExportService';
import { fromStandardFormat, toStandardFormat } from '../../utilities/DateFormatter';
import { BaseRepository } from '../BaseRepository';
import { scopedKey } from '../ItemRef';
@@ -44,17 +45,45 @@ export class ImportExportRepository extends BaseRepository {
}
/**
- * Read every live item with its child rows, plus the folders, tags, custom field definitions and logos the
- * items use. Trashed items are left out, archived items are included.
+ * The manifest every vault export reads: always the personal manifest.
+ *
+ * Note: shared manifests are not part of a regular vault export. Exporting a shared manifest is a separate,
+ * admin-only flow in the family sharing UI.
+ * @returns The personal manifest id
+ */
+ private *exportManifestId(): DbOp<string> {
+ const manifestId = yield* this.personalManifestId();
+ if (!manifestId) {
+ throw new Error('This client has no personal manifest recorded yet; sync once before exporting.');
+ }
+ return manifestId;
+ }
+
+ /**
+ * Export the personal manifest's live items, archived ones included, as an AliasVault CSV file (built from {@link getExportData}).
+ * @returns The CSV file as UTF-8 bytes
+ */
+ public *exportToCsv(): DbOp<Uint8Array> {
+ const data = yield* this.getExportData();
+ return AliasVaultCsvExportService.exportItemsToCsv(data.items, data.folders);
+ }
+
+ /**
+ * Read every live item of the personal manifest with its child rows, plus the folders, tags, custom field definitions
+ * and logos the items use. Archived items are included, deleted items (in trash) are not.
* @returns The vault data
*/
public *getExportData(): DbOp<VaultExportData> {
+ const manifestId = yield* this.exportManifestId();
+
const itemRows = yield* this.query<{ Id: string; ManifestId: string; Name: string | null; ItemType: string; FolderId: string | null; LogoId: string | null; CreatedAt: string; UpdatedAt: string }>(
- 'SELECT Id, ManifestId, Name, ItemType, FolderId, LogoId, CreatedAt, UpdatedAt FROM Items WHERE IsDeleted = 0 AND DeletedAt IS NULL ORDER BY CreatedAt'
+ 'SELECT Id, ManifestId, Name, ItemType, FolderId, LogoId, CreatedAt, UpdatedAt FROM Items WHERE IsDeleted = 0 AND DeletedAt IS NULL AND ManifestId = ? ORDER BY CreatedAt',
+ [manifestId]
);
const fieldDefinitionRows = yield* this.query<{ Id: string; ManifestId: string; FieldType: string; Label: string; IsMultiValue: number; IsHidden: number; EnableHistory: number; Weight: number; ApplicableToTypes: string | null; CreatedAt: string; UpdatedAt: string }>(
- 'SELECT Id, ManifestId, FieldType, Label, IsMultiValue, IsHidden, EnableHistory, Weight, ApplicableToTypes, CreatedAt, UpdatedAt FROM FieldDefinitions WHERE IsDeleted = 0'
+ 'SELECT Id, ManifestId, FieldType, Label, IsMultiValue, IsHidden, EnableHistory, Weight, ApplicableToTypes, CreatedAt, UpdatedAt FROM FieldDefinitions WHERE IsDeleted = 0 AND ManifestId = ?',
+ [manifestId]
);
const fieldDefinitions = fieldDefinitionRows.map((row): FieldDefinitionEntity & { ManifestId: string } => ({
Id: row.Id,
@@ -73,7 +102,8 @@ export class ImportExportRepository extends BaseRepository {
const definitionsByKey = new Map(fieldDefinitions.map(definition => [scopedKey(definition.ManifestId, definition.Id), definition]));
const fieldValueRows = yield* this.query<ChildRow & { Id: string; FieldKey: string | null; FieldDefinitionId: string | null; Value: string | null; Weight: number; CreatedAt: string; UpdatedAt: string }>(
- 'SELECT fv.Id, fv.ItemId, fv.ManifestId, fv.FieldKey, fv.FieldDefinitionId, fv.Value, fv.Weight, fv.CreatedAt, fv.UpdatedAt FROM FieldValues fv INNER JOIN Items i ON i.Id = fv.ItemId AND i.ManifestId = fv.ManifestId WHERE fv.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL ORDER BY fv.Weight, fv.ValueIndex'
+ 'SELECT fv.Id, fv.ItemId, fv.ManifestId, fv.FieldKey, fv.FieldDefinitionId, fv.Value, fv.Weight, fv.CreatedAt, fv.UpdatedAt FROM FieldValues fv INNER JOIN Items i ON i.Id = fv.ItemId AND i.ManifestId = fv.ManifestId WHERE fv.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ManifestId = ? ORDER BY fv.Weight, fv.ValueIndex',
+ [manifestId]
);
const fieldValuesByItem = ImportExportRepository.groupByItem(fieldValueRows, (row): FieldValueEntity => ({
Id: row.Id,
@@ -89,7 +119,8 @@ export class ImportExportRepository extends BaseRepository {
}));
const attachmentRows = yield* this.query<ChildRow & { Id: string; Filename: string; Blob: Uint8Array | null; CreatedAt: string; UpdatedAt: string }>(
- 'SELECT a.Id, a.ItemId, a.ManifestId, a.Filename, a.Blob, a.CreatedAt, a.UpdatedAt FROM Attachments a INNER JOIN Items i ON i.Id = a.ItemId AND i.ManifestId = a.ManifestId WHERE a.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL'
+ 'SELECT a.Id, a.ItemId, a.ManifestId, a.Filename, a.Blob, a.CreatedAt, a.UpdatedAt FROM Attachments a INNER JOIN Items i ON i.Id = a.ItemId AND i.ManifestId = a.ManifestId WHERE a.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ManifestId = ?',
+ [manifestId]
);
const attachmentsByItem = ImportExportRepository.groupByItem(attachmentRows, (row): AttachmentEntity => ({
Id: row.Id,
@@ -102,7 +133,8 @@ export class ImportExportRepository extends BaseRepository {
}));
const totpRows = yield* this.query<ChildRow & { Id: string; Name: string; SecretKey: string; Algorithm: string | null; Digits: number | null; Period: number | null; CreatedAt: string; UpdatedAt: string }>(
- 'SELECT t.Id, t.ItemId, t.ManifestId, t.Name, t.SecretKey, t.Algorithm, t.Digits, t.Period, t.CreatedAt, t.UpdatedAt FROM TotpCodes t INNER JOIN Items i ON i.Id = t.ItemId AND i.ManifestId = t.ManifestId WHERE t.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL'
+ 'SELECT t.Id, t.ItemId, t.ManifestId, t.Name, t.SecretKey, t.Algorithm, t.Digits, t.Period, t.CreatedAt, t.UpdatedAt FROM TotpCodes t INNER JOIN Items i ON i.Id = t.ItemId AND i.ManifestId = t.ManifestId WHERE t.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ManifestId = ?',
+ [manifestId]
);
const totpCodesByItem = ImportExportRepository.groupByItem(totpRows, (row): TotpCodeEntity => ({
Id: row.Id,
@@ -118,7 +150,8 @@ export class ImportExportRepository extends BaseRepository {
}));
const passkeyRows = yield* this.query<ChildRow & { Id: string; RpId: string; UserHandle: Uint8Array | null; PublicKey: string; PrivateKey: string; PrfKey: Uint8Array | null; DisplayName: string; CreatedAt: string; UpdatedAt: string }>(
- 'SELECT p.Id, p.ItemId, p.ManifestId, p.RpId, p.UserHandle, p.PublicKey, p.PrivateKey, p.PrfKey, p.DisplayName, p.CreatedAt, p.UpdatedAt FROM Passkeys p INNER JOIN Items i ON i.Id = p.ItemId AND i.ManifestId = p.ManifestId WHERE p.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL'
+ 'SELECT p.Id, p.ItemId, p.ManifestId, p.RpId, p.UserHandle, p.PublicKey, p.PrivateKey, p.PrfKey, p.DisplayName, p.CreatedAt, p.UpdatedAt FROM Passkeys p INNER JOIN Items i ON i.Id = p.ItemId AND i.ManifestId = p.ManifestId WHERE p.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ManifestId = ?',
+ [manifestId]
);
const passkeysByItem = ImportExportRepository.groupByItem(passkeyRows, (row): PasskeyEntity => ({
Id: row.Id,
@@ -153,7 +186,8 @@ export class ImportExportRepository extends BaseRepository {
});
const folderRows = yield* this.query<{ Id: string; Name: string; ParentFolderId: string | null; Weight: number; CreatedAt: string; UpdatedAt: string }>(
- 'SELECT Id, Name, ParentFolderId, Weight, CreatedAt, UpdatedAt FROM Folders WHERE IsDeleted = 0'
+ 'SELECT Id, Name, ParentFolderId, Weight, CreatedAt, UpdatedAt FROM Folders WHERE IsDeleted = 0 AND ManifestId = ?',
+ [manifestId]
);
const folders = folderRows.map((row): FolderEntity => ({
Id: row.Id,
@@ -166,7 +200,8 @@ export class ImportExportRepository extends BaseRepository {
}));
const tagRows = yield* this.query<{ Id: string; Name: string; Color: string | null; DisplayOrder: number; CreatedAt: string; UpdatedAt: string }>(
- 'SELECT Id, Name, Color, DisplayOrder, CreatedAt, UpdatedAt FROM Tags WHERE IsDeleted = 0'
+ 'SELECT Id, Name, Color, DisplayOrder, CreatedAt, UpdatedAt FROM Tags WHERE IsDeleted = 0 AND ManifestId = ?',
+ [manifestId]
);
const tags = tagRows.map((row): TagEntity => ({
Id: row.Id,
@@ -178,13 +213,14 @@ export class ImportExportRepository extends BaseRepository {
IsDeleted: false,
}));
- const itemTagRows = yield* this.query<{ ItemId: string; TagId: string }>('SELECT ItemId, TagId FROM ItemTags WHERE IsDeleted = 0');
+ const itemTagRows = yield* this.query<{ ItemId: string; TagId: string }>('SELECT ItemId, TagId FROM ItemTags WHERE IsDeleted = 0 AND ManifestId = ?', [manifestId]);
const itemTags = itemTagRows.map((row): ItemTagEntity => ({ ItemId: row.ItemId, TagId: row.TagId, IsDeleted: false }));
// Only the logos the exported items point at.
const logoIds = new Set(items.map(item => item.LogoId).filter((id): id is string => id !== null));
const logoRows = yield* this.query<{ Id: string; Source: string; FileData: Uint8Array | null; MimeType: string | null; UpdatedAt: string }>(
- 'SELECT Id, Source, FileData, MimeType, UpdatedAt FROM Logos WHERE IsDeleted = 0'
+ 'SELECT Id, Source, FileData, MimeType, UpdatedAt FROM Logos WHERE IsDeleted = 0 AND ManifestId = ?',
+ [manifestId]
);
const logos = logoRows.filter(row => logoIds.has(row.Id)).map((row): LogoEntity => ({
Id: row.Id,
diff --git a/core/client/src/transfer/export/AliasVaultCsvExportService.ts b/core/client/src/transfer/export/AliasVaultCsvExportService.ts
index 9ae5c2d18..efcda3a39 100644
--- a/core/client/src/transfer/export/AliasVaultCsvExportService.ts
+++ b/core/client/src/transfer/export/AliasVaultCsvExportService.ts
@@ -1,11 +1,10 @@
-import { FieldKey, getFieldValue, getFieldValues, normalizeTotpAlgorithm, normalizeTotpDigits, normalizeTotpPeriod, TOTP_DEFAULT_ALGORITHM, TOTP_DEFAULT_DIGITS, TOTP_DEFAULT_PERIOD } from '@aliasvault/models/vault';
+import { FieldKey, normalizeTotpAlgorithm, normalizeTotpDigits, normalizeTotpPeriod, TOTP_DEFAULT_ALGORITHM, TOTP_DEFAULT_DIGITS, TOTP_DEFAULT_PERIOD } from '@aliasvault/models/vault';
-import { fromStandardFormat } from '../../utilities/DateFormatter';
import { parseDateExact } from '../shared/DateTimeUtils';
import { writeCsv } from './CsvWriter';
-import type { Item, TotpCode } from '@aliasvault/models/vault';
+import type { FolderEntity, ItemEntity, TotpCodeEntity } from '../shared/VaultEntities';
/** The columns of the AliasVault CSV export. */
export const ALIASVAULT_CSV_COLUMNS = [
@@ -40,27 +39,30 @@ export type AliasVaultCsvColumn = (typeof ALIASVAULT_CSV_COLUMNS)[number];
export class AliasVaultCsvExportService {
/**
* Export items to CSV.
- * @param items - The items to export
- * @param getTotpCodes - Reads an item's TOTP codes; the first one is exported
+ * @param items - The items to export, as read by the vault export
+ * @param folders - The folders the items live in, to write each item's folder path
* @returns The CSV file as UTF-8 bytes
*/
- public static exportItemsToCsv(items: Item[], getTotpCodes: (item: Item) => TotpCode[] = (): TotpCode[] => []): Uint8Array {
- const rows = items.map((item): string[] => {
+ public static exportItemsToCsv(items: ItemEntity[], folders: FolderEntity[] = []): Uint8Array {
+ const foldersById = new Map(folders.filter(folder => !folder.IsDeleted).map(folder => [folder.Id, folder]));
+ const rows = items.filter(item => !item.IsDeleted).map((item): string[] => {
+ const fieldValues = item.FieldValues.filter(fv => !fv.IsDeleted).sort((a, b) => a.Weight - b.Weight);
/**
- *
+ * All values of a system field, in order.
*/
+ const values = (fieldKey: string): string[] => fieldValues.filter(fv => fv.FieldKey === fieldKey).map(fv => fv.Value ?? '');
/**
* A single field value, or the empty string when absent.
*/
- const field = (fieldKey: string): string => getFieldValue(item, fieldKey) ?? '';
+ const field = (fieldKey: string): string => values(fieldKey)[0] ?? '';
const record: Record<AliasVaultCsvColumn, string | Date | null> = {
ServiceName: item.Name ?? '',
- FolderPath: item.FolderPath?.join('/') ?? '',
- ServiceUrl: getFieldValues(item, FieldKey.LoginUrl).map(url => url.trim()).filter(url => url.length > 0).join(','),
+ FolderPath: AliasVaultCsvExportService.folderPath(item.FolderId, foldersById),
+ ServiceUrl: values(FieldKey.LoginUrl).map(url => url.trim()).filter(url => url.length > 0).join(','),
Username: field(FieldKey.LoginUsername),
CurrentPassword: field(FieldKey.LoginPassword),
AliasEmail: field(FieldKey.LoginEmail),
- TwoFactorSecret: AliasVaultCsvExportService.formatTwoFactorSecret(getTotpCodes(item)[0] ?? null),
+ TwoFactorSecret: AliasVaultCsvExportService.formatTwoFactorSecret(item.TotpCodes.find(code => !code.IsDeleted) ?? null),
AliasGender: field(FieldKey.AliasGender),
AliasFirstName: field(FieldKey.AliasFirstName),
AliasLastName: field(FieldKey.AliasLastName),
@@ -72,8 +74,8 @@ export class AliasVaultCsvExportService {
CardExpiryYear: field(FieldKey.CardExpiryYear),
CardCvv: field(FieldKey.CardCvv),
CardPin: field(FieldKey.CardPin),
- CreatedAt: fromStandardFormat(item.CreatedAt),
- UpdatedAt: fromStandardFormat(item.UpdatedAt),
+ CreatedAt: item.CreatedAt,
+ UpdatedAt: item.UpdatedAt,
};
return ALIASVAULT_CSV_COLUMNS.map(header => {
@@ -88,12 +90,28 @@ export class AliasVaultCsvExportService {
return new TextEncoder().encode(writeCsv([...ALIASVAULT_CSV_COLUMNS], rows));
}
+ /**
+ * The "/"-joined names of a folder and its parents, root first.
+ * @param folderId - The item's folder, or null for none
+ * @param foldersById - The exported folders by id
+ * @returns The folder path, or the empty string outside any folder
+ */
+ private static folderPath(folderId: string | null, foldersById: Map<string, FolderEntity>): string {
+ const names: string[] = [];
+ const visited = new Set<string>();
+ for (let folder = folderId ? foldersById.get(folderId) : undefined; folder && !visited.has(folder.Id); folder = folder.ParentFolderId ? foldersById.get(folder.ParentFolderId) : undefined) {
+ visited.add(folder.Id);
+ names.unshift(folder.Name);
+ }
+ return names.join('/');
+ }
+
/**
* 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: TotpCode | null): string {
+ private static formatTwoFactorSecret(totpCode: TotpCodeEntity | null): string {
if (!totpCode) {
return '';
}
diff --git a/core/client/src/transfer/export/__tests__/AliasVaultCsvExportService.test.ts b/core/client/src/transfer/export/__tests__/AliasVaultCsvExportService.test.ts
index 9f5027b2b..28b8994ac 100644
--- a/core/client/src/transfer/export/__tests__/AliasVaultCsvExportService.test.ts
+++ b/core/client/src/transfer/export/__tests__/AliasVaultCsvExportService.test.ts
@@ -6,11 +6,11 @@ import { AliasVaultCsvImportService } from '../../import/importers/aliasvault/Al
import { convertToItems } from '../../import/writers/ItemConverter';
import { AliasVaultCsvExportService } from '../AliasVaultCsvExportService';
-import { createAppItem, csvText } from './testHelpers';
+import { addFieldValue, addTotpCode, createTestItem, csvText } from './testHelpers';
describe('AliasVaultCsvExportService', () => {
it('re-imports an exported item from CSV unchanged', () => {
- const item = createAppItem('Test Service', ItemTypes.Login, {
+ const item = createTestItem('Test Service', ItemTypes.Login, {
[FieldKey.LoginUsername]: 'testuser',
[FieldKey.NotesContent]: 'Test notes',
[FieldKey.LoginUrl]: 'https://testservice.com',
@@ -31,8 +31,8 @@ describe('AliasVaultCsvExportService', () => {
expect(credential.ServiceUrls?.[0]).toBe('https://testservice.com');
expect(credential.Username).toBe('testuser');
expect(credential.Notes).toBe('Test notes');
- expect(credential.CreatedAt?.toISOString().substring(0, 10)).toBe(item.CreatedAt.substring(0, 10));
- expect(credential.UpdatedAt?.toISOString().substring(0, 10)).toBe(item.UpdatedAt.substring(0, 10));
+ expect(credential.CreatedAt?.toISOString().substring(0, 10)).toBe(item.CreatedAt.toISOString().substring(0, 10));
+ expect(credential.UpdatedAt?.toISOString().substring(0, 10)).toBe(item.UpdatedAt.toISOString().substring(0, 10));
expect(credential.Alias!.Gender).toBe('Male');
expect(credential.Alias!.FirstName).toBe('John');
expect(credential.Alias!.LastName).toBe('Doe');
@@ -41,8 +41,8 @@ describe('AliasVaultCsvExportService', () => {
});
it('re-imports an exported credit card item from CSV unchanged', () => {
- const loginItem = createAppItem('Login service', ItemTypes.Login, { [FieldKey.LoginUsername]: 'loginuser', [FieldKey.LoginPassword]: 'loginpass' });
- const cardItem = createAppItem('My Visa', ItemTypes.CreditCard, {
+ const loginItem = createTestItem('Login service', ItemTypes.Login, { [FieldKey.LoginUsername]: 'loginuser', [FieldKey.LoginPassword]: 'loginpass' });
+ const cardItem = createTestItem('My Visa', ItemTypes.CreditCard, {
[FieldKey.CardCardholderName]: 'John Doe',
[FieldKey.CardNumber]: '4111111111111111',
[FieldKey.CardExpiryMonth]: '12',
@@ -79,10 +79,10 @@ describe('AliasVaultCsvExportService', () => {
});
it('re-imports multiple service URLs', () => {
- const item = createAppItem('Multi url service', ItemTypes.Login, {
- [FieldKey.LoginUsername]: 'testuser',
- [FieldKey.LoginUrl]: ['https://www.aliasvault.com', 'https://app.aliasvault.com', 'https://downloads.aliasvault.com'],
- });
+ const item = createTestItem('Multi url service', ItemTypes.Login, { [FieldKey.LoginUsername]: 'testuser' });
+ addFieldValue(item, FieldKey.LoginUrl, 'https://www.aliasvault.com', 0);
+ addFieldValue(item, FieldKey.LoginUrl, 'https://app.aliasvault.com', 1);
+ addFieldValue(item, FieldKey.LoginUrl, 'https://downloads.aliasvault.com', 2);
const csv = csvText(AliasVaultCsvExportService.exportItemsToCsv([item]));
const imported = AliasVaultCsvImportService.importItemsFromCsv(csv);
@@ -95,4 +95,20 @@ describe('AliasVaultCsvExportService', () => {
const urlFieldValues = convertedItem.FieldValues.filter(fv => fv.FieldKey === FieldKey.LoginUrl).sort((a, b) => a.Weight - b.Weight);
expect(urlFieldValues.map(fv => fv.Value)).toEqual(['https://www.aliasvault.com', 'https://app.aliasvault.com', 'https://downloads.aliasvault.com']);
});
+
+ it('writes the folder path and the first 2FA secret', () => {
+ const item = createTestItem('In a folder', ItemTypes.Login, { [FieldKey.LoginUsername]: 'testuser' });
+ addTotpCode(item, 'JBSWY3DPEHPK3PXP');
+ const now = new Date();
+ const folders = [
+ { Id: 'PARENT', Name: 'Work', ParentFolderId: null, Weight: 0, CreatedAt: now, UpdatedAt: now, IsDeleted: false },
+ { Id: 'CHILD', Name: 'Projects', ParentFolderId: 'PARENT', Weight: 0, CreatedAt: now, UpdatedAt: now, IsDeleted: false },
+ ];
+ item.FolderId = 'CHILD';
+
+ const imported = AliasVaultCsvImportService.importItemsFromCsv(csvText(AliasVaultCsvExportService.exportItemsToCsv([item], folders)));
+
+ expect(imported[0].FolderPath).toBe('Work/Projects');
+ expect(imported[0].TwoFactorSecret).toBe('JBSWY3DPEHPK3PXP');
+ });
});
diff --git a/core/client/src/transfer/export/__tests__/testHelpers.ts b/core/client/src/transfer/export/__tests__/testHelpers.ts
index 513db827b..54cf153b6 100644
--- a/core/client/src/transfer/export/__tests__/testHelpers.ts
+++ b/core/client/src/transfer/export/__tests__/testHelpers.ts
@@ -1,10 +1,7 @@
-import { FieldTypes } from '@aliasvault/models/vault';
-
-import { toStandardFormat } from '../../../utilities/DateFormatter';
import { AvuxExportService } from '../AvuxExportService';
import type { FieldDefinitionEntity, FieldValueEntity, ItemEntity, LogoEntity } from '../../shared/VaultEntities';
-import type { Item, ItemType } from '@aliasvault/models/vault';
+import type { ItemType } from '@aliasvault/models/vault';
/*
* Item builders for the export tests.
@@ -19,35 +16,6 @@ export function csvText(bytes: Uint8Array): string {
return new TextDecoder().decode(bytes);
}
-/**
- * Build a test item as the app reads it from the vault.
- * @param name - The item name
- * @param itemType - The item type
- * @param fields - System field values by key; an array for a multi-value field, in display order
- * @returns The item
- */
-export function createAppItem(name: string, itemType: ItemType, fields: Record<string, string | string[]>): Item {
- const now = toStandardFormat(new Date());
- return {
- Id: crypto.randomUUID(),
- ManifestId: crypto.randomUUID(),
- Name: name,
- ItemType: itemType,
- CreatedAt: now,
- UpdatedAt: now,
- Fields: Object.entries(fields).map(([fieldKey, value], index) => ({
- FieldKey: fieldKey,
- Label: fieldKey,
- FieldType: FieldTypes.Text,
- Value: value,
- IsHidden: false,
- DisplayOrder: index,
- IsCustomField: false,
- EnableHistory: false,
- })),
- };
-}
-
/**
* Build a test item.
* @param name - The item name