Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add shared model compilation to csharp, swift and kotlin for FieldKey enum (#1404)
Leendert de Borstfe21811242c3
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/FieldKey.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/FieldKey.ktnew file mode 100644index 000000000..9df3ba34c--- /dev/null+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/FieldKey.kt@@ -0,0 +1,156 @@+// <auto-generated />+// This file is auto-generated from shared/models/src/vault/FieldKey.ts+// Do not edit this file directly. Run 'npm run generate:models' to regenerate.++package net.aliasvault.app.vaultstore.models++/**+ * System field keys for the field-based data model.+ * These keys map to FieldDefinition.FieldKey values.+ */+object FieldKey {+ /**+ * Type: Text.+ */+ const val LOGIN_USERNAME = "login.username"++ /**+ * Type: Password.+ */+ const val LOGIN_PASSWORD = "login.password"++ /**+ * Type: Text.+ */+ const val LOGIN_NOTES = "login.notes"++ /**+ * Type: URL.+ */+ const val LOGIN_URL = "login.url"++ /**+ * Type: Text.+ */+ const val LOGIN_RECOVERY_CODES = "login.recovery_codes"++ /**+ * Type: Text.+ */+ const val CARD_NUMBER = "card.number"++ /**+ * Type: Text.+ */+ const val CARD_CARDHOLDER_NAME = "card.cardholder_name"++ /**+ * Type: Text.+ */+ const val CARD_EXPIRY_MONTH = "card.expiry_month"++ /**+ * Type: Text.+ */+ const val CARD_EXPIRY_YEAR = "card.expiry_year"++ /**+ * Type: Password.+ */+ const val CARD_CVV = "card.cvv"++ /**+ * Type: Password.+ */+ const val CARD_PIN = "card.pin"++ /**+ * Type: Text.+ */+ const val IDENTITY_TITLE = "identity.title"++ /**+ * Type: Text.+ */+ const val IDENTITY_FIRST_NAME = "identity.first_name"++ /**+ * Type: Text.+ */+ const val IDENTITY_MIDDLE_NAME = "identity.middle_name"++ /**+ * Type: Text.+ */+ const val IDENTITY_LAST_NAME = "identity.last_name"++ /**+ * Type: Email.+ */+ const val IDENTITY_EMAIL = "identity.email"++ /**+ * Type: Text.+ */+ const val IDENTITY_PHONE_NUMBERS = "identity.phone_numbers"++ /**+ * Type: Text.+ */+ const val IDENTITY_ADDRESS_LINE1 = "identity.address_line1"++ /**+ * Type: Text.+ */+ const val IDENTITY_ADDRESS_LINE2 = "identity.address_line2"++ /**+ * Type: Text.+ */+ const val IDENTITY_CITY = "identity.city"++ /**+ * Type: Text.+ */+ const val IDENTITY_STATE = "identity.state"++ /**+ * Type: Text.+ */+ const val IDENTITY_POSTAL_CODE = "identity.postal_code"++ /**+ * Type: Text.+ */+ const val IDENTITY_COUNTRY = "identity.country"++ /**+ * Type: Email.+ */+ const val ALIAS_EMAIL = "alias.email"++ /**+ * Type: Text.+ */+ const val ALIAS_FIRST_NAME = "alias.first_name"++ /**+ * Type: Text.+ */+ const val ALIAS_LAST_NAME = "alias.last_name"++ /**+ * Type: Text.+ */+ const val ALIAS_NICKNAME = "alias.nickname"++ /**+ * Type: Text.+ */+ const val ALIAS_GENDER = "alias.gender"++ /**+ * Type: Date.+ */+ const val ALIAS_BIRTHDATE = "alias.birthdate"+}diff --git a/apps/mobile-app/ios/VaultModels/FieldKey.swift b/apps/mobile-app/ios/VaultModels/FieldKey.swiftnew file mode 100644index 000000000..7e123f609--- /dev/null+++ b/apps/mobile-app/ios/VaultModels/FieldKey.swift@@ -0,0 +1,96 @@+// <auto-generated />+// This file is auto-generated from shared/models/src/vault/FieldKey.ts+// Do not edit this file directly. Run 'npm run generate:models' to regenerate.++import Foundation++/// System field keys for the field-based data model.+/// These keys map to FieldDefinition.FieldKey values.+public struct FieldKey {+ /// Type: Text+ public static let loginUsername = "login.username"++ /// Type: Password+ public static let loginPassword = "login.password"++ /// Type: Text+ public static let loginNotes = "login.notes"++ /// Type: URL+ public static let loginUrl = "login.url"++ /// Type: Text+ public static let loginRecoveryCodes = "login.recovery_codes"++ /// Type: Text+ public static let cardNumber = "card.number"++ /// Type: Text+ public static let cardCardholderName = "card.cardholder_name"++ /// Type: Text+ public static let cardExpiryMonth = "card.expiry_month"++ /// Type: Text+ public static let cardExpiryYear = "card.expiry_year"++ /// Type: Password+ public static let cardCvv = "card.cvv"++ /// Type: Password+ public static let cardPin = "card.pin"++ /// Type: Text+ public static let identityTitle = "identity.title"++ /// Type: Text+ public static let identityFirstName = "identity.first_name"++ /// Type: Text+ public static let identityMiddleName = "identity.middle_name"++ /// Type: Text+ public static let identityLastName = "identity.last_name"++ /// Type: Email+ public static let identityEmail = "identity.email"++ /// Type: Text+ public static let identityPhoneNumbers = "identity.phone_numbers"++ /// Type: Text+ public static let identityAddressLine1 = "identity.address_line1"++ /// Type: Text+ public static let identityAddressLine2 = "identity.address_line2"++ /// Type: Text+ public static let identityCity = "identity.city"++ /// Type: Text+ public static let identityState = "identity.state"++ /// Type: Text+ public static let identityPostalCode = "identity.postal_code"++ /// Type: Text+ public static let identityCountry = "identity.country"++ /// Type: Email+ public static let aliasEmail = "alias.email"++ /// Type: Text+ public static let aliasFirstName = "alias.first_name"++ /// Type: Text+ public static let aliasLastName = "alias.last_name"++ /// Type: Text+ public static let aliasNickname = "alias.nickname"++ /// Type: Text+ public static let aliasGender = "alias.gender"++ /// Type: Date+ public static let aliasBirthdate = "alias.birthdate"+}diff --git a/apps/server/AliasVault.Client/Main/Models/Vault/FieldKey.cs b/apps/server/AliasVault.Client/Main/Models/Vault/FieldKey.csnew file mode 100644index 000000000..7ffe5fb1e--- /dev/null+++ b/apps/server/AliasVault.Client/Main/Models/Vault/FieldKey.cs@@ -0,0 +1,157 @@+// <auto-generated />+// This file is auto-generated from shared/models/src/vault/FieldKey.ts+// Do not edit this file directly. Run 'npm run generate:models' to regenerate.++namespace AliasClientDb.Models;++/// <summary>+/// System field keys for the field-based data model.+/// These keys map to FieldDefinition.FieldKey values.+/// </summary>+public static class FieldKey+{+ /// <summary>+ /// Type: Text+ /// </summary>+ public const string LoginUsername = "login.username";++ /// <summary>+ /// Type: Password+ /// </summary>+ public const string LoginPassword = "login.password";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string LoginNotes = "login.notes";++ /// <summary>+ /// Type: URL+ /// </summary>+ public const string LoginUrl = "login.url";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string LoginRecoveryCodes = "login.recovery_codes";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string CardNumber = "card.number";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string CardCardholderName = "card.cardholder_name";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string CardExpiryMonth = "card.expiry_month";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string CardExpiryYear = "card.expiry_year";++ /// <summary>+ /// Type: Password+ /// </summary>+ public const string CardCvv = "card.cvv";++ /// <summary>+ /// Type: Password+ /// </summary>+ public const string CardPin = "card.pin";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string IdentityTitle = "identity.title";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string IdentityFirstName = "identity.first_name";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string IdentityMiddleName = "identity.middle_name";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string IdentityLastName = "identity.last_name";++ /// <summary>+ /// Type: Email+ /// </summary>+ public const string IdentityEmail = "identity.email";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string IdentityPhoneNumbers = "identity.phone_numbers";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string IdentityAddressLine1 = "identity.address_line1";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string IdentityAddressLine2 = "identity.address_line2";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string IdentityCity = "identity.city";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string IdentityState = "identity.state";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string IdentityPostalCode = "identity.postal_code";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string IdentityCountry = "identity.country";++ /// <summary>+ /// Type: Email+ /// </summary>+ public const string AliasEmail = "alias.email";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string AliasFirstName = "alias.first_name";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string AliasLastName = "alias.last_name";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string AliasNickname = "alias.nickname";++ /// <summary>+ /// Type: Text+ /// </summary>+ public const string AliasGender = "alias.gender";++ /// <summary>+ /// Type: Date+ /// </summary>+ public const string AliasBirthdate = "alias.birthdate";+}diff --git a/shared/models/MODEL_GENERATION.md b/shared/models/MODEL_GENERATION.mdnew file mode 100644index 000000000..228dc8d91--- /dev/null+++ b/shared/models/MODEL_GENERATION.md@@ -0,0 +1,121 @@+# Model Generation++This directory contains scripts for generating model files across multiple languages from a single source of truth.++## Overview++AliasVault is a multi-platform application with:+- **TypeScript** (Browser Extension & Mobile App)+- **C#/.NET** (WASM Client & Server)+- **Swift** (iOS native modules)+- **Kotlin** (Android native modules)++To maintain consistency and reduce duplication, we generate models from TypeScript sources.++## Current Implementation++### FieldKey Generation++The `scripts/generate-field-keys.cjs` script generates `FieldKey` constants from the TypeScript source.++**Source**: `src/vault/FieldKey.ts`++**Generated files**:+- **C#**: `apps/server/Databases/AliasClientDb/Models/FieldKey.cs`+- **Swift**: `apps/mobile-app/ios/AliasVault/VaultModels/FieldKey.swift`+- **Kotlin**: `apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/FieldKey.kt`++**Usage**:+```bash+# From repository root+npm run generate:models++# Or from shared/models directory+./build.sh # Runs build + generation automatically++# Or run directly+node scripts/generate-field-keys.cjs+```++### Naming Conventions++The generator automatically applies platform-specific naming conventions:++| TypeScript | C# | Swift | Kotlin |+|------------------|------------------|------------------|---------------------|+| `LoginUsername` | `LoginUsername` | `loginUsername` | `LOGIN_USERNAME` |+| `CardNumber` | `CardNumber` | `cardNumber` | `CARD_NUMBER` |+| `AliasEmail` | `AliasEmail` | `aliasEmail` | `ALIAS_EMAIL` |++- **TypeScript/C#**: PascalCase+- **Swift**: camelCase+- **Kotlin**: SCREAMING_SNAKE_CASE++## Future: Complex Models with quicktype++For complex DTOs that require serialization/deserialization (e.g., API models, database entities), we have `quicktype` installed and ready to use.++**quicktype** can generate:+- Full classes/structs with properties+- JSON serialization/deserialization+- Type-safe parsing+- Support for nullable types, enums, unions, etc.++### Example quicktype usage:++```bash+# From JSON Schema+npx quicktype schema.json -o Model.cs --lang csharp+npx quicktype schema.json -o Model.swift --lang swift+npx quicktype schema.json -o Model.kt --lang kotlin++# From TypeScript+npx quicktype source.ts -o Model.cs --lang csharp --src-lang typescript++# From JSON sample+npx quicktype sample.json -o Model.cs --lang csharp+```++## Adding New Generators++When adding new model generators:++1. Create a new script in `shared/models/scripts/generate-{model-name}.cjs`+2. Follow the pattern from `generate-field-keys.cjs`+3. Add the generator call to `shared/models/build.sh`:+ ```bash+ node scripts/generate-{model-name}.cjs+ ```+4. The script will automatically run when:+ - Running `./build-and-distribute.sh` from the shared directory+ - Running `./build.sh` from `shared/models`+ - Running `npm run generate:models` from repository root+5. Document it here++## Guidelines++### When to use custom scripts (like `generate-field-keys.js`):+- Simple constants or enums+- String literals that map 1:1 across languages+- Cases where quicktype generates unnecessary complexity++### When to use quicktype:+- Complex DTOs with nested objects+- Models that need JSON serialization/deserialization+- API request/response models+- Database entities shared across platforms++## CI/CD Integration++Consider adding model generation to your CI pipeline to ensure generated files are always up-to-date:++```yaml+# Example GitHub Actions workflow+- name: Generate models+ run: npm run generate:models++- name: Check for changes+ run: git diff --exit-code || (echo "Generated models are out of sync!" && exit 1)+```++This ensures developers can't forget to regenerate models after changing source files.diff --git a/shared/models/README.md b/shared/models/README.mdnew file mode 100644index 000000000..2ec1616c1--- /dev/null+++ b/shared/models/README.md@@ -0,0 +1,23 @@+# Shared Models++This package serves as the **single source of truth** for data models across all AliasVault platforms.++## What This Does++This package performs two key functions:++### 1. TypeScript Distribution (As-Is)+Builds and copies TypeScript models directly to:+- **Browser Extension**: `apps/browser-extension/src/utils/dist/shared/models`+- **Mobile App**: `apps/mobile-app/utils/dist/shared/models`++These apps consume the TypeScript models as-is, enabling type-safe development with no manual synchronization needed.++### 2. Native Code Generation (Transformed)+Automatically generates platform-specific models from TypeScript sources:++| Source | Generated Output | Language |+|--------|-----------------|----------|+| `src/vault/FieldKey.ts` | `apps/server/Databases/AliasClientDb/Models/FieldKey.cs` | C# |+| `src/vault/FieldKey.ts` | `apps/mobile-app/ios/AliasVault/VaultModels/FieldKey.swift` | Swift |+| `src/vault/FieldKey.ts` | `apps/mobile-app/android/.../vaultstore/models/FieldKey.kt` | Kotlin |diff --git a/shared/models/build.sh b/shared/models/build.shindex ddad378df..3200450d3 100755--- a/shared/models/build.sh+++ b/shared/models/build.sh@@ -16,6 +16,10 @@ package_path="."echo "📦 Building $package_name..."npm install && npm run lint && npm run build+echo ""+echo "🔄 Generating platform-specific models (C#, Swift, Kotlin)..."+node scripts/generate-field-keys.cjs+dist_path="dist"files_to_copy=("webapi" "vault" "metadata")diff --git a/shared/models/scripts/generate-field-keys.cjs b/shared/models/scripts/generate-field-keys.cjsnew file mode 100755index 000000000..4cec2413f--- /dev/null+++ b/shared/models/scripts/generate-field-keys.cjs@@ -0,0 +1,194 @@+#!/usr/bin/env node+/**+ * Generates FieldKey constants for C#, Swift, and Kotlin from TypeScript source.+ */++const fs = require('fs');+const path = require('path');++// Paths+const REPO_ROOT = path.join(__dirname, '../../..');+const TS_SOURCE = path.join(REPO_ROOT, 'shared/models/src/vault/FieldKey.ts');+const CS_OUTPUT = path.join(REPO_ROOT, 'apps/server/AliasVault.Client/Main/Models/Vault/FieldKey.cs');+const SWIFT_OUTPUT = path.join(REPO_ROOT, 'apps/mobile-app/ios/VaultModels/FieldKey.swift');+const KOTLIN_OUTPUT = path.join(REPO_ROOT, 'apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/FieldKey.kt');++/**+ * Parse the TypeScript FieldKey.ts file and extract constants+ */+function parseTypeScriptFieldKeys(tsContent) {+ const fieldKeys = {};++ // Extract field comments+ const lines = tsContent.split('\n');+ let currentComment = '';++ for (let i = 0; i < lines.length; i++) {+ const line = lines[i].trim();++ // Capture JSDoc comments+ if (line.startsWith('/**') || line.startsWith('*')) {+ const commentMatch = line.match(/\*\s*(.+)/);+ if (commentMatch && !commentMatch[1].startsWith('/')) {+ currentComment = commentMatch[1].trim();+ }+ }++ // Match field definition+ const fieldMatch = line.match(/^(\w+):\s*'([^']+)',?$/);+ if (fieldMatch) {+ const [, name, value] = fieldMatch;+ fieldKeys[name] = {+ value,+ comment: currentComment+ };+ currentComment = '';+ }+ }++ return fieldKeys;+}++/**+ * Generate C# static class+ */+function generateCSharp(fieldKeys) {+ const header = `// <auto-generated />+// This file is auto-generated from shared/models/src/vault/FieldKey.ts+// Do not edit this file directly. Run 'npm run generate:models' to regenerate.++namespace AliasClientDb.Models;++/// <summary>+/// System field keys for the field-based data model.+/// These keys map to FieldDefinition.FieldKey values.+/// </summary>+public static class FieldKey+{`;++ const fields = Object.entries(fieldKeys)+ .map(([name, { value, comment }]) => {+ return ` /// <summary>+ /// ${comment}+ /// </summary>+ public const string ${name} = "${value}";`;+ })+ .join('\n\n');++ const footer = `+}+`;++ return header + '\n' + fields + footer;+}++/**+ * Generate Swift enum+ */+function generateSwift(fieldKeys) {+ const header = `// <auto-generated />+// This file is auto-generated from shared/models/src/vault/FieldKey.ts+// Do not edit this file directly. Run 'npm run generate:models' to regenerate.++import Foundation++/// System field keys for the field-based data model.+/// These keys map to FieldDefinition.FieldKey values.+public struct FieldKey {`;++ const fields = Object.entries(fieldKeys)+ .map(([name, { value, comment }]) => {+ // Convert PascalCase to camelCase for Swift+ const swiftName = name.charAt(0).toLowerCase() + name.slice(1);+ return ` /// ${comment}+ public static let ${swiftName} = "${value}"`;+ })+ .join('\n\n');++ const footer = `+}+`;++ return header + '\n' + fields + footer;+}++/**+ * Generate Kotlin object+ */+function generateKotlin(fieldKeys) {+ const header = `// <auto-generated />+// This file is auto-generated from shared/models/src/vault/FieldKey.ts+// Do not edit this file directly. Run 'npm run generate:models' to regenerate.++package net.aliasvault.app.vaultstore.models++/**+ * System field keys for the field-based data model.+ * These keys map to FieldDefinition.FieldKey values.+ */+object FieldKey {`;++ const fields = Object.entries(fieldKeys)+ .map(([name, { value, comment }]) => {+ // Convert to SCREAMING_SNAKE_CASE for Kotlin constants+ const kotlinName = name.replace(/([A-Z])/g, '_$1').toUpperCase().replace(/^_/, '');+ // Ensure comment ends with a period for Kotlin detekt+ const kotlinComment = comment.endsWith('.') ? comment : `${comment}.`;+ return ` /**+ * ${kotlinComment}+ */+ const val ${kotlinName} = "${value}"`;+ })+ .join('\n\n');++ const footer = `+}+`;++ return header + '\n' + fields + footer;+}++/**+ * Ensure directory exists+ */+function ensureDir(filePath) {+ const dir = path.dirname(filePath);+ if (!fs.existsSync(dir)) {+ fs.mkdirSync(dir, { recursive: true });+ }+}++/**+ * Main execution+ */+function main() {++ // Read TypeScript source+ if (!fs.existsSync(TS_SOURCE)) {+ throw new Error(`Source file not found: ${TS_SOURCE}`);+ }++ const tsContent = fs.readFileSync(TS_SOURCE, 'utf8');+ const fieldKeys = parseTypeScriptFieldKeys(tsContent);++ if (Object.keys(fieldKeys).length === 0) {+ throw new Error('No field keys found in source file');+ }++ // Generate C#+ ensureDir(CS_OUTPUT);+ const csContent = generateCSharp(fieldKeys);+ fs.writeFileSync(CS_OUTPUT, csContent, 'utf8');++ // Generate Swift+ ensureDir(SWIFT_OUTPUT);+ const swiftContent = generateSwift(fieldKeys);+ fs.writeFileSync(SWIFT_OUTPUT, swiftContent, 'utf8');++ // Generate Kotlin+ ensureDir(KOTLIN_OUTPUT);+ const kotlinContent = generateKotlin(fieldKeys);+ fs.writeFileSync(KOTLIN_OUTPUT, kotlinContent, 'utf8');+}++main();