Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Make vault creation work via vault-sql lib in AliasVault.Client (#955)
Leendert de Borst3e82f78fe9e9
diff --git a/apps/server/AliasVault.Client/Main/Pages/Sync/StatusMessages/Creating.razor b/apps/server/AliasVault.Client/Main/Pages/Sync/StatusMessages/Creating.razorindex 99dbc95ee..beb216378 100644--- a/apps/server/AliasVault.Client/Main/Pages/Sync/StatusMessages/Creating.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Sync/StatusMessages/Creating.razor@@ -50,7 +50,7 @@await Task.Delay(1000);// Migrate (create) the database.- if (await DbService.MigrateDatabaseAsync())+ if (await DbService.CreateNewVaultAsync()){// Save the database to the server.if (await DbService.SaveDatabaseAsync())diff --git a/apps/server/AliasVault.Client/Services/Database/DbService.cs b/apps/server/AliasVault.Client/Services/Database/DbService.csindex d9b5b1d3a..573c899e0 100644--- a/apps/server/AliasVault.Client/Services/Database/DbService.cs+++ b/apps/server/AliasVault.Client/Services/Database/DbService.cs@@ -312,6 +312,32 @@ public sealed class DbService : IDisposablereturn base64String;}+ /// <summary>+ /// Creates a new vault with the latest schema.+ /// </summary>+ /// <returns>Bool which indicates if creating a new vault was successful.</returns>+ public async Task<bool> CreateNewVaultAsync()+ {+ try+ {+ // Call JS interop to get SQL commands to create a new vault with the latest schema.+ var sqlCommands = await _jsInteropService.GetCreateVaultSqlAsync();++ // Execute the SQL commands to create a new vault with the latest schema.+ foreach (var sqlCommand in sqlCommands.SqlCommands)+ {+ await _dbContext.Database.ExecuteSqlRawAsync(sqlCommand);+ }+ }+ catch (Exception ex)+ {+ _logger.LogError(ex, "Error creating new vault.");+ return false;+ }++ return true;+ }+/// <summary>/// Migrate the database structure to the latest version./// </summary>@@ -320,7 +346,16 @@ public sealed class DbService : IDisposable{try{- await _dbContext.Database.MigrateAsync();+ // TODO: migrate database to the latest version via JS interop...+ // Call JS interop to get SQL commands to create a new vault with the latest schema.+ var sqlCommands = await _jsInteropService.GetCreateVaultSqlAsync();++ // Execute the SQL commands to create a new vault with the latest schema.+ foreach (var sqlCommand in sqlCommands.SqlCommands)+ {+ await _dbContext.Database.ExecuteSqlRawAsync(sqlCommand);+ }+_isSuccessfullyInitialized = true;await _settingsService.InitializeAsync(this);}diff --git a/apps/server/AliasVault.Client/Services/JsInteropService.cs b/apps/server/AliasVault.Client/Services/JsInteropService.csindex 6835985a5..a9416f6be 100644--- a/apps/server/AliasVault.Client/Services/JsInteropService.cs+++ b/apps/server/AliasVault.Client/Services/JsInteropService.cs@@ -19,6 +19,7 @@ public sealed class JsInteropService(IJSRuntime jsRuntime){private IJSObjectReference? _identityGeneratorModule;private IJSObjectReference? _passwordGeneratorModule;+ private IJSObjectReference? _vaultSqlInteropModule;/// <summary>/// Initialize the identity generator module.@@ -28,6 +29,7 @@ public sealed class JsInteropService(IJSRuntime jsRuntime){_identityGeneratorModule = await jsRuntime.InvokeAsync<IJSObjectReference>("import", "./js/dist/shared/identity-generator/index.mjs");_passwordGeneratorModule = await jsRuntime.InvokeAsync<IJSObjectReference>("import", "./js/dist/shared/password-generator/index.mjs");+ _vaultSqlInteropModule = await jsRuntime.InvokeAsync<IJSObjectReference>("import", "./js/dist/shared/vault-sql/index.mjs");}/// <summary>@@ -291,7 +293,7 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)/// Generates a random identity using the specified language./// </summary>/// <param name="language">The language to use for generating the identity (e.g. "en", "nl").</param>- /// <returns>A <see cref="AliasVaultIdentity"/> containing the generated identity information.</returns>+ /// <returns>An AliasVaultIdentity containing the generated identity information.</returns>public async Task<AliasVaultIdentity> GenerateRandomIdentityAsync(string language){try@@ -409,6 +411,227 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)}/// <summary>+ /// Gets SQL commands to create a new vault with the latest schema.+ /// </summary>+ /// <returns>SQL generation result with commands to execute.</returns>+ public async Task<SqlGenerationResult> GetCreateVaultSqlAsync()+ {+ try+ {+ if (_vaultSqlInteropModule == null)+ {+ await InitializeAsync();+ if (_vaultSqlInteropModule == null)+ {+ throw new InvalidOperationException("Failed to initialize identity generator module");+ }+ }++ var vaultGenerator = await _vaultSqlInteropModule.InvokeAsync<IJSObjectReference>("CreateVaultSqlGenerator");+ var result = await vaultGenerator.InvokeAsync<JsonElement>("getCreateVaultSql");++ return new SqlGenerationResult+ {+ Success = result.GetProperty("success").GetBoolean(),+ SqlCommands = [.. result.GetProperty("sqlCommands").EnumerateArray()+ .Select(x => x.GetString() ?? string.Empty)+ .Where(x => !string.IsNullOrEmpty(x))],+ Version = result.GetProperty("version").GetString() ?? "0.0.0",+ MigrationNumber = result.GetProperty("migrationNumber").GetInt32(),+ Error = result.TryGetProperty("error", out var errorElement) ? errorElement.GetString() : null,+ };+ }+ catch (JSException ex)+ {+ return new SqlGenerationResult+ {+ Success = false,+ SqlCommands = [],+ Version = "0.0.0",+ MigrationNumber = 0,+ Error = $"JavaScript error: {ex.Message}",+ };+ }+ }++ /// <summary>+ /// Gets SQL commands to check current vault version.+ /// </summary>+ /// <returns>Array of SQL commands to execute.</returns>+ public async Task<string[]> GetVersionCheckSqlAsync()+ {+ try+ {+ if (_vaultSqlInteropModule == null)+ {+ await InitializeAsync();+ if (_vaultSqlInteropModule == null)+ {+ throw new InvalidOperationException("Failed to initialize identity generator module");+ }+ }++ var vaultGenerator = await _vaultSqlInteropModule.InvokeAsync<IJSObjectReference>("CreateVaultSqlGenerator");+ var result = await vaultGenerator.InvokeAsync<JsonElement>("getVersionCheckSql");+ return result.EnumerateArray()+ .Select(x => x.GetString() ?? string.Empty)+ .Where(x => !string.IsNullOrEmpty(x))+ .ToArray();+ }+ catch (JSException)+ {+ return [];+ }+ }++ /// <summary>+ /// Gets SQL command to validate vault structure.+ /// </summary>+ /// <returns>SQL command to validate vault.</returns>+ public async Task<string> GetVaultValidationSqlAsync()+ {+ try+ {+ if (_vaultSqlInteropModule == null)+ {+ await InitializeAsync();+ if (_vaultSqlInteropModule == null)+ {+ throw new InvalidOperationException("Failed to initialize identity generator module");+ }+ }++ var vaultGenerator = await _vaultSqlInteropModule.InvokeAsync<IJSObjectReference>("CreateVaultSqlGenerator");+ return await vaultGenerator.InvokeAsync<string>("getVaultValidationSql");+ }+ catch (JSException)+ {+ return string.Empty;+ }+ }++ /// <summary>+ /// Gets SQL commands to upgrade vault from current to target migration.+ /// </summary>+ /// <param name="currentMigrationNumber">Current migration number.</param>+ /// <param name="targetMigrationNumber">Target migration number (optional, defaults to latest).</param>+ /// <returns>SQL generation result with commands to execute.</returns>+ public async Task<SqlGenerationResult> GetUpgradeVaultSqlAsync(int currentMigrationNumber, int? targetMigrationNumber = null)+ {+ try+ {+ if (_vaultSqlInteropModule == null)+ {+ await InitializeAsync();+ if (_vaultSqlInteropModule == null)+ {+ throw new InvalidOperationException("Failed to initialize identity generator module");+ }+ }++ var vaultGenerator = await _vaultSqlInteropModule.InvokeAsync<IJSObjectReference>("CreateVaultSqlGenerator");+ var result = targetMigrationNumber.HasValue+ ? await vaultGenerator.InvokeAsync<JsonElement>("getUpgradeVaultSql", currentMigrationNumber, targetMigrationNumber.Value)+ : await vaultGenerator.InvokeAsync<JsonElement>("getUpgradeToLatestSql", currentMigrationNumber);++ return new SqlGenerationResult+ {+ Success = result.GetProperty("success").GetBoolean(),+ SqlCommands = [.. result.GetProperty("sqlCommands").EnumerateArray()+ .Select(x => x.GetString() ?? string.Empty)+ .Where(x => !string.IsNullOrEmpty(x))],+ Version = result.GetProperty("version").GetString() ?? "0.0.0",+ MigrationNumber = result.GetProperty("migrationNumber").GetInt32(),+ Error = result.TryGetProperty("error", out var errorElement) ? errorElement.GetString() : null,+ };+ }+ catch (JSException ex)+ {+ return new SqlGenerationResult+ {+ Success = false,+ SqlCommands = [],+ Version = "0.0.0",+ MigrationNumber = 0,+ Error = $"JavaScript error: {ex.Message}",+ };+ }+ }++ /// <summary>+ /// Parses vault version information from query results.+ /// </summary>+ /// <param name="settingsTableExists">Whether Settings table exists.</param>+ /// <param name="versionResult">Version query result.</param>+ /// <param name="migrationResult">Migration number query result.</param>+ /// <returns>Parsed vault version information.</returns>+ public async Task<VaultVersionInfo> ParseVaultVersionInfoAsync(bool settingsTableExists, string? versionResult = null, string? migrationResult = null)+ {+ try+ {+ if (_vaultSqlInteropModule == null)+ {+ await InitializeAsync();+ if (_vaultSqlInteropModule == null)+ {+ throw new InvalidOperationException("Failed to initialize identity generator module");+ }+ }++ var vaultGenerator = await _vaultSqlInteropModule.InvokeAsync<IJSObjectReference>("CreateVaultSqlGenerator");+ var result = await vaultGenerator.InvokeAsync<JsonElement>("parseVaultVersionInfo", settingsTableExists, versionResult, migrationResult);++ return new VaultVersionInfo+ {+ CurrentVersion = result.GetProperty("currentVersion").GetString() ?? "0.0.0",+ CurrentMigrationNumber = result.GetProperty("currentMigrationNumber").GetInt32(),+ TargetVersion = result.GetProperty("targetVersion").GetString() ?? "0.0.0",+ TargetMigrationNumber = result.GetProperty("targetMigrationNumber").GetInt32(),+ NeedsUpgrade = result.GetProperty("needsUpgrade").GetBoolean(),+ };+ }+ catch (JSException ex)+ {+ return new VaultVersionInfo+ {+ CurrentVersion = "0.0.0",+ CurrentMigrationNumber = 0,+ TargetVersion = "0.0.0",+ TargetMigrationNumber = 0,+ NeedsUpgrade = true,+ Error = $"JavaScript error: {ex.Message}",+ };+ }+ }++ /// <summary>+ /// Validates vault structure from table names.+ /// </summary>+ /// <param name="tableNames">List of table names found in database.</param>+ /// <returns>True if vault structure is valid.</returns>+ public async Task<bool> ValidateVaultStructureAsync(string[] tableNames)+ {+ try+ {+ if (_vaultSqlInteropModule == null)+ {+ await InitializeAsync();+ if (_vaultSqlInteropModule == null)+ {+ throw new InvalidOperationException("Failed to initialize identity generator module");+ }+ }++ var vaultGenerator = await _vaultSqlInteropModule.InvokeAsync<IJSObjectReference>("CreateVaultSqlGenerator");+ return await vaultGenerator.InvokeAsync<bool>("validateVaultStructure", tableNames);+ }+ catch (JSException)+ {+ return false;+ }+ }++ /// <summary>/// Represents the result of a JavaScript identity generator operation./// </summary>public sealed class AliasVaultIdentity@@ -444,6 +667,73 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)public string? Gender { get; init; }}+ /// <summary>+ /// Represents the result of SQL generation for vault operations.+ /// </summary>+ public sealed class SqlGenerationResult+ {+ /// <summary>+ /// Gets a value indicating whether the SQL generation was successful.+ /// </summary>+ public bool Success { get; init; }++ /// <summary>+ /// Gets the generated SQL commands to execute.+ /// </summary>+ public List<string> SqlCommands { get; init; } = [];++ /// <summary>+ /// Gets the vault version.+ /// </summary>+ public string Version { get; init; } = "0.0.0";++ /// <summary>+ /// Gets the migration number.+ /// </summary>+ public int MigrationNumber { get; init; }++ /// <summary>+ /// Gets the optional error message.+ /// </summary>+ public string? Error { get; init; }+ }++ /// <summary>+ /// Represents vault version information.+ /// </summary>+ public sealed class VaultVersionInfo+ {+ /// <summary>+ /// Gets the current vault version.+ /// </summary>+ public string CurrentVersion { get; init; } = "0.0.0";++ /// <summary>+ /// Gets the current migration number.+ /// </summary>+ public int CurrentMigrationNumber { get; init; }++ /// <summary>+ /// Gets the target vault version.+ /// </summary>+ public string TargetVersion { get; init; } = "0.0.0";++ /// <summary>+ /// Gets the target migration number.+ /// </summary>+ public int TargetMigrationNumber { get; init; }++ /// <summary>+ /// Gets a value indicating whether the vault needs to be upgraded.+ /// </summary>+ public bool NeedsUpgrade { get; init; }++ /// <summary>+ /// Gets the optional error message.+ /// </summary>+ public string? Error { get; init; }+ }+/// <summary>/// Represents the result of a WebAuthn get credential operation./// </summary>diff --git a/apps/server/AliasVault.Client/wwwroot/js/dist/shared/vault-sql/README.md b/apps/server/AliasVault.Client/wwwroot/js/dist/shared/vault-sql/README.mdnew file mode 100644index 000000000..4db3e7914--- /dev/null+++ b/apps/server/AliasVault.Client/wwwroot/js/dist/shared/vault-sql/README.md@@ -0,0 +1,9 @@+# ⚠️ Auto-Generated Files++This folder contains the output of the shared `vault-sql` module from the `/shared` directory in the AliasVault project.++**Do not edit any of these files manually.**++To make changes:+1. Update the source files in the `/shared/vault-sql/src` directory+2. Run the `build.sh` script in the module directory to regenerate the outputs and copy them here.diff --git a/apps/server/AliasVault.Client/wwwroot/js/dist/shared/vault-sql/index.d.mts b/apps/server/AliasVault.Client/wwwroot/js/dist/shared/vault-sql/index.d.mtsnew file mode 100644index 000000000..637729992--- /dev/null+++ b/apps/server/AliasVault.Client/wwwroot/js/dist/shared/vault-sql/index.d.mts@@ -0,0 +1,126 @@+/**+ * Vault database version information+ */+interface IVaultVersion {+ /**+ * The migration revision number+ */+ revision: number;+ /**+ * The version number (e.g., "1.5.0")+ */+ version: string;+ /**+ * Description of changes in this version+ */+ description: string;+ /**+ * Release date+ */+ releaseDate: string;+}++/**+ * Result of SQL generation operations+ */+interface ISqlGenerationResult {+ success: boolean;+ sqlCommands: string[];+ version: string;+ migrationNumber: number;+ error?: string;+}+/**+ * Information about vault version requirements+ */+interface IVaultVersionInfo {+ currentVersion: string;+ currentMigrationNumber: number;+ targetVersion: string;+ targetMigrationNumber: number;+ needsUpgrade: boolean;+ availableUpgrades: IVaultVersion[];+}+/**+ * Vault SQL generator utility class+ * Provides SQL statements for vault creation and migration without database execution+ */+declare class VaultSqlGenerator {+ /**+ * Get SQL commands to create a new vault with the latest schema+ */+ getCreateVaultSql(): ISqlGenerationResult;+ /**+ * Get SQL commands to upgrade vault from current version to target version+ */+ getUpgradeVaultSql(currentMigrationNumber: number, targetMigrationNumber?: number): ISqlGenerationResult;+ /**+ * Get SQL commands to upgrade vault to latest version+ */+ getUpgradeToLatestSql(currentMigrationNumber: number): ISqlGenerationResult;+ /**+ * Get SQL commands to upgrade vault to a specific version+ */+ getUpgradeToVersionSql(currentMigrationNumber: number, targetVersion: string): ISqlGenerationResult;+ /**+ * Get SQL commands to check current vault version+ */+ getVersionCheckSql(): string[];+ /**+ * Get SQL command to validate vault structure+ */+ getVaultValidationSql(): string;+ /**+ * Parse vault version information from query results+ */+ parseVaultVersionInfo(settingsTableExists: boolean, versionResult?: string, migrationResult?: string): IVaultVersionInfo;+ /**+ * Validate vault structure from table names+ */+ validateVaultStructure(tableNames: string[]): boolean;+ /**+ * Get all available vault versions+ */+ getAvailableVersions(): IVaultVersion[];+ /**+ * Get current/latest vault version info+ */+ getCurrentVersion(): IVaultVersion;+ /**+ * Get specific migration SQL by migration number+ */+ getMigrationSql(migrationNumber: number): string | undefined;+ /**+ * Get complete schema SQL for creating new vault+ */+ getCompleteSchemaeSql(): string;+}++/**+ * Vault version information+ * Auto-generated from EF Core migration filenames+ */++/**+ * Available vault versions in chronological order+ */+declare const VAULT_VERSIONS: IVaultVersion[];++/**+ * Complete database schema SQL (latest version)+ * Auto-generated from EF Core migrations+ */+declare const COMPLETE_SCHEMA_SQL = "\n\uFEFFCREATE TABLE IF NOT EXISTS \"__EFMigrationsHistory\" (\n \"MigrationId\" TEXT NOT NULL CONSTRAINT \"PK___EFMigrationsHistory\" PRIMARY KEY,\n \"ProductVersion\" TEXT NOT NULL\n);\n\nBEGIN TRANSACTION;\nCREATE TABLE \"Aliases\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Aliases\" PRIMARY KEY,\n \"Gender\" VARCHAR NULL,\n \"FirstName\" VARCHAR NULL,\n \"LastName\" VARCHAR NULL,\n \"NickName\" VARCHAR NULL,\n \"BirthDate\" TEXT NOT NULL,\n \"AddressStreet\" VARCHAR NULL,\n \"AddressCity\" VARCHAR NULL,\n \"AddressState\" VARCHAR NULL,\n \"AddressZipCode\" VARCHAR NULL,\n \"AddressCountry\" VARCHAR NULL,\n \"Hobbies\" TEXT NULL,\n \"EmailPrefix\" TEXT NULL,\n \"PhoneMobile\" TEXT NULL,\n \"BankAccountIBAN\" TEXT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL\n);\n\nCREATE TABLE \"Services\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Services\" PRIMARY KEY,\n \"Name\" TEXT NULL,\n \"Url\" TEXT NULL,\n \"Logo\" BLOB NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL\n);\n\nCREATE TABLE \"Credentials\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Credentials\" PRIMARY KEY,\n \"AliasId\" TEXT NOT NULL,\n \"Notes\" TEXT NULL,\n \"Username\" TEXT NOT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL,\n \"ServiceId\" TEXT NOT NULL,\n CONSTRAINT \"FK_Credentials_Aliases_AliasId\" FOREIGN KEY (\"AliasId\") REFERENCES \"Aliases\" (\"Id\") ON DELETE CASCADE,\n CONSTRAINT \"FK_Credentials_Services_ServiceId\" FOREIGN KEY (\"ServiceId\") REFERENCES \"Services\" (\"Id\") ON DELETE CASCADE\n);\n\nCREATE TABLE \"Attachment\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Attachment\" PRIMARY KEY,\n \"Filename\" TEXT NOT NULL,\n \"Blob\" BLOB NOT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL,\n \"CredentialId\" TEXT NOT NULL,\n CONSTRAINT \"FK_Attachment_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE\n);\n\nCREATE TABLE \"Passwords\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Passwords\" PRIMARY KEY,\n \"Value\" TEXT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL,\n \"CredentialId\" TEXT NOT NULL,\n CONSTRAINT \"FK_Passwords_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE\n);\n\nCREATE INDEX \"IX_Attachment_CredentialId\" ON \"Attachment\" (\"CredentialId\");\n\nCREATE INDEX \"IX_Credentials_AliasId\" ON \"Credentials\" (\"AliasId\");\n\nCREATE INDEX \"IX_Credentials_ServiceId\" ON \"Credentials\" (\"ServiceId\");\n\nCREATE INDEX \"IX_Passwords_CredentialId\" ON \"Passwords\" (\"CredentialId\");\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240708094944_1.0.0-InitialMigration', '9.0.4');\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240708224522_1.0.1-EmptyTestMigration', '9.0.4');\n\nALTER TABLE \"Aliases\" RENAME COLUMN \"EmailPrefix\" TO \"Email\";\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240711204207_1.0.2-ChangeEmailColumn', '9.0.4');\n\nCREATE TABLE \"EncryptionKeys\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_EncryptionKeys\" PRIMARY KEY,\n \"PublicKey\" TEXT NOT NULL,\n \"PrivateKey\" TEXT NOT NULL,\n \"IsPrimary\" INTEGER NOT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL\n);\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240729105618_1.1.0-AddPkiTables', '9.0.4');\n\nCREATE TABLE \"Settings\" (\n \"Key\" TEXT NOT NULL CONSTRAINT \"PK_Settings\" PRIMARY KEY,\n \"Value\" TEXT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL\n);\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240805073413_1.2.0-AddSettingsTable', '9.0.4');\n\nCREATE TABLE \"ef_temp_Aliases\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Aliases\" PRIMARY KEY,\n \"BirthDate\" TEXT NOT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"Email\" TEXT NULL,\n \"FirstName\" VARCHAR NULL,\n \"Gender\" VARCHAR NULL,\n \"LastName\" VARCHAR NULL,\n \"NickName\" VARCHAR NULL,\n \"UpdatedAt\" TEXT NOT NULL\n);\n\nINSERT INTO \"ef_temp_Aliases\" (\"Id\", \"BirthDate\", \"CreatedAt\", \"Email\", \"FirstName\", \"Gender\", \"LastName\", \"NickName\", \"UpdatedAt\")\nSELECT \"Id\", \"BirthDate\", \"CreatedAt\", \"Email\", \"FirstName\", \"Gender\", \"LastName\", \"NickName\", \"UpdatedAt\"\nFROM \"Aliases\";\n\nCOMMIT;\n\nPRAGMA foreign_keys = 0;\n\nBEGIN TRANSACTION;\nDROP TABLE \"Aliases\";\n\nALTER TABLE \"ef_temp_Aliases\" RENAME TO \"Aliases\";\n\nCOMMIT;\n\nPRAGMA foreign_keys = 1;\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240805122422_1.3.0-UpdateIdentityStructure', '9.0.4');\n\nBEGIN TRANSACTION;\nCREATE TABLE \"ef_temp_Credentials\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Credentials\" PRIMARY KEY,\n \"AliasId\" TEXT NOT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"Notes\" TEXT NULL,\n \"ServiceId\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL,\n \"Username\" TEXT NULL,\n CONSTRAINT \"FK_Credentials_Aliases_AliasId\" FOREIGN KEY (\"AliasId\") REFERENCES \"Aliases\" (\"Id\") ON DELETE CASCADE,\n CONSTRAINT \"FK_Credentials_Services_ServiceId\" FOREIGN KEY (\"ServiceId\") REFERENCES \"Services\" (\"Id\") ON DELETE CASCADE\n);\n\nINSERT INTO \"ef_temp_Credentials\" (\"Id\", \"AliasId\", \"CreatedAt\", \"Notes\", \"ServiceId\", \"UpdatedAt\", \"Username\")\nSELECT \"Id\", \"AliasId\", \"CreatedAt\", \"Notes\", \"ServiceId\", \"UpdatedAt\", \"Username\"\nFROM \"Credentials\";\n\nCOMMIT;\n\nPRAGMA foreign_keys = 0;\n\nBEGIN TRANSACTION;\nDROP TABLE \"Credentials\";\n\nALTER TABLE \"ef_temp_Credentials\" RENAME TO \"Credentials\";\n\nCOMMIT;\n\nPRAGMA foreign_keys = 1;\n\nBEGIN TRANSACTION;\nCREATE INDEX \"IX_Credentials_AliasId\" ON \"Credentials\" (\"AliasId\");\n\nCREATE INDEX \"IX_Credentials_ServiceId\" ON \"Credentials\" (\"ServiceId\");\n\nCOMMIT;\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240812141727_1.3.1-MakeUsernameOptional', '9.0.4');\n\nBEGIN TRANSACTION;\nALTER TABLE \"Settings\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;\n\nALTER TABLE \"Services\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;\n\nALTER TABLE \"Passwords\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;\n\nALTER TABLE \"EncryptionKeys\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;\n\nALTER TABLE \"Credentials\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;\n\nALTER TABLE \"Attachment\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;\n\nALTER TABLE \"Aliases\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240916105320_1.4.0-AddSyncSupport', '9.0.4');\n\nALTER TABLE \"Attachment\" RENAME TO \"Attachments\";\n\nCREATE TABLE \"ef_temp_Attachments\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Attachments\" PRIMARY KEY,\n \"Blob\" BLOB NOT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"CredentialId\" TEXT NOT NULL,\n \"Filename\" TEXT NOT NULL,\n \"IsDeleted\" INTEGER NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL,\n CONSTRAINT \"FK_Attachments_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE\n);\n\nINSERT INTO \"ef_temp_Attachments\" (\"Id\", \"Blob\", \"CreatedAt\", \"CredentialId\", \"Filename\", \"IsDeleted\", \"UpdatedAt\")\nSELECT \"Id\", \"Blob\", \"CreatedAt\", \"CredentialId\", \"Filename\", \"IsDeleted\", \"UpdatedAt\"\nFROM \"Attachments\";\n\nCOMMIT;\n\nPRAGMA foreign_keys = 0;\n\nBEGIN TRANSACTION;\nDROP TABLE \"Attachments\";\n\nALTER TABLE \"ef_temp_Attachments\" RENAME TO \"Attachments\";\n\nCOMMIT;\n\nPRAGMA foreign_keys = 1;\n\nBEGIN TRANSACTION;\nCREATE INDEX \"IX_Attachments_CredentialId\" ON \"Attachments\" (\"CredentialId\");\n\nCOMMIT;\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240917191243_1.4.1-RenameAttachmentsPlural', '9.0.4');\n\nBEGIN TRANSACTION;\nCREATE TABLE \"TotpCodes\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_TotpCodes\" PRIMARY KEY,\n \"Name\" TEXT NOT NULL,\n \"SecretKey\" TEXT NOT NULL,\n \"CredentialId\" TEXT NOT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL,\n \"IsDeleted\" INTEGER NOT NULL,\n CONSTRAINT \"FK_TotpCodes_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE\n);\n\nCREATE INDEX \"IX_TotpCodes_CredentialId\" ON \"TotpCodes\" (\"CredentialId\");\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20250310131554_1.5.0-AddTotpCodes', '9.0.4');\n\nCOMMIT;\n";+/**+ * Individual migration SQL scripts+ * Auto-generated from EF Core migrations+ */+declare const MIGRATION_SCRIPTS: Record<number, string>;++/**+ * Creates a new VaultSqlGenerator instance.+ * @returns A new VaultSqlGenerator instance.+ */+declare const CreateVaultSqlGenerator: () => VaultSqlGenerator;++export { COMPLETE_SCHEMA_SQL, CreateVaultSqlGenerator, type ISqlGenerationResult, type IVaultVersion, type IVaultVersionInfo, MIGRATION_SCRIPTS, VAULT_VERSIONS, VaultSqlGenerator };diff --git a/apps/server/AliasVault.Client/wwwroot/js/dist/shared/vault-sql/index.d.ts b/apps/server/AliasVault.Client/wwwroot/js/dist/shared/vault-sql/index.d.tsnew file mode 100644index 000000000..637729992--- /dev/null+++ b/apps/server/AliasVault.Client/wwwroot/js/dist/shared/vault-sql/index.d.ts@@ -0,0 +1,126 @@+/**+ * Vault database version information+ */+interface IVaultVersion {+ /**+ * The migration revision number+ */+ revision: number;+ /**+ * The version number (e.g., "1.5.0")+ */+ version: string;+ /**+ * Description of changes in this version+ */+ description: string;+ /**+ * Release date+ */+ releaseDate: string;+}++/**+ * Result of SQL generation operations+ */+interface ISqlGenerationResult {+ success: boolean;+ sqlCommands: string[];+ version: string;+ migrationNumber: number;+ error?: string;+}+/**+ * Information about vault version requirements+ */+interface IVaultVersionInfo {+ currentVersion: string;+ currentMigrationNumber: number;+ targetVersion: string;+ targetMigrationNumber: number;+ needsUpgrade: boolean;+ availableUpgrades: IVaultVersion[];+}+/**+ * Vault SQL generator utility class+ * Provides SQL statements for vault creation and migration without database execution+ */+declare class VaultSqlGenerator {+ /**+ * Get SQL commands to create a new vault with the latest schema+ */+ getCreateVaultSql(): ISqlGenerationResult;+ /**+ * Get SQL commands to upgrade vault from current version to target version+ */+ getUpgradeVaultSql(currentMigrationNumber: number, targetMigrationNumber?: number): ISqlGenerationResult;+ /**+ * Get SQL commands to upgrade vault to latest version+ */+ getUpgradeToLatestSql(currentMigrationNumber: number): ISqlGenerationResult;+ /**+ * Get SQL commands to upgrade vault to a specific version+ */+ getUpgradeToVersionSql(currentMigrationNumber: number, targetVersion: string): ISqlGenerationResult;+ /**+ * Get SQL commands to check current vault version+ */+ getVersionCheckSql(): string[];+ /**+ * Get SQL command to validate vault structure+ */+ getVaultValidationSql(): string;+ /**+ * Parse vault version information from query results+ */+ parseVaultVersionInfo(settingsTableExists: boolean, versionResult?: string, migrationResult?: string): IVaultVersionInfo;+ /**+ * Validate vault structure from table names+ */+ validateVaultStructure(tableNames: string[]): boolean;+ /**+ * Get all available vault versions+ */+ getAvailableVersions(): IVaultVersion[];+ /**+ * Get current/latest vault version info+ */+ getCurrentVersion(): IVaultVersion;+ /**+ * Get specific migration SQL by migration number+ */+ getMigrationSql(migrationNumber: number): string | undefined;+ /**+ * Get complete schema SQL for creating new vault+ */+ getCompleteSchemaeSql(): string;+}++/**+ * Vault version information+ * Auto-generated from EF Core migration filenames+ */++/**+ * Available vault versions in chronological order+ */+declare const VAULT_VERSIONS: IVaultVersion[];++/**+ * Complete database schema SQL (latest version)+ * Auto-generated from EF Core migrations+ */+declare const COMPLETE_SCHEMA_SQL = "\n\uFEFFCREATE TABLE IF NOT EXISTS \"__EFMigrationsHistory\" (\n \"MigrationId\" TEXT NOT NULL CONSTRAINT \"PK___EFMigrationsHistory\" PRIMARY KEY,\n \"ProductVersion\" TEXT NOT NULL\n);\n\nBEGIN TRANSACTION;\nCREATE TABLE \"Aliases\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Aliases\" PRIMARY KEY,\n \"Gender\" VARCHAR NULL,\n \"FirstName\" VARCHAR NULL,\n \"LastName\" VARCHAR NULL,\n \"NickName\" VARCHAR NULL,\n \"BirthDate\" TEXT NOT NULL,\n \"AddressStreet\" VARCHAR NULL,\n \"AddressCity\" VARCHAR NULL,\n \"AddressState\" VARCHAR NULL,\n \"AddressZipCode\" VARCHAR NULL,\n \"AddressCountry\" VARCHAR NULL,\n \"Hobbies\" TEXT NULL,\n \"EmailPrefix\" TEXT NULL,\n \"PhoneMobile\" TEXT NULL,\n \"BankAccountIBAN\" TEXT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL\n);\n\nCREATE TABLE \"Services\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Services\" PRIMARY KEY,\n \"Name\" TEXT NULL,\n \"Url\" TEXT NULL,\n \"Logo\" BLOB NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL\n);\n\nCREATE TABLE \"Credentials\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Credentials\" PRIMARY KEY,\n \"AliasId\" TEXT NOT NULL,\n \"Notes\" TEXT NULL,\n \"Username\" TEXT NOT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL,\n \"ServiceId\" TEXT NOT NULL,\n CONSTRAINT \"FK_Credentials_Aliases_AliasId\" FOREIGN KEY (\"AliasId\") REFERENCES \"Aliases\" (\"Id\") ON DELETE CASCADE,\n CONSTRAINT \"FK_Credentials_Services_ServiceId\" FOREIGN KEY (\"ServiceId\") REFERENCES \"Services\" (\"Id\") ON DELETE CASCADE\n);\n\nCREATE TABLE \"Attachment\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Attachment\" PRIMARY KEY,\n \"Filename\" TEXT NOT NULL,\n \"Blob\" BLOB NOT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL,\n \"CredentialId\" TEXT NOT NULL,\n CONSTRAINT \"FK_Attachment_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE\n);\n\nCREATE TABLE \"Passwords\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Passwords\" PRIMARY KEY,\n \"Value\" TEXT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL,\n \"CredentialId\" TEXT NOT NULL,\n CONSTRAINT \"FK_Passwords_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE\n);\n\nCREATE INDEX \"IX_Attachment_CredentialId\" ON \"Attachment\" (\"CredentialId\");\n\nCREATE INDEX \"IX_Credentials_AliasId\" ON \"Credentials\" (\"AliasId\");\n\nCREATE INDEX \"IX_Credentials_ServiceId\" ON \"Credentials\" (\"ServiceId\");\n\nCREATE INDEX \"IX_Passwords_CredentialId\" ON \"Passwords\" (\"CredentialId\");\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240708094944_1.0.0-InitialMigration', '9.0.4');\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240708224522_1.0.1-EmptyTestMigration', '9.0.4');\n\nALTER TABLE \"Aliases\" RENAME COLUMN \"EmailPrefix\" TO \"Email\";\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240711204207_1.0.2-ChangeEmailColumn', '9.0.4');\n\nCREATE TABLE \"EncryptionKeys\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_EncryptionKeys\" PRIMARY KEY,\n \"PublicKey\" TEXT NOT NULL,\n \"PrivateKey\" TEXT NOT NULL,\n \"IsPrimary\" INTEGER NOT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL\n);\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240729105618_1.1.0-AddPkiTables', '9.0.4');\n\nCREATE TABLE \"Settings\" (\n \"Key\" TEXT NOT NULL CONSTRAINT \"PK_Settings\" PRIMARY KEY,\n \"Value\" TEXT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL\n);\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240805073413_1.2.0-AddSettingsTable', '9.0.4');\n\nCREATE TABLE \"ef_temp_Aliases\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Aliases\" PRIMARY KEY,\n \"BirthDate\" TEXT NOT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"Email\" TEXT NULL,\n \"FirstName\" VARCHAR NULL,\n \"Gender\" VARCHAR NULL,\n \"LastName\" VARCHAR NULL,\n \"NickName\" VARCHAR NULL,\n \"UpdatedAt\" TEXT NOT NULL\n);\n\nINSERT INTO \"ef_temp_Aliases\" (\"Id\", \"BirthDate\", \"CreatedAt\", \"Email\", \"FirstName\", \"Gender\", \"LastName\", \"NickName\", \"UpdatedAt\")\nSELECT \"Id\", \"BirthDate\", \"CreatedAt\", \"Email\", \"FirstName\", \"Gender\", \"LastName\", \"NickName\", \"UpdatedAt\"\nFROM \"Aliases\";\n\nCOMMIT;\n\nPRAGMA foreign_keys = 0;\n\nBEGIN TRANSACTION;\nDROP TABLE \"Aliases\";\n\nALTER TABLE \"ef_temp_Aliases\" RENAME TO \"Aliases\";\n\nCOMMIT;\n\nPRAGMA foreign_keys = 1;\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240805122422_1.3.0-UpdateIdentityStructure', '9.0.4');\n\nBEGIN TRANSACTION;\nCREATE TABLE \"ef_temp_Credentials\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Credentials\" PRIMARY KEY,\n \"AliasId\" TEXT NOT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"Notes\" TEXT NULL,\n \"ServiceId\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL,\n \"Username\" TEXT NULL,\n CONSTRAINT \"FK_Credentials_Aliases_AliasId\" FOREIGN KEY (\"AliasId\") REFERENCES \"Aliases\" (\"Id\") ON DELETE CASCADE,\n CONSTRAINT \"FK_Credentials_Services_ServiceId\" FOREIGN KEY (\"ServiceId\") REFERENCES \"Services\" (\"Id\") ON DELETE CASCADE\n);\n\nINSERT INTO \"ef_temp_Credentials\" (\"Id\", \"AliasId\", \"CreatedAt\", \"Notes\", \"ServiceId\", \"UpdatedAt\", \"Username\")\nSELECT \"Id\", \"AliasId\", \"CreatedAt\", \"Notes\", \"ServiceId\", \"UpdatedAt\", \"Username\"\nFROM \"Credentials\";\n\nCOMMIT;\n\nPRAGMA foreign_keys = 0;\n\nBEGIN TRANSACTION;\nDROP TABLE \"Credentials\";\n\nALTER TABLE \"ef_temp_Credentials\" RENAME TO \"Credentials\";\n\nCOMMIT;\n\nPRAGMA foreign_keys = 1;\n\nBEGIN TRANSACTION;\nCREATE INDEX \"IX_Credentials_AliasId\" ON \"Credentials\" (\"AliasId\");\n\nCREATE INDEX \"IX_Credentials_ServiceId\" ON \"Credentials\" (\"ServiceId\");\n\nCOMMIT;\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240812141727_1.3.1-MakeUsernameOptional', '9.0.4');\n\nBEGIN TRANSACTION;\nALTER TABLE \"Settings\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;\n\nALTER TABLE \"Services\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;\n\nALTER TABLE \"Passwords\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;\n\nALTER TABLE \"EncryptionKeys\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;\n\nALTER TABLE \"Credentials\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;\n\nALTER TABLE \"Attachment\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;\n\nALTER TABLE \"Aliases\" ADD \"IsDeleted\" INTEGER NOT NULL DEFAULT 0;\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240916105320_1.4.0-AddSyncSupport', '9.0.4');\n\nALTER TABLE \"Attachment\" RENAME TO \"Attachments\";\n\nCREATE TABLE \"ef_temp_Attachments\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_Attachments\" PRIMARY KEY,\n \"Blob\" BLOB NOT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"CredentialId\" TEXT NOT NULL,\n \"Filename\" TEXT NOT NULL,\n \"IsDeleted\" INTEGER NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL,\n CONSTRAINT \"FK_Attachments_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE\n);\n\nINSERT INTO \"ef_temp_Attachments\" (\"Id\", \"Blob\", \"CreatedAt\", \"CredentialId\", \"Filename\", \"IsDeleted\", \"UpdatedAt\")\nSELECT \"Id\", \"Blob\", \"CreatedAt\", \"CredentialId\", \"Filename\", \"IsDeleted\", \"UpdatedAt\"\nFROM \"Attachments\";\n\nCOMMIT;\n\nPRAGMA foreign_keys = 0;\n\nBEGIN TRANSACTION;\nDROP TABLE \"Attachments\";\n\nALTER TABLE \"ef_temp_Attachments\" RENAME TO \"Attachments\";\n\nCOMMIT;\n\nPRAGMA foreign_keys = 1;\n\nBEGIN TRANSACTION;\nCREATE INDEX \"IX_Attachments_CredentialId\" ON \"Attachments\" (\"CredentialId\");\n\nCOMMIT;\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20240917191243_1.4.1-RenameAttachmentsPlural', '9.0.4');\n\nBEGIN TRANSACTION;\nCREATE TABLE \"TotpCodes\" (\n \"Id\" TEXT NOT NULL CONSTRAINT \"PK_TotpCodes\" PRIMARY KEY,\n \"Name\" TEXT NOT NULL,\n \"SecretKey\" TEXT NOT NULL,\n \"CredentialId\" TEXT NOT NULL,\n \"CreatedAt\" TEXT NOT NULL,\n \"UpdatedAt\" TEXT NOT NULL,\n \"IsDeleted\" INTEGER NOT NULL,\n CONSTRAINT \"FK_TotpCodes_Credentials_CredentialId\" FOREIGN KEY (\"CredentialId\") REFERENCES \"Credentials\" (\"Id\") ON DELETE CASCADE\n);\n\nCREATE INDEX \"IX_TotpCodes_CredentialId\" ON \"TotpCodes\" (\"CredentialId\");\n\nINSERT INTO \"__EFMigrationsHistory\" (\"MigrationId\", \"ProductVersion\")\nVALUES ('20250310131554_1.5.0-AddTotpCodes', '9.0.4');\n\nCOMMIT;\n";+/**+ * Individual migration SQL scripts+ * Auto-generated from EF Core migrations+ */+declare const MIGRATION_SCRIPTS: Record<number, string>;++/**+ * Creates a new VaultSqlGenerator instance.+ * @returns A new VaultSqlGenerator instance.+ */+declare const CreateVaultSqlGenerator: () => VaultSqlGenerator;++export { COMPLETE_SCHEMA_SQL, CreateVaultSqlGenerator, type ISqlGenerationResult, type IVaultVersion, type IVaultVersionInfo, MIGRATION_SCRIPTS, VAULT_VERSIONS, VaultSqlGenerator };diff --git a/apps/server/AliasVault.Client/wwwroot/js/dist/shared/vault-sql/index.js b/apps/server/AliasVault.Client/wwwroot/js/dist/shared/vault-sql/index.jsnew file mode 100644index 000000000..a40a0100a--- /dev/null+++ b/apps/server/AliasVault.Client/wwwroot/js/dist/shared/vault-sql/index.js@@ -0,0 +1,742 @@+// <auto-generated>+// This file was automatically generated. Do not edit manually.++"use strict";+var __defProp = Object.defineProperty;+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;+var __getOwnPropNames = Object.getOwnPropertyNames;+var __hasOwnProp = Object.prototype.hasOwnProperty;+var __export = (target, all) => {+ for (var name in all)+ __defProp(target, name, { get: all[name], enumerable: true });+};+var __copyProps = (to, from, except, desc) => {+ if (from && typeof from === "object" || typeof from === "function") {+ for (let key of __getOwnPropNames(from))+ if (!__hasOwnProp.call(to, key) && key !== except)+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });+ }+ return to;+};+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);++// src/index.ts+var index_exports = {};+__export(index_exports, {+ COMPLETE_SCHEMA_SQL: () => COMPLETE_SCHEMA_SQL,+ CreateVaultSqlGenerator: () => CreateVaultSqlGenerator,+ MIGRATION_SCRIPTS: () => MIGRATION_SCRIPTS,+ VAULT_VERSIONS: () => VAULT_VERSIONS,+ VaultSqlGenerator: () => VaultSqlGenerator+});+module.exports = __toCommonJS(index_exports);++// src/sql/SqlConstants.ts+var COMPLETE_SCHEMA_SQL = `+\uFEFFCREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" (+ "MigrationId" TEXT NOT NULL CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY,+ "ProductVersion" TEXT NOT NULL+);++BEGIN TRANSACTION;+CREATE TABLE "Aliases" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Aliases" PRIMARY KEY,+ "Gender" VARCHAR NULL,+ "FirstName" VARCHAR NULL,+ "LastName" VARCHAR NULL,+ "NickName" VARCHAR NULL,+ "BirthDate" TEXT NOT NULL,+ "AddressStreet" VARCHAR NULL,+ "AddressCity" VARCHAR NULL,+ "AddressState" VARCHAR NULL,+ "AddressZipCode" VARCHAR NULL,+ "AddressCountry" VARCHAR NULL,+ "Hobbies" TEXT NULL,+ "EmailPrefix" TEXT NULL,+ "PhoneMobile" TEXT NULL,+ "BankAccountIBAN" TEXT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL+);++CREATE TABLE "Services" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Services" PRIMARY KEY,+ "Name" TEXT NULL,+ "Url" TEXT NULL,+ "Logo" BLOB NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL+);++CREATE TABLE "Credentials" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Credentials" PRIMARY KEY,+ "AliasId" TEXT NOT NULL,+ "Notes" TEXT NULL,+ "Username" TEXT NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ "ServiceId" TEXT NOT NULL,+ CONSTRAINT "FK_Credentials_Aliases_AliasId" FOREIGN KEY ("AliasId") REFERENCES "Aliases" ("Id") ON DELETE CASCADE,+ CONSTRAINT "FK_Credentials_Services_ServiceId" FOREIGN KEY ("ServiceId") REFERENCES "Services" ("Id") ON DELETE CASCADE+);++CREATE TABLE "Attachment" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Attachment" PRIMARY KEY,+ "Filename" TEXT NOT NULL,+ "Blob" BLOB NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ "CredentialId" TEXT NOT NULL,+ CONSTRAINT "FK_Attachment_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+);++CREATE TABLE "Passwords" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Passwords" PRIMARY KEY,+ "Value" TEXT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ "CredentialId" TEXT NOT NULL,+ CONSTRAINT "FK_Passwords_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+);++CREATE INDEX "IX_Attachment_CredentialId" ON "Attachment" ("CredentialId");++CREATE INDEX "IX_Credentials_AliasId" ON "Credentials" ("AliasId");++CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");++CREATE INDEX "IX_Passwords_CredentialId" ON "Passwords" ("CredentialId");++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240708094944_1.0.0-InitialMigration', '9.0.4');++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240708224522_1.0.1-EmptyTestMigration', '9.0.4');++ALTER TABLE "Aliases" RENAME COLUMN "EmailPrefix" TO "Email";++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240711204207_1.0.2-ChangeEmailColumn', '9.0.4');++CREATE TABLE "EncryptionKeys" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_EncryptionKeys" PRIMARY KEY,+ "PublicKey" TEXT NOT NULL,+ "PrivateKey" TEXT NOT NULL,+ "IsPrimary" INTEGER NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL+);++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240729105618_1.1.0-AddPkiTables', '9.0.4');++CREATE TABLE "Settings" (+ "Key" TEXT NOT NULL CONSTRAINT "PK_Settings" PRIMARY KEY,+ "Value" TEXT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL+);++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240805073413_1.2.0-AddSettingsTable', '9.0.4');++CREATE TABLE "ef_temp_Aliases" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Aliases" PRIMARY KEY,+ "BirthDate" TEXT NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "Email" TEXT NULL,+ "FirstName" VARCHAR NULL,+ "Gender" VARCHAR NULL,+ "LastName" VARCHAR NULL,+ "NickName" VARCHAR NULL,+ "UpdatedAt" TEXT NOT NULL+);++INSERT INTO "ef_temp_Aliases" ("Id", "BirthDate", "CreatedAt", "Email", "FirstName", "Gender", "LastName", "NickName", "UpdatedAt")+SELECT "Id", "BirthDate", "CreatedAt", "Email", "FirstName", "Gender", "LastName", "NickName", "UpdatedAt"+FROM "Aliases";++COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;+DROP TABLE "Aliases";++ALTER TABLE "ef_temp_Aliases" RENAME TO "Aliases";++COMMIT;++PRAGMA foreign_keys = 1;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240805122422_1.3.0-UpdateIdentityStructure', '9.0.4');++BEGIN TRANSACTION;+CREATE TABLE "ef_temp_Credentials" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Credentials" PRIMARY KEY,+ "AliasId" TEXT NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "Notes" TEXT NULL,+ "ServiceId" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ "Username" TEXT NULL,+ CONSTRAINT "FK_Credentials_Aliases_AliasId" FOREIGN KEY ("AliasId") REFERENCES "Aliases" ("Id") ON DELETE CASCADE,+ CONSTRAINT "FK_Credentials_Services_ServiceId" FOREIGN KEY ("ServiceId") REFERENCES "Services" ("Id") ON DELETE CASCADE+);++INSERT INTO "ef_temp_Credentials" ("Id", "AliasId", "CreatedAt", "Notes", "ServiceId", "UpdatedAt", "Username")+SELECT "Id", "AliasId", "CreatedAt", "Notes", "ServiceId", "UpdatedAt", "Username"+FROM "Credentials";++COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;+DROP TABLE "Credentials";++ALTER TABLE "ef_temp_Credentials" RENAME TO "Credentials";++COMMIT;++PRAGMA foreign_keys = 1;++BEGIN TRANSACTION;+CREATE INDEX "IX_Credentials_AliasId" ON "Credentials" ("AliasId");++CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");++COMMIT;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240812141727_1.3.1-MakeUsernameOptional', '9.0.4');++BEGIN TRANSACTION;+ALTER TABLE "Settings" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Services" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Passwords" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "EncryptionKeys" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Credentials" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Attachment" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Aliases" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240916105320_1.4.0-AddSyncSupport', '9.0.4');++ALTER TABLE "Attachment" RENAME TO "Attachments";++CREATE TABLE "ef_temp_Attachments" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Attachments" PRIMARY KEY,+ "Blob" BLOB NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "CredentialId" TEXT NOT NULL,+ "Filename" TEXT NOT NULL,+ "IsDeleted" INTEGER NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ CONSTRAINT "FK_Attachments_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+);++INSERT INTO "ef_temp_Attachments" ("Id", "Blob", "CreatedAt", "CredentialId", "Filename", "IsDeleted", "UpdatedAt")+SELECT "Id", "Blob", "CreatedAt", "CredentialId", "Filename", "IsDeleted", "UpdatedAt"+FROM "Attachments";++COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;+DROP TABLE "Attachments";++ALTER TABLE "ef_temp_Attachments" RENAME TO "Attachments";++COMMIT;++PRAGMA foreign_keys = 1;++BEGIN TRANSACTION;+CREATE INDEX "IX_Attachments_CredentialId" ON "Attachments" ("CredentialId");++COMMIT;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240917191243_1.4.1-RenameAttachmentsPlural', '9.0.4');++BEGIN TRANSACTION;+CREATE TABLE "TotpCodes" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_TotpCodes" PRIMARY KEY,+ "Name" TEXT NOT NULL,+ "SecretKey" TEXT NOT NULL,+ "CredentialId" TEXT NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ "IsDeleted" INTEGER NOT NULL,+ CONSTRAINT "FK_TotpCodes_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+);++CREATE INDEX "IX_TotpCodes_CredentialId" ON "TotpCodes" ("CredentialId");++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20250310131554_1.5.0-AddTotpCodes', '9.0.4');++COMMIT;+`;+var MIGRATION_SCRIPTS = {+ 1: `\uFEFFBEGIN TRANSACTION;+INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240708224522_1.0.1-EmptyTestMigration', '9.0.4');++COMMIT;`,+ 2: `\uFEFFBEGIN TRANSACTION;+ALTER TABLE "Aliases" RENAME COLUMN "EmailPrefix" TO "Email";++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240711204207_1.0.2-ChangeEmailColumn', '9.0.4');++COMMIT;`,+ 3: `\uFEFFBEGIN TRANSACTION;+CREATE TABLE "EncryptionKeys" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_EncryptionKeys" PRIMARY KEY,+ "PublicKey" TEXT NOT NULL,+ "PrivateKey" TEXT NOT NULL,+ "IsPrimary" INTEGER NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL+);++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240729105618_1.1.0-AddPkiTables', '9.0.4');++COMMIT;`,+ 4: `\uFEFFBEGIN TRANSACTION;+CREATE TABLE "Settings" (+ "Key" TEXT NOT NULL CONSTRAINT "PK_Settings" PRIMARY KEY,+ "Value" TEXT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL+);++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240805073413_1.2.0-AddSettingsTable', '9.0.4');++COMMIT;`,+ 5: `\uFEFFBEGIN TRANSACTION;+CREATE TABLE "ef_temp_Aliases" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Aliases" PRIMARY KEY,+ "BirthDate" TEXT NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "Email" TEXT NULL,+ "FirstName" VARCHAR NULL,+ "Gender" VARCHAR NULL,+ "LastName" VARCHAR NULL,+ "NickName" VARCHAR NULL,+ "UpdatedAt" TEXT NOT NULL+);++INSERT INTO "ef_temp_Aliases" ("Id", "BirthDate", "CreatedAt", "Email", "FirstName", "Gender", "LastName", "NickName", "UpdatedAt")+SELECT "Id", "BirthDate", "CreatedAt", "Email", "FirstName", "Gender", "LastName", "NickName", "UpdatedAt"+FROM "Aliases";++COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;+DROP TABLE "Aliases";++ALTER TABLE "ef_temp_Aliases" RENAME TO "Aliases";++COMMIT;++PRAGMA foreign_keys = 1;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240805122422_1.3.0-UpdateIdentityStructure', '9.0.4');`,+ 6: `\uFEFFBEGIN TRANSACTION;+CREATE TABLE "ef_temp_Credentials" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Credentials" PRIMARY KEY,+ "AliasId" TEXT NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "Notes" TEXT NULL,+ "ServiceId" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ "Username" TEXT NULL,+ CONSTRAINT "FK_Credentials_Aliases_AliasId" FOREIGN KEY ("AliasId") REFERENCES "Aliases" ("Id") ON DELETE CASCADE,+ CONSTRAINT "FK_Credentials_Services_ServiceId" FOREIGN KEY ("ServiceId") REFERENCES "Services" ("Id") ON DELETE CASCADE+);++INSERT INTO "ef_temp_Credentials" ("Id", "AliasId", "CreatedAt", "Notes", "ServiceId", "UpdatedAt", "Username")+SELECT "Id", "AliasId", "CreatedAt", "Notes", "ServiceId", "UpdatedAt", "Username"+FROM "Credentials";++COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;+DROP TABLE "Credentials";++ALTER TABLE "ef_temp_Credentials" RENAME TO "Credentials";++COMMIT;++PRAGMA foreign_keys = 1;++BEGIN TRANSACTION;+CREATE INDEX "IX_Credentials_AliasId" ON "Credentials" ("AliasId");++CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");++COMMIT;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240812141727_1.3.1-MakeUsernameOptional', '9.0.4');`,+ 7: `\uFEFFBEGIN TRANSACTION;+ALTER TABLE "Settings" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Services" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Passwords" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "EncryptionKeys" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Credentials" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Attachment" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Aliases" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240916105320_1.4.0-AddSyncSupport', '9.0.4');++COMMIT;`,+ 8: `\uFEFFBEGIN TRANSACTION;+ALTER TABLE "Attachment" RENAME TO "Attachments";++CREATE TABLE "ef_temp_Attachments" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Attachments" PRIMARY KEY,+ "Blob" BLOB NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "CredentialId" TEXT NOT NULL,+ "Filename" TEXT NOT NULL,+ "IsDeleted" INTEGER NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ CONSTRAINT "FK_Attachments_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+);++INSERT INTO "ef_temp_Attachments" ("Id", "Blob", "CreatedAt", "CredentialId", "Filename", "IsDeleted", "UpdatedAt")+SELECT "Id", "Blob", "CreatedAt", "CredentialId", "Filename", "IsDeleted", "UpdatedAt"+FROM "Attachments";++COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;+DROP TABLE "Attachments";++ALTER TABLE "ef_temp_Attachments" RENAME TO "Attachments";++COMMIT;++PRAGMA foreign_keys = 1;++BEGIN TRANSACTION;+CREATE INDEX "IX_Attachments_CredentialId" ON "Attachments" ("CredentialId");++COMMIT;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240917191243_1.4.1-RenameAttachmentsPlural', '9.0.4');`,+ 9: `\uFEFFBEGIN TRANSACTION;+CREATE TABLE "TotpCodes" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_TotpCodes" PRIMARY KEY,+ "Name" TEXT NOT NULL,+ "SecretKey" TEXT NOT NULL,+ "CredentialId" TEXT NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ "IsDeleted" INTEGER NOT NULL,+ CONSTRAINT "FK_TotpCodes_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+);++CREATE INDEX "IX_TotpCodes_CredentialId" ON "TotpCodes" ("CredentialId");++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20250310131554_1.5.0-AddTotpCodes', '9.0.4');++COMMIT;`+};++// src/sql/VaultVersions.ts+var VAULT_VERSIONS = [+ {+ revision: 1,+ version: "1.0.1",+ description: "Empty Test Migration",+ releaseDate: "2024-07-08"+ },+ {+ revision: 2,+ version: "1.0.2",+ description: "Change Email Column",+ releaseDate: "2024-07-11"+ },+ {+ revision: 3,+ version: "1.1.0",+ description: "Add Pki Tables",+ releaseDate: "2024-07-29"+ },+ {+ revision: 4,+ version: "1.2.0",+ description: "Add Settings Table",+ releaseDate: "2024-08-05"+ },+ {+ revision: 5,+ version: "1.3.0",+ description: "Update Identity Structure",+ releaseDate: "2024-08-05"+ },+ {+ revision: 6,+ version: "1.3.1",+ description: "Make Username Optional",+ releaseDate: "2024-08-12"+ },+ {+ revision: 7,+ version: "1.4.0",+ description: "Add Sync Support",+ releaseDate: "2024-09-16"+ },+ {+ revision: 8,+ version: "1.4.1",+ description: "Rename Attachments Plural",+ releaseDate: "2024-09-17"+ },+ {+ revision: 9,+ version: "1.5.0",+ description: "Add Totp Codes",+ releaseDate: "2025-03-10"+ }+];++// src/sql/VaultSqlGenerator.ts+var VaultSqlGenerator = class {+ /**+ * Get SQL commands to create a new vault with the latest schema+ */+ getCreateVaultSql() {+ try {+ const sqlCommands = [+ "PRAGMA foreign_keys = ON;",+ COMPLETE_SCHEMA_SQL,+ // Insert version tracking+ `INSERT INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")+ VALUES ('vault_version', '${VAULT_VERSIONS[VAULT_VERSIONS.length - 1].version}', datetime('now'), datetime('now'), 0);`,+ `INSERT INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")+ VALUES ('vault_migration_number', '${VAULT_VERSIONS[VAULT_VERSIONS.length - 1].revision}', datetime('now'), datetime('now'), 0);`+ ];+ return {+ success: true,+ sqlCommands,+ version: VAULT_VERSIONS[VAULT_VERSIONS.length - 1].version,+ migrationNumber: VAULT_VERSIONS[VAULT_VERSIONS.length - 1].revision+ };+ } catch (error) {+ return {+ success: false,+ sqlCommands: [],+ version: "0.0.0",+ migrationNumber: 0,+ error: error instanceof Error ? error.message : "Unknown error creating vault SQL"+ };+ }+ }+ /**+ * Get SQL commands to upgrade vault from current version to target version+ */+ getUpgradeVaultSql(currentMigrationNumber, targetMigrationNumber) {+ try {+ const targetMigration = targetMigrationNumber ?? VAULT_VERSIONS[VAULT_VERSIONS.length - 1].revision;+ const targetVersionInfo = VAULT_VERSIONS.find((v) => v.revision === targetMigration);+ if (!targetVersionInfo) {+ return {+ success: false,+ sqlCommands: [],+ version: "0.0.0",+ migrationNumber: 0,+ error: `Target migration number ${targetMigration} not found`+ };+ }+ if (currentMigrationNumber >= targetMigration) {+ return {+ success: true,+ sqlCommands: [],+ version: targetVersionInfo.version,+ migrationNumber: targetMigration+ };+ }+ const migrationsToApply = VAULT_VERSIONS.filter(+ (v) => v.revision > currentMigrationNumber && v.revision <= targetMigration+ );+ const sqlCommands = ["PRAGMA foreign_keys = ON;"];+ for (const migration of migrationsToApply) {+ const migrationSql = MIGRATION_SCRIPTS[migration.revision];+ if (migrationSql) {+ sqlCommands.push(migrationSql);+ }+ }+ sqlCommands.push(+ `INSERT OR REPLACE INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")+ VALUES ('vault_version', '${targetVersionInfo.version}', datetime('now'), datetime('now'), 0);`+ );+ sqlCommands.push(+ `INSERT OR REPLACE INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")+ VALUES ('vault_migration_number', '${targetMigration}', datetime('now'), datetime('now'), 0);`+ );+ return {+ success: true,+ sqlCommands,+ version: targetVersionInfo.version,+ migrationNumber: targetMigration+ };+ } catch (error) {+ return {+ success: false,+ sqlCommands: [],+ version: "0.0.0",+ migrationNumber: 0,+ error: error instanceof Error ? error.message : "Unknown error generating upgrade SQL"+ };+ }+ }+ /**+ * Get SQL commands to upgrade vault to latest version+ */+ getUpgradeToLatestSql(currentMigrationNumber) {+ return this.getUpgradeVaultSql(currentMigrationNumber);+ }+ /**+ * Get SQL commands to upgrade vault to a specific version+ */+ getUpgradeToVersionSql(currentMigrationNumber, targetVersion) {+ const targetVersionInfo = VAULT_VERSIONS.find((v) => v.version === targetVersion);+ if (!targetVersionInfo) {+ return {+ success: false,+ sqlCommands: [],+ version: "0.0.0",+ migrationNumber: 0,+ error: `Target version ${targetVersion} not found`+ };+ }+ return this.getUpgradeVaultSql(currentMigrationNumber, targetVersionInfo.revision);+ }+ /**+ * Get SQL commands to check current vault version+ */+ getVersionCheckSql() {+ return [+ // Check if Settings table exists+ "SELECT name FROM sqlite_master WHERE type='table' AND name='Settings';",+ // Get vault version+ "SELECT Value FROM Settings WHERE Key = 'vault_version' AND IsDeleted = 0 LIMIT 1;",+ // Get migration number+ "SELECT Value FROM Settings WHERE Key = 'vault_migration_number' AND IsDeleted = 0 LIMIT 1;"+ ];+ }+ /**+ * Get SQL command to validate vault structure+ */+ getVaultValidationSql() {+ return `SELECT name FROM sqlite_master WHERE type='table' AND name IN+ ('Aliases', 'Services', 'Credentials', 'Passwords', 'Attachments', 'EncryptionKeys', 'Settings', 'TotpCodes');`;+ }+ /**+ * Parse vault version information from query results+ */+ parseVaultVersionInfo(settingsTableExists, versionResult, migrationResult) {+ let currentVersion = "0.0.0";+ let currentMigrationNumber = 0;+ if (settingsTableExists) {+ if (versionResult) {+ currentVersion = versionResult;+ } else {+ currentVersion = "1.0.0";+ currentMigrationNumber = 1;+ }+ if (migrationResult) {+ currentMigrationNumber = parseInt(migrationResult, 10);+ }+ }+ const latestVersion = VAULT_VERSIONS[VAULT_VERSIONS.length - 1];+ const needsUpgrade = currentMigrationNumber < latestVersion.revision;+ const availableUpgrades = VAULT_VERSIONS.filter((v) => v.revision > currentMigrationNumber);+ return {+ currentVersion,+ currentMigrationNumber,+ targetVersion: latestVersion.version,+ targetMigrationNumber: latestVersion.revision,+ needsUpgrade,+ availableUpgrades+ };+ }+ /**+ * Validate vault structure from table names+ */+ validateVaultStructure(tableNames) {+ const requiredTables = ["Aliases", "Services", "Credentials", "Passwords", "Attachments", "EncryptionKeys", "Settings", "TotpCodes"];+ const foundTables = tableNames.filter((name) => requiredTables.includes(name));+ return foundTables.length >= 5;+ }+ /**+ * Get all available vault versions+ */+ getAvailableVersions() {+ return [...VAULT_VERSIONS];+ }+ /**+ * Get current/latest vault version info+ */+ getCurrentVersion() {+ return VAULT_VERSIONS[VAULT_VERSIONS.length - 1];+ }+ /**+ * Get specific migration SQL by migration number+ */+ getMigrationSql(migrationNumber) {+ return MIGRATION_SCRIPTS[migrationNumber];+ }+ /**+ * Get complete schema SQL for creating new vault+ */+ getCompleteSchemaeSql() {+ return COMPLETE_SCHEMA_SQL;+ }+};++// src/factories/VaultSqlGeneratorFactory.ts+var CreateVaultSqlGenerator = () => {+ return new VaultSqlGenerator();+};+// Annotate the CommonJS export names for ESM import in node:+0 && (module.exports = {+ COMPLETE_SCHEMA_SQL,+ CreateVaultSqlGenerator,+ MIGRATION_SCRIPTS,+ VAULT_VERSIONS,+ VaultSqlGenerator+});+//# sourceMappingURL=index.js.map\ No newline at end of filediff --git a/apps/server/AliasVault.Client/wwwroot/js/dist/shared/vault-sql/index.mjs b/apps/server/AliasVault.Client/wwwroot/js/dist/shared/vault-sql/index.mjsnew file mode 100644index 000000000..eba8ac27a--- /dev/null+++ b/apps/server/AliasVault.Client/wwwroot/js/dist/shared/vault-sql/index.mjs@@ -0,0 +1,712 @@+// <auto-generated>+// This file was automatically generated. Do not edit manually.+++// src/sql/SqlConstants.ts+var COMPLETE_SCHEMA_SQL = `+\uFEFFCREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" (+ "MigrationId" TEXT NOT NULL CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY,+ "ProductVersion" TEXT NOT NULL+);++BEGIN TRANSACTION;+CREATE TABLE "Aliases" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Aliases" PRIMARY KEY,+ "Gender" VARCHAR NULL,+ "FirstName" VARCHAR NULL,+ "LastName" VARCHAR NULL,+ "NickName" VARCHAR NULL,+ "BirthDate" TEXT NOT NULL,+ "AddressStreet" VARCHAR NULL,+ "AddressCity" VARCHAR NULL,+ "AddressState" VARCHAR NULL,+ "AddressZipCode" VARCHAR NULL,+ "AddressCountry" VARCHAR NULL,+ "Hobbies" TEXT NULL,+ "EmailPrefix" TEXT NULL,+ "PhoneMobile" TEXT NULL,+ "BankAccountIBAN" TEXT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL+);++CREATE TABLE "Services" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Services" PRIMARY KEY,+ "Name" TEXT NULL,+ "Url" TEXT NULL,+ "Logo" BLOB NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL+);++CREATE TABLE "Credentials" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Credentials" PRIMARY KEY,+ "AliasId" TEXT NOT NULL,+ "Notes" TEXT NULL,+ "Username" TEXT NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ "ServiceId" TEXT NOT NULL,+ CONSTRAINT "FK_Credentials_Aliases_AliasId" FOREIGN KEY ("AliasId") REFERENCES "Aliases" ("Id") ON DELETE CASCADE,+ CONSTRAINT "FK_Credentials_Services_ServiceId" FOREIGN KEY ("ServiceId") REFERENCES "Services" ("Id") ON DELETE CASCADE+);++CREATE TABLE "Attachment" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Attachment" PRIMARY KEY,+ "Filename" TEXT NOT NULL,+ "Blob" BLOB NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ "CredentialId" TEXT NOT NULL,+ CONSTRAINT "FK_Attachment_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+);++CREATE TABLE "Passwords" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Passwords" PRIMARY KEY,+ "Value" TEXT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ "CredentialId" TEXT NOT NULL,+ CONSTRAINT "FK_Passwords_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+);++CREATE INDEX "IX_Attachment_CredentialId" ON "Attachment" ("CredentialId");++CREATE INDEX "IX_Credentials_AliasId" ON "Credentials" ("AliasId");++CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");++CREATE INDEX "IX_Passwords_CredentialId" ON "Passwords" ("CredentialId");++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240708094944_1.0.0-InitialMigration', '9.0.4');++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240708224522_1.0.1-EmptyTestMigration', '9.0.4');++ALTER TABLE "Aliases" RENAME COLUMN "EmailPrefix" TO "Email";++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240711204207_1.0.2-ChangeEmailColumn', '9.0.4');++CREATE TABLE "EncryptionKeys" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_EncryptionKeys" PRIMARY KEY,+ "PublicKey" TEXT NOT NULL,+ "PrivateKey" TEXT NOT NULL,+ "IsPrimary" INTEGER NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL+);++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240729105618_1.1.0-AddPkiTables', '9.0.4');++CREATE TABLE "Settings" (+ "Key" TEXT NOT NULL CONSTRAINT "PK_Settings" PRIMARY KEY,+ "Value" TEXT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL+);++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240805073413_1.2.0-AddSettingsTable', '9.0.4');++CREATE TABLE "ef_temp_Aliases" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Aliases" PRIMARY KEY,+ "BirthDate" TEXT NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "Email" TEXT NULL,+ "FirstName" VARCHAR NULL,+ "Gender" VARCHAR NULL,+ "LastName" VARCHAR NULL,+ "NickName" VARCHAR NULL,+ "UpdatedAt" TEXT NOT NULL+);++INSERT INTO "ef_temp_Aliases" ("Id", "BirthDate", "CreatedAt", "Email", "FirstName", "Gender", "LastName", "NickName", "UpdatedAt")+SELECT "Id", "BirthDate", "CreatedAt", "Email", "FirstName", "Gender", "LastName", "NickName", "UpdatedAt"+FROM "Aliases";++COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;+DROP TABLE "Aliases";++ALTER TABLE "ef_temp_Aliases" RENAME TO "Aliases";++COMMIT;++PRAGMA foreign_keys = 1;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240805122422_1.3.0-UpdateIdentityStructure', '9.0.4');++BEGIN TRANSACTION;+CREATE TABLE "ef_temp_Credentials" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Credentials" PRIMARY KEY,+ "AliasId" TEXT NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "Notes" TEXT NULL,+ "ServiceId" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ "Username" TEXT NULL,+ CONSTRAINT "FK_Credentials_Aliases_AliasId" FOREIGN KEY ("AliasId") REFERENCES "Aliases" ("Id") ON DELETE CASCADE,+ CONSTRAINT "FK_Credentials_Services_ServiceId" FOREIGN KEY ("ServiceId") REFERENCES "Services" ("Id") ON DELETE CASCADE+);++INSERT INTO "ef_temp_Credentials" ("Id", "AliasId", "CreatedAt", "Notes", "ServiceId", "UpdatedAt", "Username")+SELECT "Id", "AliasId", "CreatedAt", "Notes", "ServiceId", "UpdatedAt", "Username"+FROM "Credentials";++COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;+DROP TABLE "Credentials";++ALTER TABLE "ef_temp_Credentials" RENAME TO "Credentials";++COMMIT;++PRAGMA foreign_keys = 1;++BEGIN TRANSACTION;+CREATE INDEX "IX_Credentials_AliasId" ON "Credentials" ("AliasId");++CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");++COMMIT;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240812141727_1.3.1-MakeUsernameOptional', '9.0.4');++BEGIN TRANSACTION;+ALTER TABLE "Settings" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Services" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Passwords" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "EncryptionKeys" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Credentials" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Attachment" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Aliases" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240916105320_1.4.0-AddSyncSupport', '9.0.4');++ALTER TABLE "Attachment" RENAME TO "Attachments";++CREATE TABLE "ef_temp_Attachments" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Attachments" PRIMARY KEY,+ "Blob" BLOB NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "CredentialId" TEXT NOT NULL,+ "Filename" TEXT NOT NULL,+ "IsDeleted" INTEGER NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ CONSTRAINT "FK_Attachments_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+);++INSERT INTO "ef_temp_Attachments" ("Id", "Blob", "CreatedAt", "CredentialId", "Filename", "IsDeleted", "UpdatedAt")+SELECT "Id", "Blob", "CreatedAt", "CredentialId", "Filename", "IsDeleted", "UpdatedAt"+FROM "Attachments";++COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;+DROP TABLE "Attachments";++ALTER TABLE "ef_temp_Attachments" RENAME TO "Attachments";++COMMIT;++PRAGMA foreign_keys = 1;++BEGIN TRANSACTION;+CREATE INDEX "IX_Attachments_CredentialId" ON "Attachments" ("CredentialId");++COMMIT;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240917191243_1.4.1-RenameAttachmentsPlural', '9.0.4');++BEGIN TRANSACTION;+CREATE TABLE "TotpCodes" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_TotpCodes" PRIMARY KEY,+ "Name" TEXT NOT NULL,+ "SecretKey" TEXT NOT NULL,+ "CredentialId" TEXT NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ "IsDeleted" INTEGER NOT NULL,+ CONSTRAINT "FK_TotpCodes_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+);++CREATE INDEX "IX_TotpCodes_CredentialId" ON "TotpCodes" ("CredentialId");++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20250310131554_1.5.0-AddTotpCodes', '9.0.4');++COMMIT;+`;+var MIGRATION_SCRIPTS = {+ 1: `\uFEFFBEGIN TRANSACTION;+INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240708224522_1.0.1-EmptyTestMigration', '9.0.4');++COMMIT;`,+ 2: `\uFEFFBEGIN TRANSACTION;+ALTER TABLE "Aliases" RENAME COLUMN "EmailPrefix" TO "Email";++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240711204207_1.0.2-ChangeEmailColumn', '9.0.4');++COMMIT;`,+ 3: `\uFEFFBEGIN TRANSACTION;+CREATE TABLE "EncryptionKeys" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_EncryptionKeys" PRIMARY KEY,+ "PublicKey" TEXT NOT NULL,+ "PrivateKey" TEXT NOT NULL,+ "IsPrimary" INTEGER NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL+);++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240729105618_1.1.0-AddPkiTables', '9.0.4');++COMMIT;`,+ 4: `\uFEFFBEGIN TRANSACTION;+CREATE TABLE "Settings" (+ "Key" TEXT NOT NULL CONSTRAINT "PK_Settings" PRIMARY KEY,+ "Value" TEXT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL+);++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240805073413_1.2.0-AddSettingsTable', '9.0.4');++COMMIT;`,+ 5: `\uFEFFBEGIN TRANSACTION;+CREATE TABLE "ef_temp_Aliases" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Aliases" PRIMARY KEY,+ "BirthDate" TEXT NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "Email" TEXT NULL,+ "FirstName" VARCHAR NULL,+ "Gender" VARCHAR NULL,+ "LastName" VARCHAR NULL,+ "NickName" VARCHAR NULL,+ "UpdatedAt" TEXT NOT NULL+);++INSERT INTO "ef_temp_Aliases" ("Id", "BirthDate", "CreatedAt", "Email", "FirstName", "Gender", "LastName", "NickName", "UpdatedAt")+SELECT "Id", "BirthDate", "CreatedAt", "Email", "FirstName", "Gender", "LastName", "NickName", "UpdatedAt"+FROM "Aliases";++COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;+DROP TABLE "Aliases";++ALTER TABLE "ef_temp_Aliases" RENAME TO "Aliases";++COMMIT;++PRAGMA foreign_keys = 1;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240805122422_1.3.0-UpdateIdentityStructure', '9.0.4');`,+ 6: `\uFEFFBEGIN TRANSACTION;+CREATE TABLE "ef_temp_Credentials" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Credentials" PRIMARY KEY,+ "AliasId" TEXT NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "Notes" TEXT NULL,+ "ServiceId" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ "Username" TEXT NULL,+ CONSTRAINT "FK_Credentials_Aliases_AliasId" FOREIGN KEY ("AliasId") REFERENCES "Aliases" ("Id") ON DELETE CASCADE,+ CONSTRAINT "FK_Credentials_Services_ServiceId" FOREIGN KEY ("ServiceId") REFERENCES "Services" ("Id") ON DELETE CASCADE+);++INSERT INTO "ef_temp_Credentials" ("Id", "AliasId", "CreatedAt", "Notes", "ServiceId", "UpdatedAt", "Username")+SELECT "Id", "AliasId", "CreatedAt", "Notes", "ServiceId", "UpdatedAt", "Username"+FROM "Credentials";++COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;+DROP TABLE "Credentials";++ALTER TABLE "ef_temp_Credentials" RENAME TO "Credentials";++COMMIT;++PRAGMA foreign_keys = 1;++BEGIN TRANSACTION;+CREATE INDEX "IX_Credentials_AliasId" ON "Credentials" ("AliasId");++CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");++COMMIT;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240812141727_1.3.1-MakeUsernameOptional', '9.0.4');`,+ 7: `\uFEFFBEGIN TRANSACTION;+ALTER TABLE "Settings" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Services" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Passwords" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "EncryptionKeys" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Credentials" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Attachment" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Aliases" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240916105320_1.4.0-AddSyncSupport', '9.0.4');++COMMIT;`,+ 8: `\uFEFFBEGIN TRANSACTION;+ALTER TABLE "Attachment" RENAME TO "Attachments";++CREATE TABLE "ef_temp_Attachments" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Attachments" PRIMARY KEY,+ "Blob" BLOB NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "CredentialId" TEXT NOT NULL,+ "Filename" TEXT NOT NULL,+ "IsDeleted" INTEGER NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ CONSTRAINT "FK_Attachments_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+);++INSERT INTO "ef_temp_Attachments" ("Id", "Blob", "CreatedAt", "CredentialId", "Filename", "IsDeleted", "UpdatedAt")+SELECT "Id", "Blob", "CreatedAt", "CredentialId", "Filename", "IsDeleted", "UpdatedAt"+FROM "Attachments";++COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;+DROP TABLE "Attachments";++ALTER TABLE "ef_temp_Attachments" RENAME TO "Attachments";++COMMIT;++PRAGMA foreign_keys = 1;++BEGIN TRANSACTION;+CREATE INDEX "IX_Attachments_CredentialId" ON "Attachments" ("CredentialId");++COMMIT;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240917191243_1.4.1-RenameAttachmentsPlural', '9.0.4');`,+ 9: `\uFEFFBEGIN TRANSACTION;+CREATE TABLE "TotpCodes" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_TotpCodes" PRIMARY KEY,+ "Name" TEXT NOT NULL,+ "SecretKey" TEXT NOT NULL,+ "CredentialId" TEXT NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ "IsDeleted" INTEGER NOT NULL,+ CONSTRAINT "FK_TotpCodes_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+);++CREATE INDEX "IX_TotpCodes_CredentialId" ON "TotpCodes" ("CredentialId");++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20250310131554_1.5.0-AddTotpCodes', '9.0.4');++COMMIT;`+};++// src/sql/VaultVersions.ts+var VAULT_VERSIONS = [+ {+ revision: 1,+ version: "1.0.1",+ description: "Empty Test Migration",+ releaseDate: "2024-07-08"+ },+ {+ revision: 2,+ version: "1.0.2",+ description: "Change Email Column",+ releaseDate: "2024-07-11"+ },+ {+ revision: 3,+ version: "1.1.0",+ description: "Add Pki Tables",+ releaseDate: "2024-07-29"+ },+ {+ revision: 4,+ version: "1.2.0",+ description: "Add Settings Table",+ releaseDate: "2024-08-05"+ },+ {+ revision: 5,+ version: "1.3.0",+ description: "Update Identity Structure",+ releaseDate: "2024-08-05"+ },+ {+ revision: 6,+ version: "1.3.1",+ description: "Make Username Optional",+ releaseDate: "2024-08-12"+ },+ {+ revision: 7,+ version: "1.4.0",+ description: "Add Sync Support",+ releaseDate: "2024-09-16"+ },+ {+ revision: 8,+ version: "1.4.1",+ description: "Rename Attachments Plural",+ releaseDate: "2024-09-17"+ },+ {+ revision: 9,+ version: "1.5.0",+ description: "Add Totp Codes",+ releaseDate: "2025-03-10"+ }+];++// src/sql/VaultSqlGenerator.ts+var VaultSqlGenerator = class {+ /**+ * Get SQL commands to create a new vault with the latest schema+ */+ getCreateVaultSql() {+ try {+ const sqlCommands = [+ "PRAGMA foreign_keys = ON;",+ COMPLETE_SCHEMA_SQL,+ // Insert version tracking+ `INSERT INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")+ VALUES ('vault_version', '${VAULT_VERSIONS[VAULT_VERSIONS.length - 1].version}', datetime('now'), datetime('now'), 0);`,+ `INSERT INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")+ VALUES ('vault_migration_number', '${VAULT_VERSIONS[VAULT_VERSIONS.length - 1].revision}', datetime('now'), datetime('now'), 0);`+ ];+ return {+ success: true,+ sqlCommands,+ version: VAULT_VERSIONS[VAULT_VERSIONS.length - 1].version,+ migrationNumber: VAULT_VERSIONS[VAULT_VERSIONS.length - 1].revision+ };+ } catch (error) {+ return {+ success: false,+ sqlCommands: [],+ version: "0.0.0",+ migrationNumber: 0,+ error: error instanceof Error ? error.message : "Unknown error creating vault SQL"+ };+ }+ }+ /**+ * Get SQL commands to upgrade vault from current version to target version+ */+ getUpgradeVaultSql(currentMigrationNumber, targetMigrationNumber) {+ try {+ const targetMigration = targetMigrationNumber ?? VAULT_VERSIONS[VAULT_VERSIONS.length - 1].revision;+ const targetVersionInfo = VAULT_VERSIONS.find((v) => v.revision === targetMigration);+ if (!targetVersionInfo) {+ return {+ success: false,+ sqlCommands: [],+ version: "0.0.0",+ migrationNumber: 0,+ error: `Target migration number ${targetMigration} not found`+ };+ }+ if (currentMigrationNumber >= targetMigration) {+ return {+ success: true,+ sqlCommands: [],+ version: targetVersionInfo.version,+ migrationNumber: targetMigration+ };+ }+ const migrationsToApply = VAULT_VERSIONS.filter(+ (v) => v.revision > currentMigrationNumber && v.revision <= targetMigration+ );+ const sqlCommands = ["PRAGMA foreign_keys = ON;"];+ for (const migration of migrationsToApply) {+ const migrationSql = MIGRATION_SCRIPTS[migration.revision];+ if (migrationSql) {+ sqlCommands.push(migrationSql);+ }+ }+ sqlCommands.push(+ `INSERT OR REPLACE INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")+ VALUES ('vault_version', '${targetVersionInfo.version}', datetime('now'), datetime('now'), 0);`+ );+ sqlCommands.push(+ `INSERT OR REPLACE INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")+ VALUES ('vault_migration_number', '${targetMigration}', datetime('now'), datetime('now'), 0);`+ );+ return {+ success: true,+ sqlCommands,+ version: targetVersionInfo.version,+ migrationNumber: targetMigration+ };+ } catch (error) {+ return {+ success: false,+ sqlCommands: [],+ version: "0.0.0",+ migrationNumber: 0,+ error: error instanceof Error ? error.message : "Unknown error generating upgrade SQL"+ };+ }+ }+ /**+ * Get SQL commands to upgrade vault to latest version+ */+ getUpgradeToLatestSql(currentMigrationNumber) {+ return this.getUpgradeVaultSql(currentMigrationNumber);+ }+ /**+ * Get SQL commands to upgrade vault to a specific version+ */+ getUpgradeToVersionSql(currentMigrationNumber, targetVersion) {+ const targetVersionInfo = VAULT_VERSIONS.find((v) => v.version === targetVersion);+ if (!targetVersionInfo) {+ return {+ success: false,+ sqlCommands: [],+ version: "0.0.0",+ migrationNumber: 0,+ error: `Target version ${targetVersion} not found`+ };+ }+ return this.getUpgradeVaultSql(currentMigrationNumber, targetVersionInfo.revision);+ }+ /**+ * Get SQL commands to check current vault version+ */+ getVersionCheckSql() {+ return [+ // Check if Settings table exists+ "SELECT name FROM sqlite_master WHERE type='table' AND name='Settings';",+ // Get vault version+ "SELECT Value FROM Settings WHERE Key = 'vault_version' AND IsDeleted = 0 LIMIT 1;",+ // Get migration number+ "SELECT Value FROM Settings WHERE Key = 'vault_migration_number' AND IsDeleted = 0 LIMIT 1;"+ ];+ }+ /**+ * Get SQL command to validate vault structure+ */+ getVaultValidationSql() {+ return `SELECT name FROM sqlite_master WHERE type='table' AND name IN+ ('Aliases', 'Services', 'Credentials', 'Passwords', 'Attachments', 'EncryptionKeys', 'Settings', 'TotpCodes');`;+ }+ /**+ * Parse vault version information from query results+ */+ parseVaultVersionInfo(settingsTableExists, versionResult, migrationResult) {+ let currentVersion = "0.0.0";+ let currentMigrationNumber = 0;+ if (settingsTableExists) {+ if (versionResult) {+ currentVersion = versionResult;+ } else {+ currentVersion = "1.0.0";+ currentMigrationNumber = 1;+ }+ if (migrationResult) {+ currentMigrationNumber = parseInt(migrationResult, 10);+ }+ }+ const latestVersion = VAULT_VERSIONS[VAULT_VERSIONS.length - 1];+ const needsUpgrade = currentMigrationNumber < latestVersion.revision;+ const availableUpgrades = VAULT_VERSIONS.filter((v) => v.revision > currentMigrationNumber);+ return {+ currentVersion,+ currentMigrationNumber,+ targetVersion: latestVersion.version,+ targetMigrationNumber: latestVersion.revision,+ needsUpgrade,+ availableUpgrades+ };+ }+ /**+ * Validate vault structure from table names+ */+ validateVaultStructure(tableNames) {+ const requiredTables = ["Aliases", "Services", "Credentials", "Passwords", "Attachments", "EncryptionKeys", "Settings", "TotpCodes"];+ const foundTables = tableNames.filter((name) => requiredTables.includes(name));+ return foundTables.length >= 5;+ }+ /**+ * Get all available vault versions+ */+ getAvailableVersions() {+ return [...VAULT_VERSIONS];+ }+ /**+ * Get current/latest vault version info+ */+ getCurrentVersion() {+ return VAULT_VERSIONS[VAULT_VERSIONS.length - 1];+ }+ /**+ * Get specific migration SQL by migration number+ */+ getMigrationSql(migrationNumber) {+ return MIGRATION_SCRIPTS[migrationNumber];+ }+ /**+ * Get complete schema SQL for creating new vault+ */+ getCompleteSchemaeSql() {+ return COMPLETE_SCHEMA_SQL;+ }+};++// src/factories/VaultSqlGeneratorFactory.ts+var CreateVaultSqlGenerator = () => {+ return new VaultSqlGenerator();+};+export {+ COMPLETE_SCHEMA_SQL,+ CreateVaultSqlGenerator,+ MIGRATION_SCRIPTS,+ VAULT_VERSIONS,+ VaultSqlGenerator+};+//# sourceMappingURL=index.mjs.map\ No newline at end of filediff --git a/shared/vault-sql/build.sh b/shared/vault-sql/build.shindex b23fe47c7..10b89820b 100755--- a/shared/vault-sql/build.sh+++ b/shared/vault-sql/build.sh@@ -21,10 +21,12 @@ dist_path="dist"for target in "${TARGETS[@]}"; doecho "📂 Copying $package_name → $target"- mkdir -p "$target"# Remove any existing files in the target directory- rm -rf "$target/*"+ rm -rf "$target"++ # (Re)create the target directory+ mkdir -p "$target"# Copy all build outputscp -R "$dist_path"/* "$target/"diff --git a/shared/vault-sql/package-lock.json b/shared/vault-sql/package-lock.jsonindex 97834835c..cf3e921f9 100644--- a/shared/vault-sql/package-lock.json+++ b/shared/vault-sql/package-lock.json@@ -7,7 +7,7 @@"": {"name": "@aliasvault/vault-sql","version": "1.0.0",- "license": "MIT",+ "license": "AGPL-3.0","devDependencies": {"@typescript-eslint/eslint-plugin": "^8.21.0","@typescript-eslint/parser": "^8.21.0",diff --git a/shared/vault-sql/package.json b/shared/vault-sql/package.jsonindex 5c724214c..cb17c4d59 100644--- a/shared/vault-sql/package.json+++ b/shared/vault-sql/package.json@@ -1,21 +1,22 @@{"name": "@aliasvault/vault-sql","version": "1.0.0",- "type": "module",- "main": "dist/index.mjs",- "types": "dist/index.d.mts",+ "main": "dist/index.js",+ "types": "dist/index.d.ts","scripts": {- "build": "tsup",- "clean": "rm -rf dist",- "lint": "eslint src",- "lint:fix": "eslint src --fix",- "test": "vitest",- "test:coverage": "vitest --coverage"- },+ "build": "tsup",+ "clean": "rm -rf dist",+ "test": "vitest run",+ "test:watch": "vitest",+ "test:coverage": "vitest run --coverage",+ "lint": "eslint src",+ "lint:custom": "eslint",+ "lint:fix": "eslint src --fix"+ },"files": ["dist"],- "license": "MIT",+ "license": "AGPL-3.0","devDependencies": {"@typescript-eslint/eslint-plugin": "^8.21.0","@typescript-eslint/parser": "^8.21.0",diff --git a/shared/vault-sql/src/VaultManager.ts b/shared/vault-sql/src/VaultManager.tsdeleted file mode 100644index d49d8de5e..000000000--- a/shared/vault-sql/src/VaultManager.ts+++ /dev/null@@ -1,279 +0,0 @@-import { COMPLETE_SCHEMA_SQL, MIGRATION_SCRIPTS } from './sql/SqlConstants.js';-import { VAULT_VERSIONS, CURRENT_VAULT_VERSION, type IVaultVersion } from './types/VaultVersion.js';--/**- * Database execution interface for different platforms- */-export interface IDbExecutor {- /**- * Execute SQL command- */- executeSql(sql: string): Promise<void>;-- /**- * Execute SQL command and return results- */- executeSqlWithResults<T = unknown>(sql: string): Promise<T[]>;-- /**- * Execute multiple SQL commands in a transaction- */- executeTransaction(sqlCommands: string[]): Promise<void>;-}--/**- * Vault creation and migration result- */-export interface IVaultOperationResult {- success: boolean;- version: string;- migrationNumber: number;- error?: string;-}--/**- * Vault version info from database- */-export interface ICurrentVaultInfo {- version: string;- migrationNumber: number;- needsUpgrade: boolean;- availableUpgrades: IVaultVersion[];-}--/**- * Vault SQL manager for creating and migrating vaults across platforms- */-export class VaultManager {- constructor(private dbExecutor: IDbExecutor) {}-- /**- * Create a new vault with the latest schema- */- async createNewVault(): Promise<IVaultOperationResult> {- try {- // Enable foreign key constraints and create complete schema- const sqlCommands = [- 'PRAGMA foreign_keys = ON;',- COMPLETE_SCHEMA_SQL,- // Insert version tracking- `INSERT INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")- VALUES ('vault_version', '${CURRENT_VAULT_VERSION.version}', datetime('now'), datetime('now'), 0);`,- `INSERT INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")- VALUES ('vault_migration_number', '${CURRENT_VAULT_VERSION.migrationNumber}', datetime('now'), datetime('now'), 0);`- ];-- await this.dbExecutor.executeTransaction(sqlCommands);-- return {- success: true,- version: CURRENT_VAULT_VERSION.version,- migrationNumber: CURRENT_VAULT_VERSION.migrationNumber- };- } catch (error) {- return {- success: false,- version: '0.0.0',- migrationNumber: 0,- error: error instanceof Error ? error.message : 'Unknown error'- };- }- }-- /**- * Get current vault version and upgrade information- */- async getCurrentVaultInfo(): Promise<ICurrentVaultInfo> {- try {- // Check if Settings table exists- const tables = await this.dbExecutor.executeSqlWithResults<{name: string}>(- "SELECT name FROM sqlite_master WHERE type='table' AND name='Settings';"- );-- if (tables.length === 0) {- // Very old vault or no vault - needs full migration- return {- version: '0.0.0',- migrationNumber: 0,- needsUpgrade: true,- availableUpgrades: VAULT_VERSIONS- };- }-- // Try to get version from Settings table- const versionResult = await this.dbExecutor.executeSqlWithResults<{Value: string}>(- "SELECT Value FROM Settings WHERE Key = 'vault_version' AND IsDeleted = 0 LIMIT 1;"- );-- const migrationResult = await this.dbExecutor.executeSqlWithResults<{Value: string}>(- "SELECT Value FROM Settings WHERE Key = 'vault_migration_number' AND IsDeleted = 0 LIMIT 1;"- );-- let currentVersion = '1.0.0';- let currentMigrationNumber = 1;-- if (versionResult.length > 0) {- currentVersion = versionResult[0].Value;- }-- if (migrationResult.length > 0) {- currentMigrationNumber = parseInt(migrationResult[0].Value, 10);- }-- const needsUpgrade = currentMigrationNumber < CURRENT_VAULT_VERSION.migrationNumber;- const availableUpgrades = VAULT_VERSIONS.filter(v => v.migrationNumber > currentMigrationNumber);-- return {- version: currentVersion,- migrationNumber: currentMigrationNumber,- needsUpgrade,- availableUpgrades- };- } catch {- // If we can't determine version, assume it needs upgrade- return {- version: '0.0.0',- migrationNumber: 0,- needsUpgrade: true,- availableUpgrades: VAULT_VERSIONS- };- }- }-- /**- * Upgrade vault to latest version- */- async upgradeVault(): Promise<IVaultOperationResult> {- try {- const currentInfo = await this.getCurrentVaultInfo();-- if (!currentInfo.needsUpgrade) {- return {- success: true,- version: currentInfo.version,- migrationNumber: currentInfo.migrationNumber- };- }-- // Apply migrations in order- const sqlCommands: string[] = ['PRAGMA foreign_keys = ON;'];-- for (const upgrade of currentInfo.availableUpgrades) {- const migrationSql = MIGRATION_SCRIPTS[upgrade.migrationNumber];- if (migrationSql) {- sqlCommands.push(migrationSql);- }- }-- // Update version tracking- sqlCommands.push(- `INSERT OR REPLACE INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")- VALUES ('vault_version', '${CURRENT_VAULT_VERSION.version}', datetime('now'), datetime('now'), 0);`- );- sqlCommands.push(- `INSERT OR REPLACE INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")- VALUES ('vault_migration_number', '${CURRENT_VAULT_VERSION.migrationNumber}', datetime('now'), datetime('now'), 0);`- );-- await this.dbExecutor.executeTransaction(sqlCommands);-- return {- success: true,- version: CURRENT_VAULT_VERSION.version,- migrationNumber: CURRENT_VAULT_VERSION.migrationNumber- };- } catch (error) {- return {- success: false,- version: '0.0.0',- migrationNumber: 0,- error: error instanceof Error ? error.message : 'Unknown error'- };- }- }-- /**- * Upgrade vault to a specific version- */- async upgradeVaultToVersion(targetVersion: string): Promise<IVaultOperationResult> {- try {- const currentInfo = await this.getCurrentVaultInfo();- const targetVersionInfo = VAULT_VERSIONS.find(v => v.version === targetVersion);-- if (!targetVersionInfo) {- return {- success: false,- version: currentInfo.version,- migrationNumber: currentInfo.migrationNumber,- error: `Target version ${targetVersion} not found`- };- }-- if (currentInfo.migrationNumber >= targetVersionInfo.migrationNumber) {- return {- success: true,- version: currentInfo.version,- migrationNumber: currentInfo.migrationNumber- };- }-- // Apply migrations up to target version- const sqlCommands: string[] = ['PRAGMA foreign_keys = ON;'];-- const migrationsToApply = VAULT_VERSIONS.filter(- v => v.migrationNumber > currentInfo.migrationNumber &&- v.migrationNumber <= targetVersionInfo.migrationNumber- );-- for (const migration of migrationsToApply) {- const migrationSql = MIGRATION_SCRIPTS[migration.migrationNumber];- if (migrationSql) {- sqlCommands.push(migrationSql);- }- }-- // Update version tracking- sqlCommands.push(- `INSERT OR REPLACE INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")- VALUES ('vault_version', '${targetVersionInfo.version}', datetime('now'), datetime('now'), 0);`- );- sqlCommands.push(- `INSERT OR REPLACE INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")- VALUES ('vault_migration_number', '${targetVersionInfo.migrationNumber}', datetime('now'), datetime('now'), 0);`- );-- await this.dbExecutor.executeTransaction(sqlCommands);-- return {- success: true,- version: targetVersionInfo.version,- migrationNumber: targetVersionInfo.migrationNumber- };- } catch (error) {- return {- success: false,- version: '0.0.0',- migrationNumber: 0,- error: error instanceof Error ? error.message : 'Unknown error'- };- }- }-- /**- * Check if vault database exists and is valid- */- async isValidVault(): Promise<boolean> {- try {- // Check if core tables exist- const tables = await this.dbExecutor.executeSqlWithResults<{name: string}>(- `SELECT name FROM sqlite_master WHERE type='table' AND name IN- ('Aliases', 'Services', 'Credentials', 'Passwords', 'Attachments', 'EncryptionKeys', 'Settings', 'TotpCodes');`- );-- // Should have all 8 core tables- return tables.length >= 5; // At minimum, need core tables (some might not exist in older versions)- } catch {- return false;- }- }-}diff --git a/shared/vault-sql/src/__tests__/VaultManager.test.ts b/shared/vault-sql/src/__tests__/VaultManager.test.tsdeleted file mode 100644index af05786b7..000000000--- a/shared/vault-sql/src/__tests__/VaultManager.test.ts+++ /dev/null@@ -1,198 +0,0 @@-import { describe, it, expect, beforeEach, vi } from 'vitest';-import { VaultManager, type IDbExecutor } from '../VaultManager.js';-import { CURRENT_VAULT_VERSION } from '../types/VaultVersion.js';--// Mock database executor for testing-class MockDbExecutor implements IDbExecutor {- private queries: string[] = [];- private mockResults: Record<string, unknown[]> = {};-- async executeSql(sql: string): Promise<void> {- this.queries.push(sql);- }-- async executeSqlWithResults<T = unknown>(sql: string): Promise<T[]> {- this.queries.push(sql);- // Normalize SQL for matching - remove extra whitespace and newlines- const key = sql.toLowerCase().replace(/\s+/g, ' ').trim();- return (this.mockResults[key] as T[]) || [];- }-- async executeTransaction(sqlCommands: string[]): Promise<void> {- this.queries.push(...sqlCommands);- }-- // Test helpers- getExecutedQueries(): string[] {- return [...this.queries];- }-- clearQueries(): void {- this.queries = [];- }-- setMockResult(sql: string, result: unknown[]): void {- // Normalize SQL for matching - remove extra whitespace and newlines- const key = sql.toLowerCase().replace(/\s+/g, ' ').trim();- this.mockResults[key] = result;- }-}--describe('VaultManager', () => {- let vaultManager: VaultManager;- let mockDb: MockDbExecutor;-- beforeEach(() => {- mockDb = new MockDbExecutor();- vaultManager = new VaultManager(mockDb);- });-- describe('createNewVault', () => {- it('should create a new vault with latest schema', async () => {- const result = await vaultManager.createNewVault();-- expect(result.success).toBe(true);- expect(result.version).toBe(CURRENT_VAULT_VERSION.version);- expect(result.migrationNumber).toBe(CURRENT_VAULT_VERSION.migrationNumber);-- const queries = mockDb.getExecutedQueries();- expect(queries).toContain('PRAGMA foreign_keys = ON;');- expect(queries.some(q => q.includes('CREATE TABLE "Aliases"'))).toBe(true);- expect(queries.some(q => q.includes('vault_version'))).toBe(true);- });-- it('should handle errors during vault creation', async () => {- const failingDb = {- executeSql: vi.fn().mockRejectedValue(new Error('Database error')),- executeSqlWithResults: vi.fn(),- executeTransaction: vi.fn().mockRejectedValue(new Error('Database error'))- };-- const failingVaultManager = new VaultManager(failingDb);- const result = await failingVaultManager.createNewVault();-- expect(result.success).toBe(false);- expect(result.error).toBe('Database error');- });- });-- describe('getCurrentVaultInfo', () => {- it('should return correct info for new vault without Settings table', async () => {- // Mock no Settings table exists- mockDb.setMockResult("select name from sqlite_master where type='table' and name='settings';", []);-- const info = await vaultManager.getCurrentVaultInfo();-- expect(info.version).toBe('0.0.0');- expect(info.migrationNumber).toBe(0);- expect(info.needsUpgrade).toBe(true);- expect(info.availableUpgrades.length).toBeGreaterThan(0);- });-- it('should return correct info for existing vault with version info', async () => {- // Mock Settings table exists- mockDb.setMockResult("select name from sqlite_master where type='table' and name='settings';", [{ name: 'Settings' }]);-- // Mock version queries- mockDb.setMockResult("select value from settings where key = 'vault_version' and isdeleted = 0 limit 1;", [{ Value: '1.2.0' }]);- mockDb.setMockResult("select value from settings where key = 'vault_migration_number' and isdeleted = 0 limit 1;", [{ Value: '4' }]);-- const info = await vaultManager.getCurrentVaultInfo();-- expect(info.version).toBe('1.2.0');- expect(info.migrationNumber).toBe(4);- expect(info.needsUpgrade).toBe(info.migrationNumber < CURRENT_VAULT_VERSION.migrationNumber);- });-- it('should handle errors and default to needs upgrade', async () => {- const failingDb = {- executeSql: vi.fn(),- executeSqlWithResults: vi.fn().mockRejectedValue(new Error('Database error')),- executeTransaction: vi.fn()- };-- const failingVaultManager = new VaultManager(failingDb);- const info = await failingVaultManager.getCurrentVaultInfo();-- expect(info.version).toBe('0.0.0');- expect(info.migrationNumber).toBe(0);- expect(info.needsUpgrade).toBe(true);- });- });-- describe('upgradeVault', () => {- it('should not upgrade if vault is already current', async () => {- // Mock Settings table exists- mockDb.setMockResult("select name from sqlite_master where type='table' and name='settings';", [{ name: 'Settings' }]);-- // Mock current version- mockDb.setMockResult("select value from settings where key = 'vault_version' and isdeleted = 0 limit 1;", [{ Value: CURRENT_VAULT_VERSION.version }]);- mockDb.setMockResult("select value from settings where key = 'vault_migration_number' and isdeleted = 0 limit 1;", [{ Value: CURRENT_VAULT_VERSION.migrationNumber.toString() }]);-- const result = await vaultManager.upgradeVault();-- expect(result.success).toBe(true);- expect(result.version).toBe(CURRENT_VAULT_VERSION.version);- expect(result.migrationNumber).toBe(CURRENT_VAULT_VERSION.migrationNumber);- });-- it('should upgrade from older version', async () => {- // Mock Settings table exists with older version- mockDb.setMockResult("select name from sqlite_master where type='table' and name='settings';", [{ name: 'Settings' }]);- mockDb.setMockResult("select value from settings where key = 'vault_version' and isdeleted = 0 limit 1;", [{ Value: '1.0.0' }]);- mockDb.setMockResult("select value from settings where key = 'vault_migration_number' and isdeleted = 0 limit 1;", [{ Value: '1' }]);-- const result = await vaultManager.upgradeVault();-- expect(result.success).toBe(true);- expect(result.version).toBe(CURRENT_VAULT_VERSION.version);- expect(result.migrationNumber).toBe(CURRENT_VAULT_VERSION.migrationNumber);-- const queries = mockDb.getExecutedQueries();- expect(queries).toContain('PRAGMA foreign_keys = ON;');- expect(queries.some(q => q.includes('vault_version'))).toBe(true);- });- });-- describe('isValidVault', () => {- it('should return true for valid vault with core tables', async () => {- mockDb.setMockResult(- `select name from sqlite_master where type='table' and name in- ('aliases', 'services', 'credentials', 'passwords', 'attachments', 'encryptionkeys', 'settings', 'totpcodes');`,- [- { name: 'Aliases' },- { name: 'Services' },- { name: 'Credentials' },- { name: 'Passwords' },- { name: 'Attachments' }- ]- );-- const isValid = await vaultManager.isValidVault();- expect(isValid).toBe(true);- });-- it('should return false for vault with insufficient tables', async () => {- mockDb.setMockResult(- `select name from sqlite_master where type='table' and name in- ('aliases', 'services', 'credentials', 'passwords', 'attachments', 'encryptionkeys', 'settings', 'totpcodes');`,- [{ name: 'Aliases' }]- );-- const isValid = await vaultManager.isValidVault();- expect(isValid).toBe(false);- });-- it('should return false on database error', async () => {- const failingDb = {- executeSql: vi.fn(),- executeSqlWithResults: vi.fn().mockRejectedValue(new Error('Database error')),- executeTransaction: vi.fn()- };-- const failingVaultManager = new VaultManager(failingDb);- const isValid = await failingVaultManager.isValidVault();- expect(isValid).toBe(false);- });- });-});diff --git a/shared/vault-sql/src/__tests__/VaultSqlGenerator.test.ts b/shared/vault-sql/src/__tests__/VaultSqlGenerator.test.tsnew file mode 100644index 000000000..3206c5196--- /dev/null+++ b/shared/vault-sql/src/__tests__/VaultSqlGenerator.test.ts@@ -0,0 +1,165 @@+import { describe, it, expect } from 'vitest';+import { VaultSqlGenerator } from '../sql/VaultSqlGenerator.js';+import { CURRENT_VAULT_VERSION } from '../types/VaultVersion.js';++describe('VaultSqlGenerator', () => {+ describe('getCreateVaultSql', () => {+ it('should return SQL commands for creating a new vault', () => {+ const result = VaultSqlGenerator.getCreateVaultSql();++ expect(result.success).toBe(true);+ expect(result.sqlCommands.length).toBeGreaterThan(0);+ expect(result.version).toBe(CURRENT_VAULT_VERSION.version);+ expect(result.migrationNumber).toBe(CURRENT_VAULT_VERSION.migrationNumber);++ // Should include PRAGMA and schema creation+ expect(result.sqlCommands[0]).toBe('PRAGMA foreign_keys = ON;');+ expect(result.sqlCommands.some(cmd => cmd.includes('CREATE TABLE "Aliases"'))).toBe(true);+ expect(result.sqlCommands.some(cmd => cmd.includes('vault_version'))).toBe(true);+ });+ });++ describe('getUpgradeVaultSql', () => {+ it('should return empty commands when vault is already at target version', () => {+ const result = VaultSqlGenerator.getUpgradeVaultSql(CURRENT_VAULT_VERSION.migrationNumber);++ expect(result.success).toBe(true);+ expect(result.sqlCommands).toEqual([]);+ expect(result.version).toBe(CURRENT_VAULT_VERSION.version);+ expect(result.migrationNumber).toBe(CURRENT_VAULT_VERSION.migrationNumber);+ });++ it('should return upgrade commands for older version', () => {+ const result = VaultSqlGenerator.getUpgradeVaultSql(1, 3); // Upgrade from v1.0.0 to v1.1.0++ expect(result.success).toBe(true);+ expect(result.sqlCommands.length).toBeGreaterThan(0);++ // Should include PRAGMA and version updates+ expect(result.sqlCommands[0]).toBe('PRAGMA foreign_keys = ON;');+ expect(result.sqlCommands.some(cmd => cmd.includes('vault_version'))).toBe(true);+ });++ it('should handle invalid target migration number', () => {+ const result = VaultSqlGenerator.getUpgradeVaultSql(1, 999);++ expect(result.success).toBe(false);+ expect(result.error).toContain('not found');+ });+ });++ describe('getUpgradeToVersionSql', () => {+ it('should upgrade to specific version', () => {+ const result = VaultSqlGenerator.getUpgradeToVersionSql(1, '1.2.0');++ expect(result.success).toBe(true);+ expect(result.sqlCommands.length).toBeGreaterThan(0);+ });++ it('should handle invalid version', () => {+ const result = VaultSqlGenerator.getUpgradeToVersionSql(1, '99.99.99');++ expect(result.success).toBe(false);+ expect(result.error).toContain('not found');+ });+ });++ describe('getVersionCheckSql', () => {+ it('should return SQL commands to check vault version', () => {+ const commands = VaultSqlGenerator.getVersionCheckSql();++ expect(commands.length).toBe(3);+ expect(commands[0]).toContain('sqlite_master');+ expect(commands[1]).toContain('vault_version');+ expect(commands[2]).toContain('vault_migration_number');+ });+ });++ describe('getVaultValidationSql', () => {+ it('should return SQL to validate vault structure', () => {+ const sql = VaultSqlGenerator.getVaultValidationSql();++ expect(sql).toContain('sqlite_master');+ expect(sql).toContain('Aliases');+ expect(sql).toContain('Services');+ expect(sql).toContain('Credentials');+ });+ });++ describe('parseVaultVersionInfo', () => {+ it('should parse vault version info correctly', () => {+ const info = VaultSqlGenerator.parseVaultVersionInfo(true, '1.2.0', '4');++ expect(info.currentVersion).toBe('1.2.0');+ expect(info.currentMigrationNumber).toBe(4);+ expect(info.needsUpgrade).toBe(info.currentMigrationNumber < CURRENT_VAULT_VERSION.migrationNumber);+ });++ it('should handle missing Settings table', () => {+ const info = VaultSqlGenerator.parseVaultVersionInfo(false);++ expect(info.currentVersion).toBe('0.0.0');+ expect(info.currentMigrationNumber).toBe(0);+ expect(info.needsUpgrade).toBe(true);+ });++ it('should handle Settings table without version info', () => {+ const info = VaultSqlGenerator.parseVaultVersionInfo(true);++ expect(info.currentVersion).toBe('1.0.0');+ expect(info.currentMigrationNumber).toBe(1);+ });+ });++ describe('validateVaultStructure', () => {+ it('should validate vault with all required tables', () => {+ const tables = ['Aliases', 'Services', 'Credentials', 'Passwords', 'Settings'];+ const isValid = VaultSqlGenerator.validateVaultStructure(tables);++ expect(isValid).toBe(true);+ });++ it('should reject vault with missing core tables', () => {+ const tables = ['Aliases', 'Services'];+ const isValid = VaultSqlGenerator.validateVaultStructure(tables);++ expect(isValid).toBe(false);+ });++ it('should handle case-insensitive table names', () => {+ const tables = ['aliases', 'services', 'credentials', 'passwords'];+ const isValid = VaultSqlGenerator.validateVaultStructure(tables);++ expect(isValid).toBe(true);+ });+ });++ describe('utility methods', () => {+ it('should return available versions', () => {+ const versions = VaultSqlGenerator.getAvailableVersions();++ expect(versions.length).toBeGreaterThan(0);+ expect(versions[0].version).toBe('1.0.0');+ });++ it('should return current version', () => {+ const version = VaultSqlGenerator.getCurrentVersion();++ expect(version).toEqual(CURRENT_VAULT_VERSION);+ });++ it('should return migration SQL by number', () => {+ const sql = VaultSqlGenerator.getMigrationSql(1);++ expect(sql).toBeDefined();+ expect(sql).toContain('CREATE TABLE');+ });++ it('should return complete schema SQL', () => {+ const sql = VaultSqlGenerator.getCompleteSchemaeSql();++ expect(sql).toBeDefined();+ expect(sql).toContain('CREATE TABLE "Aliases"');+ });+ });+});\ No newline at end of filediff --git a/shared/vault-sql/src/factories/VaultSqlGeneratorFactory.ts b/shared/vault-sql/src/factories/VaultSqlGeneratorFactory.tsnew file mode 100644index 000000000..3cd3443ac--- /dev/null+++ b/shared/vault-sql/src/factories/VaultSqlGeneratorFactory.ts@@ -0,0 +1,9 @@+import { VaultSqlGenerator } from '../sql/VaultSqlGenerator';++/**+ * Creates a new VaultSqlGenerator instance.+ * @returns A new VaultSqlGenerator instance.+ */+export const CreateVaultSqlGenerator = (): VaultSqlGenerator => {+ return new VaultSqlGenerator();+};\ No newline at end of filediff --git a/shared/vault-sql/src/index.ts b/shared/vault-sql/src/index.tsindex df25eb13e..c55686b80 100644--- a/shared/vault-sql/src/index.ts+++ b/shared/vault-sql/src/index.ts@@ -1,27 +1,5 @@-/**- * @aliasvault/vault-sql- *- * Shared SQL scripts and utilities for AliasVault database operations.- * Provides cross-platform vault creation and migration functionality.- */--// Export VaultManager and interfaces-export {- VaultManager,- type IDbExecutor,- type IVaultOperationResult,- type ICurrentVaultInfo-} from './VaultManager.js';--// Export version types and constants-export {- type IVaultVersion,- VAULT_VERSIONS,- CURRENT_VAULT_VERSION-} from './types/VaultVersion.js';--// Export SQL constants-export {- COMPLETE_SCHEMA_SQL,- MIGRATION_SCRIPTS-} from './sql/SqlConstants.js';+export * from './types/VaultVersion';+export * from './sql/VaultSqlGenerator';+export * from './sql/VaultVersions';+export * from './sql/SqlConstants';+export * from './factories/VaultSqlGeneratorFactory';\ No newline at end of filediff --git a/shared/vault-sql/src/sql/SqlConstants.ts b/shared/vault-sql/src/sql/SqlConstants.tsindex b4c5deb79..2bc9de6c9 100644--- a/shared/vault-sql/src/sql/SqlConstants.ts+++ b/shared/vault-sql/src/sql/SqlConstants.ts@@ -1,300 +1,451 @@+/* eslint-disable no-irregular-whitespace */+/*** Complete database schema SQL (latest version)+ * Auto-generated from EF Core migrations*/-export const COMPLETE_SCHEMA_SQL = `-- AliasVault Client Database Complete Schema--- Final schema after all migrations (up to version 1.5.0)--- This script creates the complete database structure---- Enable foreign key constraints-PRAGMA foreign_keys = ON;+export const COMPLETE_SCHEMA_SQL = `+CREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" (+ "MigrationId" TEXT NOT NULL CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY,+ "ProductVersion" TEXT NOT NULL+);--- Create Aliases table+BEGIN TRANSACTION;CREATE TABLE "Aliases" (- "Id" TEXT NOT NULL PRIMARY KEY,- "Gender" VARCHAR(255),- "FirstName" VARCHAR(255),- "LastName" VARCHAR(255),- "NickName" VARCHAR(255),+ "Id" TEXT NOT NULL CONSTRAINT "PK_Aliases" PRIMARY KEY,+ "Gender" VARCHAR NULL,+ "FirstName" VARCHAR NULL,+ "LastName" VARCHAR NULL,+ "NickName" VARCHAR NULL,"BirthDate" TEXT NOT NULL,- "Email" TEXT, -- Renamed from EmailPrefix in v1.0.2+ "AddressStreet" VARCHAR NULL,+ "AddressCity" VARCHAR NULL,+ "AddressState" VARCHAR NULL,+ "AddressZipCode" VARCHAR NULL,+ "AddressCountry" VARCHAR NULL,+ "Hobbies" TEXT NULL,+ "EmailPrefix" TEXT NULL,+ "PhoneMobile" TEXT NULL,+ "BankAccountIBAN" TEXT NULL,"CreatedAt" TEXT NOT NULL,- "UpdatedAt" TEXT NOT NULL,- "IsDeleted" INTEGER NOT NULL DEFAULT 0 -- Added in v1.4.0- -- Note: Address, phone, hobbies, and bank account columns removed in v1.3.0+ "UpdatedAt" TEXT NOT NULL);--- Create Services tableCREATE TABLE "Services" (- "Id" TEXT NOT NULL PRIMARY KEY,- "Name" TEXT,- "Url" TEXT,- "Logo" BLOB,+ "Id" TEXT NOT NULL CONSTRAINT "PK_Services" PRIMARY KEY,+ "Name" TEXT NULL,+ "Url" TEXT NULL,+ "Logo" BLOB NULL,"CreatedAt" TEXT NOT NULL,- "UpdatedAt" TEXT NOT NULL,- "IsDeleted" INTEGER NOT NULL DEFAULT 0 -- Added in v1.4.0+ "UpdatedAt" TEXT NOT NULL);--- Create Credentials tableCREATE TABLE "Credentials" (- "Id" TEXT NOT NULL PRIMARY KEY,+ "Id" TEXT NOT NULL CONSTRAINT "PK_Credentials" PRIMARY KEY,"AliasId" TEXT NOT NULL,- "Notes" TEXT,- "Username" TEXT, -- Made optional in v1.3.1+ "Notes" TEXT NULL,+ "Username" TEXT NOT NULL,"CreatedAt" TEXT NOT NULL,"UpdatedAt" TEXT NOT NULL,"ServiceId" TEXT NOT NULL,- "IsDeleted" INTEGER NOT NULL DEFAULT 0, -- Added in v1.4.0- FOREIGN KEY ("AliasId") REFERENCES "Aliases" ("Id") ON DELETE CASCADE,- FOREIGN KEY ("ServiceId") REFERENCES "Services" ("Id") ON DELETE CASCADE+ CONSTRAINT "FK_Credentials_Aliases_AliasId" FOREIGN KEY ("AliasId") REFERENCES "Aliases" ("Id") ON DELETE CASCADE,+ CONSTRAINT "FK_Credentials_Services_ServiceId" FOREIGN KEY ("ServiceId") REFERENCES "Services" ("Id") ON DELETE CASCADE);--- Create Attachments table (renamed from Attachment in v1.4.1)-CREATE TABLE "Attachments" (- "Id" TEXT NOT NULL PRIMARY KEY,+CREATE TABLE "Attachment" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Attachment" PRIMARY KEY,"Filename" TEXT NOT NULL,"Blob" BLOB NOT NULL,"CreatedAt" TEXT NOT NULL,"UpdatedAt" TEXT NOT NULL,"CredentialId" TEXT NOT NULL,- "IsDeleted" INTEGER NOT NULL DEFAULT 0, -- Added in v1.4.0- FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+ CONSTRAINT "FK_Attachment_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE);--- Create Passwords tableCREATE TABLE "Passwords" (- "Id" TEXT NOT NULL PRIMARY KEY,- "Value" TEXT,+ "Id" TEXT NOT NULL CONSTRAINT "PK_Passwords" PRIMARY KEY,+ "Value" TEXT NULL,"CreatedAt" TEXT NOT NULL,"UpdatedAt" TEXT NOT NULL,"CredentialId" TEXT NOT NULL,- "IsDeleted" INTEGER NOT NULL DEFAULT 0, -- Added in v1.4.0- FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+ CONSTRAINT "FK_Passwords_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE);--- Create EncryptionKeys table (added in v1.1.0)+CREATE INDEX "IX_Attachment_CredentialId" ON "Attachment" ("CredentialId");++CREATE INDEX "IX_Credentials_AliasId" ON "Credentials" ("AliasId");++CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");++CREATE INDEX "IX_Passwords_CredentialId" ON "Passwords" ("CredentialId");++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240708094944_1.0.0-InitialMigration', '9.0.4');++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240708224522_1.0.1-EmptyTestMigration', '9.0.4');++ALTER TABLE "Aliases" RENAME COLUMN "EmailPrefix" TO "Email";++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240711204207_1.0.2-ChangeEmailColumn', '9.0.4');+CREATE TABLE "EncryptionKeys" (- "Id" TEXT NOT NULL PRIMARY KEY,+ "Id" TEXT NOT NULL CONSTRAINT "PK_EncryptionKeys" PRIMARY KEY,"PublicKey" TEXT NOT NULL,"PrivateKey" TEXT NOT NULL,"IsPrimary" INTEGER NOT NULL,"CreatedAt" TEXT NOT NULL,- "UpdatedAt" TEXT NOT NULL,- "IsDeleted" INTEGER NOT NULL DEFAULT 0 -- Added in v1.4.0+ "UpdatedAt" TEXT NOT NULL);--- Create Settings table (added in v1.2.0)-CREATE TABLE "Settings" (- "Key" TEXT NOT NULL PRIMARY KEY,- "Value" TEXT,- "CreatedAt" TEXT NOT NULL,- "UpdatedAt" TEXT NOT NULL,- "IsDeleted" INTEGER NOT NULL DEFAULT 0 -- Added in v1.4.0-);+INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240729105618_1.1.0-AddPkiTables', '9.0.4');--- Create TotpCodes table (added in v1.5.0)-CREATE TABLE "TotpCodes" (- "Id" TEXT NOT NULL PRIMARY KEY,- "Name" TEXT NOT NULL,- "SecretKey" TEXT NOT NULL,- "CredentialId" TEXT NOT NULL,+CREATE TABLE "Settings" (+ "Key" TEXT NOT NULL CONSTRAINT "PK_Settings" PRIMARY KEY,+ "Value" TEXT NULL,"CreatedAt" TEXT NOT NULL,- "UpdatedAt" TEXT NOT NULL,- "IsDeleted" INTEGER NOT NULL,- FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+ "UpdatedAt" TEXT NOT NULL);--- Create indexes-CREATE INDEX "IX_Attachments_CredentialId" ON "Attachments" ("CredentialId");-CREATE INDEX "IX_Credentials_AliasId" ON "Credentials" ("AliasId");-CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");-CREATE INDEX "IX_Passwords_CredentialId" ON "Passwords" ("CredentialId");-CREATE INDEX "IX_TotpCodes_CredentialId" ON "TotpCodes" ("CredentialId");`;--/**- * Individual migration SQL scripts- */-export const MIGRATION_SCRIPTS: Record<number, string> = {- 1: `-- Migration 1.0.0: Initial Migration--- Create the initial database schema for AliasVault Client+INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240805073413_1.2.0-AddSettingsTable', '9.0.4');--- Create Aliases table-CREATE TABLE "Aliases" (- "Id" TEXT NOT NULL PRIMARY KEY,- "Gender" VARCHAR(255),- "FirstName" VARCHAR(255),- "LastName" VARCHAR(255),- "NickName" VARCHAR(255),+CREATE TABLE "ef_temp_Aliases" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Aliases" PRIMARY KEY,"BirthDate" TEXT NOT NULL,- "AddressStreet" VARCHAR(255),- "AddressCity" VARCHAR(255),- "AddressState" VARCHAR(255),- "AddressZipCode" VARCHAR(255),- "AddressCountry" VARCHAR(255),- "Hobbies" TEXT,- "EmailPrefix" TEXT,- "PhoneMobile" TEXT,- "BankAccountIBAN" TEXT,"CreatedAt" TEXT NOT NULL,+ "Email" TEXT NULL,+ "FirstName" VARCHAR NULL,+ "Gender" VARCHAR NULL,+ "LastName" VARCHAR NULL,+ "NickName" VARCHAR NULL,"UpdatedAt" TEXT NOT NULL);--- Create Services table-CREATE TABLE "Services" (- "Id" TEXT NOT NULL PRIMARY KEY,- "Name" TEXT,- "Url" TEXT,- "Logo" BLOB,- "CreatedAt" TEXT NOT NULL,- "UpdatedAt" TEXT NOT NULL-);+INSERT INTO "ef_temp_Aliases" ("Id", "BirthDate", "CreatedAt", "Email", "FirstName", "Gender", "LastName", "NickName", "UpdatedAt")+SELECT "Id", "BirthDate", "CreatedAt", "Email", "FirstName", "Gender", "LastName", "NickName", "UpdatedAt"+FROM "Aliases";--- Create Credentials table-CREATE TABLE "Credentials" (- "Id" TEXT NOT NULL PRIMARY KEY,+COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;+DROP TABLE "Aliases";++ALTER TABLE "ef_temp_Aliases" RENAME TO "Aliases";++COMMIT;++PRAGMA foreign_keys = 1;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240805122422_1.3.0-UpdateIdentityStructure', '9.0.4');++BEGIN TRANSACTION;+CREATE TABLE "ef_temp_Credentials" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Credentials" PRIMARY KEY,"AliasId" TEXT NOT NULL,- "Notes" TEXT,- "Username" TEXT NOT NULL,"CreatedAt" TEXT NOT NULL,- "UpdatedAt" TEXT NOT NULL,+ "Notes" TEXT NULL,"ServiceId" TEXT NOT NULL,- FOREIGN KEY ("AliasId") REFERENCES "Aliases" ("Id") ON DELETE CASCADE,- FOREIGN KEY ("ServiceId") REFERENCES "Services" ("Id") ON DELETE CASCADE+ "UpdatedAt" TEXT NOT NULL,+ "Username" TEXT NULL,+ CONSTRAINT "FK_Credentials_Aliases_AliasId" FOREIGN KEY ("AliasId") REFERENCES "Aliases" ("Id") ON DELETE CASCADE,+ CONSTRAINT "FK_Credentials_Services_ServiceId" FOREIGN KEY ("ServiceId") REFERENCES "Services" ("Id") ON DELETE CASCADE);--- Create Attachment table-CREATE TABLE "Attachment" (- "Id" TEXT NOT NULL PRIMARY KEY,- "Filename" TEXT NOT NULL,+INSERT INTO "ef_temp_Credentials" ("Id", "AliasId", "CreatedAt", "Notes", "ServiceId", "UpdatedAt", "Username")+SELECT "Id", "AliasId", "CreatedAt", "Notes", "ServiceId", "UpdatedAt", "Username"+FROM "Credentials";++COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;+DROP TABLE "Credentials";++ALTER TABLE "ef_temp_Credentials" RENAME TO "Credentials";++COMMIT;++PRAGMA foreign_keys = 1;++BEGIN TRANSACTION;+CREATE INDEX "IX_Credentials_AliasId" ON "Credentials" ("AliasId");++CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");++COMMIT;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240812141727_1.3.1-MakeUsernameOptional', '9.0.4');++BEGIN TRANSACTION;+ALTER TABLE "Settings" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Services" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Passwords" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "EncryptionKeys" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Credentials" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Attachment" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Aliases" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240916105320_1.4.0-AddSyncSupport', '9.0.4');++ALTER TABLE "Attachment" RENAME TO "Attachments";++CREATE TABLE "ef_temp_Attachments" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Attachments" PRIMARY KEY,"Blob" BLOB NOT NULL,"CreatedAt" TEXT NOT NULL,- "UpdatedAt" TEXT NOT NULL,"CredentialId" TEXT NOT NULL,- FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+ "Filename" TEXT NOT NULL,+ "IsDeleted" INTEGER NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ CONSTRAINT "FK_Attachments_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE);--- Create Passwords table-CREATE TABLE "Passwords" (- "Id" TEXT NOT NULL PRIMARY KEY,- "Value" TEXT,+INSERT INTO "ef_temp_Attachments" ("Id", "Blob", "CreatedAt", "CredentialId", "Filename", "IsDeleted", "UpdatedAt")+SELECT "Id", "Blob", "CreatedAt", "CredentialId", "Filename", "IsDeleted", "UpdatedAt"+FROM "Attachments";++COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;+DROP TABLE "Attachments";++ALTER TABLE "ef_temp_Attachments" RENAME TO "Attachments";++COMMIT;++PRAGMA foreign_keys = 1;++BEGIN TRANSACTION;+CREATE INDEX "IX_Attachments_CredentialId" ON "Attachments" ("CredentialId");++COMMIT;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240917191243_1.4.1-RenameAttachmentsPlural', '9.0.4');++BEGIN TRANSACTION;+CREATE TABLE "TotpCodes" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_TotpCodes" PRIMARY KEY,+ "Name" TEXT NOT NULL,+ "SecretKey" TEXT NOT NULL,+ "CredentialId" TEXT NOT NULL,"CreatedAt" TEXT NOT NULL,"UpdatedAt" TEXT NOT NULL,- "CredentialId" TEXT NOT NULL,- FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+ "IsDeleted" INTEGER NOT NULL,+ CONSTRAINT "FK_TotpCodes_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE);--- Create indexes-CREATE INDEX "IX_Attachment_CredentialId" ON "Attachment" ("CredentialId");-CREATE INDEX "IX_Credentials_AliasId" ON "Credentials" ("AliasId");-CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");-CREATE INDEX "IX_Passwords_CredentialId" ON "Passwords" ("CredentialId");`,+CREATE INDEX "IX_TotpCodes_CredentialId" ON "TotpCodes" ("CredentialId");++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20250310131554_1.5.0-AddTotpCodes', '9.0.4');- 2: `-- Migration 1.0.2: Change Email Column--- Rename EmailPrefix to Email in Aliases table+COMMIT;+`;+/**+ * Individual migration SQL scripts+ * Auto-generated from EF Core migrations+ */+export const MIGRATION_SCRIPTS: Record<number, string> = {+ 1: `BEGIN TRANSACTION;+INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240708224522_1.0.1-EmptyTestMigration', '9.0.4');-ALTER TABLE "Aliases" RENAME COLUMN "EmailPrefix" TO "Email";`,+COMMIT;`,+ 2: `BEGIN TRANSACTION;+ALTER TABLE "Aliases" RENAME COLUMN "EmailPrefix" TO "Email";- 3: `-- Migration 1.1.0: Add PKI Tables--- Add EncryptionKeys table for PKI support+INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240711204207_1.0.2-ChangeEmailColumn', '9.0.4');+COMMIT;`,+ 3: `BEGIN TRANSACTION;CREATE TABLE "EncryptionKeys" (- "Id" TEXT NOT NULL PRIMARY KEY,+ "Id" TEXT NOT NULL CONSTRAINT "PK_EncryptionKeys" PRIMARY KEY,"PublicKey" TEXT NOT NULL,"PrivateKey" TEXT NOT NULL,"IsPrimary" INTEGER NOT NULL,"CreatedAt" TEXT NOT NULL,"UpdatedAt" TEXT NOT NULL-);`,+);- 4: `-- Migration 1.2.0: Add Settings Table--- Add Settings table for user preferences+INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240729105618_1.1.0-AddPkiTables', '9.0.4');+COMMIT;`,+ 4: `BEGIN TRANSACTION;CREATE TABLE "Settings" (- "Key" TEXT NOT NULL PRIMARY KEY,- "Value" TEXT,+ "Key" TEXT NOT NULL CONSTRAINT "PK_Settings" PRIMARY KEY,+ "Value" TEXT NULL,+ "CreatedAt" TEXT NOT NULL,+ "UpdatedAt" TEXT NOT NULL+);++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240805073413_1.2.0-AddSettingsTable', '9.0.4');++COMMIT;`,+ 5: `BEGIN TRANSACTION;+CREATE TABLE "ef_temp_Aliases" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Aliases" PRIMARY KEY,+ "BirthDate" TEXT NOT NULL,"CreatedAt" TEXT NOT NULL,+ "Email" TEXT NULL,+ "FirstName" VARCHAR NULL,+ "Gender" VARCHAR NULL,+ "LastName" VARCHAR NULL,+ "NickName" VARCHAR NULL,"UpdatedAt" TEXT NOT NULL-);`,-- 5: `-- Migration 1.3.0: Update Identity Structure--- Remove address, phone, hobbies, and bank account columns from Aliases table--ALTER TABLE "Aliases" DROP COLUMN "AddressStreet";-ALTER TABLE "Aliases" DROP COLUMN "AddressCity";-ALTER TABLE "Aliases" DROP COLUMN "AddressState";-ALTER TABLE "Aliases" DROP COLUMN "AddressZipCode";-ALTER TABLE "Aliases" DROP COLUMN "AddressCountry";-ALTER TABLE "Aliases" DROP COLUMN "Hobbies";-ALTER TABLE "Aliases" DROP COLUMN "PhoneMobile";-ALTER TABLE "Aliases" DROP COLUMN "BankAccountIBAN";`,-- 6: `-- Migration 1.3.1: Make Username Optional--- Make Username column nullable in Credentials table---- SQLite doesn't support ALTER COLUMN directly, so we need to recreate the table--- Create temporary table with new structure-CREATE TABLE "Credentials_temp" (- "Id" TEXT NOT NULL PRIMARY KEY,+);++INSERT INTO "ef_temp_Aliases" ("Id", "BirthDate", "CreatedAt", "Email", "FirstName", "Gender", "LastName", "NickName", "UpdatedAt")+SELECT "Id", "BirthDate", "CreatedAt", "Email", "FirstName", "Gender", "LastName", "NickName", "UpdatedAt"+FROM "Aliases";++COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;+DROP TABLE "Aliases";++ALTER TABLE "ef_temp_Aliases" RENAME TO "Aliases";++COMMIT;++PRAGMA foreign_keys = 1;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240805122422_1.3.0-UpdateIdentityStructure', '9.0.4');`,+ 6: `BEGIN TRANSACTION;+CREATE TABLE "ef_temp_Credentials" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Credentials" PRIMARY KEY,"AliasId" TEXT NOT NULL,- "Notes" TEXT,- "Username" TEXT, -- Made optional (nullable)"CreatedAt" TEXT NOT NULL,- "UpdatedAt" TEXT NOT NULL,+ "Notes" TEXT NULL,"ServiceId" TEXT NOT NULL,- FOREIGN KEY ("AliasId") REFERENCES "Aliases" ("Id") ON DELETE CASCADE,- FOREIGN KEY ("ServiceId") REFERENCES "Services" ("Id") ON DELETE CASCADE+ "UpdatedAt" TEXT NOT NULL,+ "Username" TEXT NULL,+ CONSTRAINT "FK_Credentials_Aliases_AliasId" FOREIGN KEY ("AliasId") REFERENCES "Aliases" ("Id") ON DELETE CASCADE,+ CONSTRAINT "FK_Credentials_Services_ServiceId" FOREIGN KEY ("ServiceId") REFERENCES "Services" ("Id") ON DELETE CASCADE);--- Copy data from old table to new table-INSERT INTO "Credentials_temp"-SELECT "Id", "AliasId", "Notes", "Username", "CreatedAt", "UpdatedAt", "ServiceId"+INSERT INTO "ef_temp_Credentials" ("Id", "AliasId", "CreatedAt", "Notes", "ServiceId", "UpdatedAt", "Username")+SELECT "Id", "AliasId", "CreatedAt", "Notes", "ServiceId", "UpdatedAt", "Username"FROM "Credentials";--- Drop old table+COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;DROP TABLE "Credentials";--- Rename temp table to original name-ALTER TABLE "Credentials_temp" RENAME TO "Credentials";+ALTER TABLE "ef_temp_Credentials" RENAME TO "Credentials";++COMMIT;++PRAGMA foreign_keys = 1;--- Recreate indexes+BEGIN TRANSACTION;CREATE INDEX "IX_Credentials_AliasId" ON "Credentials" ("AliasId");-CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");`,- 7: `-- Migration 1.4.0: Add Sync Support--- Add IsDeleted column to all tables for soft delete support+CREATE INDEX "IX_Credentials_ServiceId" ON "Credentials" ("ServiceId");++COMMIT;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240812141727_1.3.1-MakeUsernameOptional', '9.0.4');`,+ 7: `BEGIN TRANSACTION;+ALTER TABLE "Settings" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Services" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Passwords" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;-ALTER TABLE "Aliases" ADD COLUMN "IsDeleted" INTEGER NOT NULL DEFAULT 0;-ALTER TABLE "Services" ADD COLUMN "IsDeleted" INTEGER NOT NULL DEFAULT 0;-ALTER TABLE "Credentials" ADD COLUMN "IsDeleted" INTEGER NOT NULL DEFAULT 0;-ALTER TABLE "Attachment" ADD COLUMN "IsDeleted" INTEGER NOT NULL DEFAULT 0;-ALTER TABLE "Passwords" ADD COLUMN "IsDeleted" INTEGER NOT NULL DEFAULT 0;-ALTER TABLE "EncryptionKeys" ADD COLUMN "IsDeleted" INTEGER NOT NULL DEFAULT 0;-ALTER TABLE "Settings" ADD COLUMN "IsDeleted" INTEGER NOT NULL DEFAULT 0;`,+ALTER TABLE "EncryptionKeys" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;- 8: `-- Migration 1.4.1: Rename Attachments Plural--- Rename Attachment table to Attachments for consistency+ALTER TABLE "Credentials" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;+ALTER TABLE "Attachment" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++ALTER TABLE "Aliases" ADD "IsDeleted" INTEGER NOT NULL DEFAULT 0;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240916105320_1.4.0-AddSyncSupport', '9.0.4');++COMMIT;`,+ 8: `BEGIN TRANSACTION;ALTER TABLE "Attachment" RENAME TO "Attachments";--- Drop old index-DROP INDEX "IX_Attachment_CredentialId";+CREATE TABLE "ef_temp_Attachments" (+ "Id" TEXT NOT NULL CONSTRAINT "PK_Attachments" PRIMARY KEY,+ "Blob" BLOB NOT NULL,+ "CreatedAt" TEXT NOT NULL,+ "CredentialId" TEXT NOT NULL,+ "Filename" TEXT NOT NULL,+ "IsDeleted" INTEGER NOT NULL,+ "UpdatedAt" TEXT NOT NULL,+ CONSTRAINT "FK_Attachments_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+);++INSERT INTO "ef_temp_Attachments" ("Id", "Blob", "CreatedAt", "CredentialId", "Filename", "IsDeleted", "UpdatedAt")+SELECT "Id", "Blob", "CreatedAt", "CredentialId", "Filename", "IsDeleted", "UpdatedAt"+FROM "Attachments";++COMMIT;++PRAGMA foreign_keys = 0;++BEGIN TRANSACTION;+DROP TABLE "Attachments";++ALTER TABLE "ef_temp_Attachments" RENAME TO "Attachments";--- Create new index with correct name-CREATE INDEX "IX_Attachments_CredentialId" ON "Attachments" ("CredentialId");`,+COMMIT;- 9: `-- Migration 1.5.0: Add TOTP Codes--- Add TotpCodes table for 2FA support+PRAGMA foreign_keys = 1;+BEGIN TRANSACTION;+CREATE INDEX "IX_Attachments_CredentialId" ON "Attachments" ("CredentialId");++COMMIT;++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20240917191243_1.4.1-RenameAttachmentsPlural', '9.0.4');`,+ 9: `BEGIN TRANSACTION;CREATE TABLE "TotpCodes" (- "Id" TEXT NOT NULL PRIMARY KEY,+ "Id" TEXT NOT NULL CONSTRAINT "PK_TotpCodes" PRIMARY KEY,"Name" TEXT NOT NULL,"SecretKey" TEXT NOT NULL,"CredentialId" TEXT NOT NULL,"CreatedAt" TEXT NOT NULL,"UpdatedAt" TEXT NOT NULL,"IsDeleted" INTEGER NOT NULL,- FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE+ CONSTRAINT "FK_TotpCodes_Credentials_CredentialId" FOREIGN KEY ("CredentialId") REFERENCES "Credentials" ("Id") ON DELETE CASCADE);--- Create index-CREATE INDEX "IX_TotpCodes_CredentialId" ON "TotpCodes" ("CredentialId");`+CREATE INDEX "IX_TotpCodes_CredentialId" ON "TotpCodes" ("CredentialId");++INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")+VALUES ('20250310131554_1.5.0-AddTotpCodes', '9.0.4');++COMMIT;`,};diff --git a/shared/vault-sql/src/sql/VaultSqlGenerator.ts b/shared/vault-sql/src/sql/VaultSqlGenerator.tsnew file mode 100644index 000000000..e10848253--- /dev/null+++ b/shared/vault-sql/src/sql/VaultSqlGenerator.ts@@ -0,0 +1,261 @@+import { COMPLETE_SCHEMA_SQL, MIGRATION_SCRIPTS } from './SqlConstants';+import { VAULT_VERSIONS } from './VaultVersions';+import { type IVaultVersion } from '../types/VaultVersion';++/**+ * Result of SQL generation operations+ */+export interface ISqlGenerationResult {+ success: boolean;+ sqlCommands: string[];+ version: string;+ migrationNumber: number;+ error?: string;+}++/**+ * Information about vault version requirements+ */+export interface IVaultVersionInfo {+ currentVersion: string;+ currentMigrationNumber: number;+ targetVersion: string;+ targetMigrationNumber: number;+ needsUpgrade: boolean;+ availableUpgrades: IVaultVersion[];+}++/**+ * Vault SQL generator utility class+ * Provides SQL statements for vault creation and migration without database execution+ */+export class VaultSqlGenerator {+ /**+ * Get SQL commands to create a new vault with the latest schema+ */+ getCreateVaultSql(): ISqlGenerationResult {+ try {+ const sqlCommands = [+ 'PRAGMA foreign_keys = ON;',+ COMPLETE_SCHEMA_SQL,+ // Insert version tracking+ `INSERT INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")+ VALUES ('vault_version', '${VAULT_VERSIONS[VAULT_VERSIONS.length - 1].version}', datetime('now'), datetime('now'), 0);`,+ `INSERT INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")+ VALUES ('vault_migration_number', '${VAULT_VERSIONS[VAULT_VERSIONS.length - 1].revision}', datetime('now'), datetime('now'), 0);`+ ];++ return {+ success: true,+ sqlCommands,+ version: VAULT_VERSIONS[VAULT_VERSIONS.length - 1].version,+ migrationNumber: VAULT_VERSIONS[VAULT_VERSIONS.length - 1].revision+ };+ } catch (error) {+ return {+ success: false,+ sqlCommands: [],+ version: '0.0.0',+ migrationNumber: 0,+ error: error instanceof Error ? error.message : 'Unknown error creating vault SQL'+ };+ }+ }++ /**+ * Get SQL commands to upgrade vault from current version to target version+ */+ getUpgradeVaultSql(currentMigrationNumber: number, targetMigrationNumber?: number): ISqlGenerationResult {+ try {+ const targetMigration = targetMigrationNumber ?? VAULT_VERSIONS[VAULT_VERSIONS.length - 1].revision;+ const targetVersionInfo = VAULT_VERSIONS.find(v => v.revision === targetMigration);++ if (!targetVersionInfo) {+ return {+ success: false,+ sqlCommands: [],+ version: '0.0.0',+ migrationNumber: 0,+ error: `Target migration number ${targetMigration} not found`+ };+ }++ // If already at target version or beyond, no upgrade needed+ if (currentMigrationNumber >= targetMigration) {+ return {+ success: true,+ sqlCommands: [],+ version: targetVersionInfo.version,+ migrationNumber: targetMigration+ };+ }++ // Get migrations to apply+ const migrationsToApply = VAULT_VERSIONS.filter(+ v => v.revision > currentMigrationNumber &&+ v.revision <= targetMigration+ );++ const sqlCommands: string[] = ['PRAGMA foreign_keys = ON;'];++ // Add migration SQL commands+ for (const migration of migrationsToApply) {+ const migrationSql = MIGRATION_SCRIPTS[migration.revision];+ if (migrationSql) {+ sqlCommands.push(migrationSql);+ }+ }++ // Update version tracking+ sqlCommands.push(+ `INSERT OR REPLACE INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")+ VALUES ('vault_version', '${targetVersionInfo.version}', datetime('now'), datetime('now'), 0);`+ );+ sqlCommands.push(+ `INSERT OR REPLACE INTO "Settings" ("Key", "Value", "CreatedAt", "UpdatedAt", "IsDeleted")+ VALUES ('vault_migration_number', '${targetMigration}', datetime('now'), datetime('now'), 0);`+ );++ return {+ success: true,+ sqlCommands,+ version: targetVersionInfo.version,+ migrationNumber: targetMigration+ };+ } catch (error) {+ return {+ success: false,+ sqlCommands: [],+ version: '0.0.0',+ migrationNumber: 0,+ error: error instanceof Error ? error.message : 'Unknown error generating upgrade SQL'+ };+ }+ }++ /**+ * Get SQL commands to upgrade vault to latest version+ */+ getUpgradeToLatestSql(currentMigrationNumber: number): ISqlGenerationResult {+ return this.getUpgradeVaultSql(currentMigrationNumber);+ }++ /**+ * Get SQL commands to upgrade vault to a specific version+ */+ getUpgradeToVersionSql(currentMigrationNumber: number, targetVersion: string): ISqlGenerationResult {+ const targetVersionInfo = VAULT_VERSIONS.find(v => v.version === targetVersion);++ if (!targetVersionInfo) {+ return {+ success: false,+ sqlCommands: [],+ version: '0.0.0',+ migrationNumber: 0,+ error: `Target version ${targetVersion} not found`+ };+ }++ return this.getUpgradeVaultSql(currentMigrationNumber, targetVersionInfo.revision);+ }++ /**+ * Get SQL commands to check current vault version+ */+ getVersionCheckSql(): string[] {+ return [+ // Check if Settings table exists+ "SELECT name FROM sqlite_master WHERE type='table' AND name='Settings';",+ // Get vault version+ "SELECT Value FROM Settings WHERE Key = 'vault_version' AND IsDeleted = 0 LIMIT 1;",+ // Get migration number+ "SELECT Value FROM Settings WHERE Key = 'vault_migration_number' AND IsDeleted = 0 LIMIT 1;"+ ];+ }++ /**+ * Get SQL command to validate vault structure+ */+ getVaultValidationSql(): string {+ return `SELECT name FROM sqlite_master WHERE type='table' AND name IN+ ('Aliases', 'Services', 'Credentials', 'Passwords', 'Attachments', 'EncryptionKeys', 'Settings', 'TotpCodes');`;+ }++ /**+ * Parse vault version information from query results+ */+ parseVaultVersionInfo(+ settingsTableExists: boolean,+ versionResult?: string,+ migrationResult?: string+ ): IVaultVersionInfo {+ let currentVersion = '0.0.0';+ let currentMigrationNumber = 0;++ if (settingsTableExists) {+ if (versionResult) {+ currentVersion = versionResult;+ } else {+ // Has Settings table but no version info - likely v1.0.0 or v1.1.0+ currentVersion = '1.0.0';+ currentMigrationNumber = 1;+ }++ if (migrationResult) {+ currentMigrationNumber = parseInt(migrationResult, 10);+ }+ }++ const latestVersion = VAULT_VERSIONS[VAULT_VERSIONS.length - 1];+ const needsUpgrade = currentMigrationNumber < latestVersion.revision;+ const availableUpgrades = VAULT_VERSIONS.filter(v => v.revision > currentMigrationNumber);++ return {+ currentVersion,+ currentMigrationNumber,+ targetVersion: latestVersion.version,+ targetMigrationNumber: latestVersion.revision,+ needsUpgrade,+ availableUpgrades+ };+ }++ /**+ * Validate vault structure from table names+ */+ validateVaultStructure(tableNames: string[]): boolean {+ const requiredTables = ['Aliases', 'Services', 'Credentials', 'Passwords', 'Attachments', 'EncryptionKeys', 'Settings', 'TotpCodes'];+ const foundTables = tableNames.filter(name => requiredTables.includes(name));++ // Should have at least 5 core tables (some might not exist in older versions)+ return foundTables.length >= 5;+ }++ /**+ * Get all available vault versions+ */+ getAvailableVersions(): IVaultVersion[] {+ return [...VAULT_VERSIONS];+ }++ /**+ * Get current/latest vault version info+ */+ getCurrentVersion(): IVaultVersion {+ return VAULT_VERSIONS[VAULT_VERSIONS.length - 1];+ }++ /**+ * Get specific migration SQL by migration number+ */+ getMigrationSql(migrationNumber: number): string | undefined {+ return MIGRATION_SCRIPTS[migrationNumber];+ }++ /**+ * Get complete schema SQL for creating new vault+ */+ getCompleteSchemaeSql(): string {+ return COMPLETE_SCHEMA_SQL;+ }+}\ No newline at end of filediff --git a/shared/vault-sql/src/sql/VaultVersions.ts b/shared/vault-sql/src/sql/VaultVersions.tsnew file mode 100644index 000000000..2b863e1d3--- /dev/null+++ b/shared/vault-sql/src/sql/VaultVersions.ts@@ -0,0 +1,66 @@+/**+ * Vault version information+ * Auto-generated from EF Core migration filenames+ */++import { IVaultVersion } from "../types/VaultVersion";++/**+ * Available vault versions in chronological order+ */+export const VAULT_VERSIONS: IVaultVersion[] = [+ {+ revision: 1,+ version: '1.0.1',+ description: 'Empty Test Migration',+ releaseDate: '2024-07-08'+ },+ {+ revision: 2,+ version: '1.0.2',+ description: 'Change Email Column',+ releaseDate: '2024-07-11'+ },+ {+ revision: 3,+ version: '1.1.0',+ description: 'Add Pki Tables',+ releaseDate: '2024-07-29'+ },+ {+ revision: 4,+ version: '1.2.0',+ description: 'Add Settings Table',+ releaseDate: '2024-08-05'+ },+ {+ revision: 5,+ version: '1.3.0',+ description: 'Update Identity Structure',+ releaseDate: '2024-08-05'+ },+ {+ revision: 6,+ version: '1.3.1',+ description: 'Make Username Optional',+ releaseDate: '2024-08-12'+ },+ {+ revision: 7,+ version: '1.4.0',+ description: 'Add Sync Support',+ releaseDate: '2024-09-16'+ },+ {+ revision: 8,+ version: '1.4.1',+ description: 'Rename Attachments Plural',+ releaseDate: '2024-09-17'+ },+ {+ revision: 9,+ version: '1.5.0',+ description: 'Add Totp Codes',+ releaseDate: '2025-03-10'+ },+];diff --git a/shared/vault-sql/src/types/VaultVersion.ts b/shared/vault-sql/src/types/VaultVersion.tsindex 6b589973a..8085f4189 100644--- a/shared/vault-sql/src/types/VaultVersion.ts+++ b/shared/vault-sql/src/types/VaultVersion.ts@@ -3,14 +3,14 @@*/export interface IVaultVersion {/**- * The version number (e.g., "1.5.0")+ * The migration revision number*/- version: string;+ revision: number;/**- * The migration number+ * The version number (e.g., "1.5.0")*/- migrationNumber: number;+ version: string;/*** Description of changes in this version@@ -22,68 +22,3 @@ export interface IVaultVersion {*/releaseDate: string;}--/**- * Available vault versions in chronological order- */-export const VAULT_VERSIONS: IVaultVersion[] = [- {- version: '1.0.0',- migrationNumber: 1,- description: 'Initial database schema with core vault functionality',- releaseDate: '2024-07-08'- },- {- version: '1.0.2',- migrationNumber: 2,- description: 'Email column rename for improved clarity',- releaseDate: '2024-07-11'- },- {- version: '1.1.0',- migrationNumber: 3,- description: 'PKI support with encryption keys table',- releaseDate: '2024-07-29'- },- {- version: '1.2.0',- migrationNumber: 4,- description: 'Settings table for user preferences',- releaseDate: '2024-08-05'- },- {- version: '1.3.0',- migrationNumber: 5,- description: 'Identity structure simplification',- releaseDate: '2024-08-05'- },- {- version: '1.3.1',- migrationNumber: 6,- description: 'Optional username support',- releaseDate: '2024-08-12'- },- {- version: '1.4.0',- migrationNumber: 7,- description: 'Soft delete support for synchronization',- releaseDate: '2024-09-16'- },- {- version: '1.4.1',- migrationNumber: 8,- description: 'Attachment table rename for consistency',- releaseDate: '2024-09-17'- },- {- version: '1.5.0',- migrationNumber: 9,- description: 'TOTP (2FA) support',- releaseDate: '2025-03-10'- }-];--/**- * Current/latest vault version- */-export const CURRENT_VAULT_VERSION = VAULT_VERSIONS[VAULT_VERSIONS.length - 1];diff --git a/shared/vault-sql/tsconfig.json b/shared/vault-sql/tsconfig.jsonindex 8b023c515..4c8b07964 100644--- a/shared/vault-sql/tsconfig.json+++ b/shared/vault-sql/tsconfig.json@@ -6,14 +6,14 @@"declarationMap": true,"module": "ESNext","target": "ES2020",- "lib": ["ES2020"],+ "lib": ["ES2020", "DOM"],"strict": true,"moduleResolution": "bundler",+ "resolveJsonModule": true,"esModuleInterop": true,"isolatedModules": true,"forceConsistentCasingInFileNames": true,- "baseUrl": ".",- "skipLibCheck": true,+ "baseUrl": "."},- "include": ["src/**/*"]+ "include": ["src/**/*.ts"]}diff --git a/shared/vault-sql/tsup.config.ts b/shared/vault-sql/tsup.config.tsindex cb5bcd2a3..38953dcaf 100644--- a/shared/vault-sql/tsup.config.ts+++ b/shared/vault-sql/tsup.config.ts@@ -1,15 +1,14 @@import { defineConfig } from 'tsup';export default defineConfig({- entry: ['src/**/index.ts'],- format: ['esm'],+ entry: ['src/index.ts'],+ format: ['cjs', 'esm'],+ target: 'es2020',dts: true,- splitting: false,- sourcemap: true,clean: true,- treeshake: true,- target: 'es2020',+ splitting: false,minify: false,+ sourcemap: true,banner: {js: '// <auto-generated>\n// This file was automatically generated. Do not edit manually.\n',}