Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update history tracking to save value on change directly to history (#1473)
Leendert de Borst106a62c895ee
diff --git a/apps/browser-extension/src/utils/db/repositories/ItemRepository.ts b/apps/browser-extension/src/utils/db/repositories/ItemRepository.tsindex c8b8fd0ff..5649db336 100644--- a/apps/browser-extension/src/utils/db/repositories/ItemRepository.ts+++ b/apps/browser-extension/src/utils/db/repositories/ItemRepository.ts@@ -412,6 +412,7 @@ export class ItemRepository extends BaseRepository {/*** Insert field values for a new item.+ * Also creates history records for fields with EnableHistory=true.*/private insertFieldValues(itemId: string,@@ -434,12 +435,9 @@ export class ItemRepository extends BaseRepository {// Handle multi-value fieldsconst values = Array.isArray(field.Value) ? field.Value : [field.Value];+ const filteredValues = values.filter(v => v && v.trim() !== '');- for (const value of values) {- if (!value || (typeof value === 'string' && value.trim() === '')) {- continue;- }-+ for (const value of filteredValues) {this.client.executeUpdate(FieldValueQueries.INSERT, [this.generateId(),itemId,@@ -452,6 +450,24 @@ export class ItemRepository extends BaseRepository {0]);}++ // Create history record for fields with EnableHistory=true+ if (field.EnableHistory && filteredValues.length > 0) {+ const historyId = this.generateId();+ const valueSnapshot = JSON.stringify(filteredValues);++ this.client.executeUpdate(FieldHistoryQueries.INSERT, [+ historyId,+ itemId,+ null,+ field.FieldKey,+ valueSnapshot,+ currentDateTime,+ currentDateTime,+ currentDateTime,+ 0+ ]);+ }}}@@ -615,6 +631,11 @@ export class ItemRepository extends BaseRepository {/*** Track field history for fields with EnableHistory=true.+ *+ * This saves the NEW value to history on every change. Since each value is saved+ * when it's set, we don't need to save the old value (it was already saved when+ * it was first set). This ensures that during merge conflicts, no values are ever+ * lost since history records sync independently via LWW and each has a unique ID.*/private async trackFieldHistory(itemId: string,@@ -648,12 +669,16 @@ export class ItemRepository extends BaseRepository {const oldValues = existingValuesMap[newField.FieldKey] || [];const newValues = Array.isArray(newField.Value) ? newField.Value : [newField.Value];- const valuesChanged = oldValues.length !== newValues.length ||- !oldValues.every((val, idx) => val === newValues[idx]);+ // Filter out empty values for comparison+ const filteredNewValues = newValues.filter(v => v && v.trim() !== '');++ const valuesChanged = oldValues.length !== filteredNewValues.length ||+ !oldValues.every((val, idx) => val === filteredNewValues[idx]);- if (valuesChanged && oldValues.length > 0) {+ // Save new values to history when they change (ensures they survive merge conflicts)+ if (valuesChanged && filteredNewValues.length > 0) {const historyId = this.generateId();- const valueSnapshot = JSON.stringify(oldValues);+ const valueSnapshot = JSON.stringify(filteredNewValues);this.client.executeUpdate(FieldHistoryQueries.INSERT, [historyId,diff --git a/apps/mobile-app/utils/db/repositories/ItemRepository.ts b/apps/mobile-app/utils/db/repositories/ItemRepository.tsindex 4251d804c..caf24d63d 100644--- a/apps/mobile-app/utils/db/repositories/ItemRepository.ts+++ b/apps/mobile-app/utils/db/repositories/ItemRepository.ts@@ -413,15 +413,16 @@ export class ItemRepository extends BaseRepository {/*** Insert field values for an item.+ * Also creates history records for fields with EnableHistory=true.*/private async insertFieldValues(itemId: string, fields: ItemField[], now: string): Promise<void> {for (let i = 0; i < fields.length; i++) {const field = fields[i];const values = Array.isArray(field.Value) ? field.Value : [field.Value];+ const filteredValues = values.filter(v => v !== undefined && v !== null && v !== '');- for (let j = 0; j < values.length; j++) {- const value = values[j];- if (value === undefined || value === null || value === '') continue;+ for (let j = 0; j < filteredValues.length; j++) {+ const value = filteredValues[j];await this.client.executeUpdate(FieldValueQueries.INSERT, [this.generateId(),@@ -435,6 +436,27 @@ export class ItemRepository extends BaseRepository {0]);}++ // Create history record for fields with EnableHistory=true+ if (field.EnableHistory && filteredValues.length > 0) {+ // Check if FieldHistories table exists+ if (await this.tableExists('FieldHistories')) {+ const historyId = this.generateId();+ const valueSnapshot = JSON.stringify(filteredValues);++ await this.client.executeUpdate(FieldHistoryQueries.INSERT, [+ historyId,+ itemId,+ null,+ field.FieldKey,+ valueSnapshot,+ now,+ now,+ now,+ 0+ ]);+ }+ }}}@@ -547,6 +569,11 @@ export class ItemRepository extends BaseRepository {/*** Track field history for fields with EnableHistory=true.* Compares old values with new values and creates history records.+ *+ * This saves the NEW value to history on every change. Since each value is saved+ * when it's set, we don't need to save the old value (it was already saved when+ * it was first set). This ensures that during merge conflicts, no values are ever+ * lost since history records sync independently via LWW and each has a unique ID.*/private async trackFieldHistory(itemId: string,@@ -585,12 +612,16 @@ export class ItemRepository extends BaseRepository {const oldValues = existingValuesMap[newField.FieldKey] || [];const newValues = Array.isArray(newField.Value) ? newField.Value : [newField.Value];- const valuesChanged = oldValues.length !== newValues.length ||- !oldValues.every((val, idx) => val === newValues[idx]);+ // Filter out empty values for comparison+ const filteredNewValues = newValues.filter(v => v && v.trim() !== '');++ const valuesChanged = oldValues.length !== filteredNewValues.length ||+ !oldValues.every((val, idx) => val === filteredNewValues[idx]);- if (valuesChanged && oldValues.length > 0) {+ // Save new values to history when they change (ensures they survive merge conflicts)+ if (valuesChanged && filteredNewValues.length > 0) {const historyId = this.generateId();- const valueSnapshot = JSON.stringify(oldValues);+ const valueSnapshot = JSON.stringify(filteredNewValues);await this.client.executeUpdate(FieldHistoryQueries.INSERT, [historyId,diff --git a/apps/server/AliasVault.Client/Services/ItemService.cs b/apps/server/AliasVault.Client/Services/ItemService.csindex 4ec4b6fd1..bd0640f4b 100644--- a/apps/server/AliasVault.Client/Services/ItemService.cs+++ b/apps/server/AliasVault.Client/Services/ItemService.cs@@ -226,6 +226,9 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, ConftotpCode.UpdatedAt = currentDateTime;}+ // Create history records for fields with EnableHistory=true+ await CreateInitialFieldHistoryAsync(context, item, currentDateTime);+context.Items.Add(item);// Save the database to the server if saveToDb is true.@@ -1289,6 +1292,11 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf/// <summary>/// Track field history for fields with EnableHistory=true./// Compares old values with new values and creates history records.+ ///+ /// This saves the NEW value to history on every change. Since each value is saved+ /// when it's set, we don't need to save the old value (it was already saved when+ /// it was first set). This ensures that during merge conflicts, no values are ever+ /// lost since history records sync independently via LWW and each has a unique ID./// </summary>/// <param name="context">The database context.</param>/// <param name="existingItem">The existing item in the database.</param>@@ -1328,17 +1336,17 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Confvar oldValues = existingByFieldKey.TryGetValue(fieldKey, out var values) ? values : new List<string>();+ // Filter out empty values for comparison+ var filteredNewValues = newValues.Where(v => !string.IsNullOrWhiteSpace(v)).ToList();+// Check if values have changed- var valuesChanged = oldValues.Count != newValues.Count ||- !oldValues.SequenceEqual(newValues);+ var valuesChanged = oldValues.Count != filteredNewValues.Count ||+ !oldValues.SequenceEqual(filteredNewValues);- // Only create history if values changed AND there were old values- if (valuesChanged && oldValues.Count > 0)+ // Save new values to history when they change (ensures they survive merge conflicts)+ if (valuesChanged && filteredNewValues.Count > 0){- // Create a JSON snapshot of old values- var valueSnapshot = System.Text.Json.JsonSerializer.Serialize(oldValues);-- // Create new history record+ var valueSnapshot = System.Text.Json.JsonSerializer.Serialize(filteredNewValues);var historyRecord = new FieldHistory{Id = Guid.NewGuid(),@@ -1359,6 +1367,56 @@ public sealed class ItemService(HttpClient httpClient, DbService dbService, Conf}}+ /// <summary>+ /// Create initial field history records for fields with EnableHistory=true when creating a new item.+ /// This ensures the initial value is captured in history for merge conflict resolution.+ /// </summary>+ /// <param name="context">The database context.</param>+ /// <param name="item">The new item being created.</param>+ /// <param name="createDateTime">The timestamp for creation.</param>+ /// <returns>Task.</returns>+ private static Task CreateInitialFieldHistoryAsync(AliasClientDbContext context, Item item, DateTime createDateTime)+ {+ // Group field values by key to handle multi-value fields+ var fieldsByKey = item.FieldValues+ .Where(fv => !fv.IsDeleted && fv.FieldKey != null)+ .GroupBy(f => f.FieldKey!)+ .ToDictionary(g => g.Key, g => g.OrderBy(f => f.Weight).Select(f => f.Value ?? string.Empty).ToList());++ foreach (var (fieldKey, values) in fieldsByKey)+ {+ // Check if history tracking is enabled for this field+ var fieldDef = SystemFieldRegistry.GetSystemField(fieldKey);+ if (fieldDef == null || !fieldDef.EnableHistory)+ {+ continue;+ }++ // Filter out empty values+ var filteredValues = values.Where(v => !string.IsNullOrWhiteSpace(v)).ToList();++ if (filteredValues.Count > 0)+ {+ var valueSnapshot = System.Text.Json.JsonSerializer.Serialize(filteredValues);+ var historyRecord = new FieldHistory+ {+ Id = Guid.NewGuid(),+ ItemId = item.Id,+ FieldKey = fieldKey,+ FieldDefinitionId = null,+ ValueSnapshot = valueSnapshot,+ ChangedAt = createDateTime,+ CreatedAt = createDateTime,+ UpdatedAt = createDateTime,+ IsDeleted = false,+ };+ context.FieldHistories.Add(historyRecord);+ }+ }++ return Task.CompletedTask;+ }+/// <summary>/// Prune old field history records./// Keeps only the most recent MaxFieldHistoryRecords records.