Compare commits

...

107 Commits

Author SHA1 Message Date
Trent Larson 59d711bd90 make fixes to help my Mac build electron 6 days ago
Matthew Raymer c355de6e33 Merge branch 'sql-absurd-sql-further' of ssh://173.199.124.46:222/trent_larson/crowd-funder-for-time-pwa into sql-absurd-sql-further 6 days ago
Matthew Raymer 28c114a2c7 fix(sqlite): resolve migration issues and enhance documentation 6 days ago
Trent Larson dabfe33fbe add Python dependency for electron on Mac 6 days ago
Trent Larson d8f2587d1c fix some errors and correct recent type duplications & bloat 6 days ago
Matthew Raymer 3946a8a27a fix(database): improve SQLite connection handling and initialization 6 days ago
Trent Larson 4c40b80718 rename script files that would fail in the prebuild step 7 days ago
Trent Larson 74989c2b64 fix linting 7 days ago
Trent Larson 7e17b41444 rename a js config file to avoid an error running lint 7 days ago
Trent Larson 83acb028c7 fix more logic for tests 7 days ago
Matthew Raymer 786f07e067 feat(electron): Implement SQLite database initialization with proper logging 7 days ago
Matthew Raymer 710cc1683c fix(sqlite): Standardize connection options and improve error handling 7 days ago
Matthew Raymer ebef5d6c8d feat(sqlite): Initialize database with complete schema and PRAGMAs 7 days ago
Matthew Raymer 43ea7ee610 Merge branch 'sql-absurd-sql-further' of ssh://173.199.124.46:222/trent_larson/crowd-funder-for-time-pwa into sql-absurd-sql-further 1 week ago
Matthew Raymer 57191df416 feat(sqlite): Database file creation working, connection pending 1 week ago
Trent Larson 644593a5f4 fix linting 1 week ago
Matthew Raymer 900c2521c7 WIP: Improve SQLite initialization and error handling 1 week ago
Matthew Raymer 182cff2b16 fix(typescript): resolve linter violations and improve type safety 1 week ago
Matthew Raymer 3b4ef908f3 feat(electron): improve window and database initialization 1 week ago
Matthew Raymer a5a9e15ece WIP: Refactor Electron SQLite initialization and database path handling 1 week ago
Matthew Raymer a6d8f0eb8a fix(electron): assign sqlitePlugin globally and improve error logging 1 week ago
Matthew Raymer 3997a88b44 fix: rename postcss.config.js to .cjs for ES module compatibility 1 week ago
Trent Larson 5eeeae32c6 fix some incorrect logic & things AI hallucinated 1 week ago
Matthew Raymer d9895086e6 experiment(electron): different vite build script for web application 1 week ago
Matthew Raymer fb8d1cb8b2 fix(electron): add null check for devToolsWebContents to prevent TypeScript error 1 week ago
Matthew Raymer 70c0edbed0 fix: SQLite plugin initialization in Electron main process 1 week ago
Matthew Raymer 55cc08d675 chore: linting 1 week ago
Matthew Raymer 688a5be76e Merge branch 'sql-absurd-sql-further' of ssh://173.199.124.46:222/trent_larson/crowd-funder-for-time-pwa into sql-absurd-sql-further 1 week ago
Matthew Raymer 014341f320 fix(electron): simplify SQLite plugin initialization 1 week ago
Matthew Raymer 1d5e062c76 fix(electron): app loads 1 week ago
Matthew Raymer 2c5c15108a debug(electron): missing main.ts 1 week ago
Matthew Raymer 26df0fb671 debug(electron): app index loads but problem with preload script 1 week ago
Trent Larson ef3bfcdbd2 fix linting 1 week ago
Trent Larson ec1f27bab1 fix more logging cleanup errors 1 week ago
Trent Larson 01c33069c4 fix more of the logging & log display 1 week ago
Trent Larson c637d39dc9 fix log cleanup check to actually pay attention to limit 1 week ago
Trent Larson 3e90bafbd1 correct & simplify the DB logging 1 week ago
Matthew Raymer d2c3e5db05 fix: one lint that got past me 1 week ago
Matthew Raymer e824fcce2e fix: linting issues 1 week ago
Matthew Raymer f2c49872a6 fix: resolve TypeScript errors in database service implementation 1 week ago
Matthew Raymer 229d9184b2 WIP: BROKEN FOR ELECTRON: Fixes in progress 1 week ago
Matthew Raymer 29908b77e3 feat(types): add comprehensive type definitions for @jlongster/sql.js 1 week ago
Matthew Raymer 16cad04e5c WIP: fix(AbsurdSqlDatabaseService) fixes to typing and other curious beasts 1 week ago
Matthew Raymer e4f859a116 fix: update offerGiverDid to use credentialSubject.offeredBy 1 week ago
Matthew Raymer 7f17a3d9c7 refactor: remove unused imports and parameters in passkeyDidPeer.ts 1 week ago
Matthew Raymer 2d4d9691ca fix: use challenge parameter in verifyJwtWebCrypto preimage 1 week ago
Matthew Raymer 63575b36ed fix: use challenge parameter in verifyJwtP256 preimage 1 week ago
Matthew Raymer 2eb46367bc fix: resolve TypeScript errors in passkeyDidPeer.ts 1 week ago
Matthew Raymer cea0456148 fix: resolve type conflicts in AccountKeyInfo and KeyMeta imports 1 week ago
Matthew Raymer 6f5db13a49 fix: consolidate KeyMeta interface and improve type safety 1 week ago
Matthew Raymer 068662625d fix: resolve type compatibility in offerGiverDid 1 week ago
Matthew Raymer 23627835f9 refactor: improve type safety in endorser server and common interfaces 1 week ago
Matthew Raymer f1ba6f9231 fix(endorserServer): improve type safety in claim handling 1 week ago
Matthew Raymer 137fce3e30 fix(endorserServer): improve type safety and error handling 1 week ago
Matthew Raymer 7166dadbc0 fix(types): correct type imports and improve null safety 1 week ago
Matthew Raymer bc274bdf7f fix(types): improve account type safety and metadata handling 1 week ago
Matthew Raymer 082f8c0126 feat(QRScanner): implement QRScannerOptions in WebInlineQRScanner 1 week ago
Matthew Raymer fd09c7e426 fix(deepLinks): improve route validation and type safety 1 week ago
Matthew Raymer be40643379 fix: unused element 1 week ago
Matthew Raymer 835a270e65 feat(qr-scanner): Add camera state management to CapacitorQRScanner 1 week ago
Matthew Raymer 13682a1930 fix(db): add type declarations for SQL.js and absurd-sql modules 1 week ago
Matthew Raymer 669a66c24c fix(db): improve type safety in AbsurdSqlDatabaseService 1 week ago
Matthew Raymer 13505b539e fix(db): resolve type compatibility in AbsurdSqlDatabaseService 1 week ago
Matthew Raymer 07ac340733 feat(capacitor): implement storage permission checks for file operations 1 week ago
Matthew Raymer ba2b2fc543 fix: placeholder for PyWebViewPlatformService writeAndShareFile 1 week ago
Trent Larson 21184e7625 fix spelling of SQLite module for iOS 1 week ago
Trent Larson 8d1511e38f convert all remaining DB writes & reads to SQL (with successful registration & claim) 1 week ago
Matthew Raymer b18112b869 WIP: disabling absurd-sql when using Capacitor SQLite 2 weeks ago
Matthew Raymer a228a9b1c0 fix: add requirements for capacitor/sqlite 2 weeks ago
Matthew Raymer 1560ff0829 feature: fleshed out capacitor and electron database operators 2 weeks ago
Trent Larson 7de4125eb7 add SQL DB access to everywhere we are using the DB, up to the "C" files 2 weeks ago
Matthew Raymer 81d4f0c762 fix: resolve PWA build issues with SQL.js worker files 2 weeks ago
Trent Larson 4c1b4fe651 fix linting 2 weeks ago
Matthew Raymer e63541ef53 fix: update ESLint and VS Code settings 2 weeks ago
Trent Larson 0bfc18c385 add encryption & decryption for the sensitive identity & mnemonic in SQL DB 2 weeks ago
Matthew Raymer 35f5df6b6b fix: move lexical declarations outside case blocks 2 weeks ago
Matthew Raymer 0f1ac2b230 fix: move lexical declarations outside case blocks in AbsurdSqlDatabaseService 2 weeks ago
Trent Larson 3c0bdeaed3 remove debugging console statements 2 weeks ago
Trent Larson 11f2527b04 start adding the SQL approach to files, also using the Dexie approach if desired 2 weeks ago
Trent Larson 5d8175aeeb add encryption for the two SQL columns, replace basic DB utils, add USE_DEXIE_DB flag, and start adding SQL everywhere 2 weeks ago
Trent Larson b6b95cb0d0 remove unused redirect to start page (now that we're creating an ID up front) 2 weeks ago
Trent Larson 655c5188a4 add queueing to the DB service so that requests get processed in order 2 weeks ago
Trent Larson 8b7451330f remove possibility of failing a migration script and then succeeding on later ones 2 weeks ago
Trent Larson b8fbc3f7a6 fix console error about "window" unavailable due to service worker 2 weeks ago
Trent Larson 92dadba1cb rename the absurd-sql-specific items for clarity 2 weeks ago
Trent Larson 3a6f585de0 adjust so DB calls go to the factory 2 weeks ago
Trent Larson 2647c5a77d fix migrations logging error 2 weeks ago
Matt Raymer 682fceb1c6 Merge remote-tracking branch 'refs/remotes/origin/sql-absurd-sql' into sql-absurd-sql 2 weeks ago
Matt Raymer e0013008b4 refactor: improve type safety and browser compatibility - Replace any types with SqlValue[] in migration system - Add browser-compatible implementations of Node.js modules (crypto, fs, path) - Update Vite config to handle Node.js module polyfills - Remove outdated migration documentation files 2 weeks ago
Trent Larson 0674d98670 fix BUILDING instructions 2 weeks ago
Matt Raymer ee441d1aea refactor(db): improve type safety in migration system 2 weeks ago
Matt Raymer 75f6e99200 chore: update migration documents and move to new home 2 weeks ago
Matt Raymer 52c9e57ef4 Merge remote-tracking branch 'refs/remotes/origin/sql-absurd-sql' into sql-absurd-sql 2 weeks ago
Trent Larson 603823d808 add to build instructions for electron on mac 2 weeks ago
Trent Larson 5f24f4975d fix linting 2 weeks ago
Trent Larson 5057d7d07f don't always apply the camera-implementation cursor rules 2 weeks ago
Trent Larson 946e88d903 add a input area for arbitrary SQL on the test page 2 weeks ago
Matt Raymer cbfb1ebf57 Merge branch 'new-storage' into sql-absurd-sql 2 weeks ago
Trent Larson a38934e38d fix problems with race conditions and multiple DatabaseService instances 2 weeks ago
Trent Larson a3bdcfd168 fix problem with initialization & refactor types 2 weeks ago
Trent Larson 83771caee1 add more to the inital migration, and refactor the locations of types 2 weeks ago
Trent Larson da35b225cd remove unused setting 2 weeks ago
Trent Larson 8c3920e108 add DB setup with migrations 2 weeks ago
Trent Larson 54f269054f fix error loading WASM file 2 weeks ago
Matt Raymer 574520d9b3 feat(db): Implement SQLite database layer with migration support 2 weeks ago
Trent Larson 6556eb55a3 add the other pieces for the previous commit 2 weeks ago
Trent Larson 634e2bb2fb try absurd-sql, which fails in browser with: SyntaxError: Cannot use import statement outside a module (at registerSQLWorker.js... 2 weeks ago
  1. 153
      .cursor/rules/absurd-sql.mdc
  2. 2
      .cursor/rules/crowd-funder-for-time-pwa/docs/camera-implementation.mdc
  3. 1
      .env.development
  4. 6
      .env.example
  5. 1
      .env.production
  6. 1
      .env.staging
  7. 6
      .eslintrc.cjs
  8. 6
      BUILDING.md
  9. 2
      android/app/build.gradle
  10. 1
      android/app/capacitor.build.gradle
  11. 35
      android/app/src/main/assets/capacitor.config.json
  12. 4
      android/app/src/main/assets/capacitor.plugins.json
  13. 10
      android/app/src/main/java/app/timesafari/MainActivity.java
  14. 3
      android/capacitor.settings.gradle
  15. 46
      capacitor.config.json
  16. 399
      doc/dexie-to-sqlite-mapping.md
  17. 95
      doc/migration-to-wa-sqlite.md
  18. 339
      doc/secure-storage-implementation.md
  19. 329
      doc/storage-implementation-checklist.md
  20. 1310
      docs/secure-storage-implementation.md
  21. 55
      electron/.gitignore
  22. BIN
      electron/assets/appIcon.ico
  23. BIN
      electron/assets/appIcon.png
  24. BIN
      electron/assets/splash.gif
  25. BIN
      electron/assets/splash.png
  26. 62
      electron/capacitor.config.json
  27. 28
      electron/electron-builder.config.json
  28. 75
      electron/live-runner.js
  29. 5243
      electron/package-lock.json
  30. 51
      electron/package.json
  31. 10
      electron/resources/electron-publisher-custom.js
  32. 110
      electron/src/index.ts
  33. 97
      electron/src/preload.ts
  34. 6
      electron/src/rt/electron-plugins.js
  35. 88
      electron/src/rt/electron-rt.ts
  36. 77
      electron/src/rt/logger.ts
  37. 584
      electron/src/rt/sqlite-init.ts
  38. 950
      electron/src/rt/sqlite-migrations.ts
  39. 244
      electron/src/setup.ts
  40. 18
      electron/tsconfig.json
  41. 186
      experiment.sh
  42. 5
      ios/App/App/AppDelegate.swift
  43. 1
      ios/App/Podfile
  44. 29
      main.js
  45. 5039
      package-lock.json
  46. 57
      package.json
  47. 0
      postcss.config.cjs
  48. 1
      requirements.txt
  49. 85
      scripts/build-electron.cjs
  50. 243
      scripts/build-electron.js
  51. 15
      scripts/copy-wasm.cjs
  52. 20
      src/App.vue
  53. 11
      src/components/DataExportSection.vue
  54. 33
      src/components/FeedFilters.vue
  55. 32
      src/components/GiftedDialog.vue
  56. 26
      src/components/GiftedPrompts.vue
  57. 13
      src/components/ImageMethodDialog.vue
  58. 32
      src/components/MembersList.vue
  59. 22
      src/components/OfferDialog.vue
  60. 36
      src/components/OnboardingDialog.vue
  61. 14
      src/components/PhotoDialog.vue
  62. 12
      src/components/PushNotificationPermission.vue
  63. 8
      src/components/TopMessage.vue
  64. 13
      src/components/UserNameDialog.vue
  65. 7
      src/components/World/components/objects/landmarks.js
  66. 5
      src/constants/app.ts
  67. 134
      src/db-sql/migration.ts
  68. 267
      src/db/databaseUtil.ts
  69. 56
      src/db/index.ts
  70. 6
      src/db/tables/accounts.ts
  71. 751
      src/electron/main.ts
  72. 113
      src/electron/preload.js
  73. 59
      src/interfaces/absurd-sql.d.ts
  74. 55
      src/interfaces/claims.ts
  75. 74
      src/interfaces/common.ts
  76. 17
      src/interfaces/database.ts
  77. 40
      src/interfaces/index.ts
  78. 8
      src/interfaces/records.ts
  79. 116
      src/libs/crypto/index.ts
  80. 21
      src/libs/crypto/vc/index.ts
  81. 157
      src/libs/crypto/vc/passkeyDidPeer.ts
  82. 420
      src/libs/endorserServer.ts
  83. 296
      src/libs/util.ts
  84. 2
      src/main.capacitor.ts
  85. 7
      src/main.common.ts
  86. 71
      src/main.electron.ts
  87. 215
      src/main.ts
  88. 34
      src/main.web.ts
  89. 6
      src/registerSQLWorker.js
  90. 20
      src/registerServiceWorker.ts
  91. 25
      src/router/index.ts
  92. 29
      src/services/AbsurdSqlDatabaseService.d.ts
  93. 243
      src/services/AbsurdSqlDatabaseService.ts
  94. 24
      src/services/PlatformService.ts
  95. 41
      src/services/QRScanner/CapacitorQRScanner.ts
  96. 29
      src/services/QRScanner/WebInlineQRScanner.ts
  97. 116
      src/services/database/ConnectionPool.ts
  98. 19
      src/services/deepLinks.ts
  99. 67
      src/services/migrationService.ts
  100. 230
      src/services/platforms/CapacitorPlatformService.ts

153
.cursor/rules/absurd-sql.mdc

@ -0,0 +1,153 @@
---
description:
globs:
alwaysApply: true
---
# Absurd SQL - Cursor Development Guide
## Project Overview
Absurd SQL is a backend implementation for sql.js that enables persistent SQLite databases in the browser by using IndexedDB as a block storage system. This guide provides rules and best practices for developing with this project in Cursor.
## Project Structure
```
absurd-sql/
├── src/ # Source code
├── dist/ # Built files
├── package.json # Dependencies and scripts
├── rollup.config.js # Build configuration
└── jest.config.js # Test configuration
```
## Development Rules
### 1. Worker Thread Requirements
- All SQL operations MUST be performed in a worker thread
- Main thread should only handle worker initialization and communication
- Never block the main thread with database operations
### 2. Code Organization
- Keep worker code in separate files (e.g., `*.worker.js`)
- Use ES modules for imports/exports
- Follow the project's existing module structure
### 3. Required Headers
When developing locally or deploying, ensure these headers are set:
```
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
```
### 4. Browser Compatibility
- Primary target: Modern browsers with SharedArrayBuffer support
- Fallback mode: Safari (with limitations)
- Always test in both modes
### 5. Database Configuration
Recommended database settings:
```sql
PRAGMA journal_mode=MEMORY;
PRAGMA page_size=8192; -- Optional, but recommended
```
### 6. Development Workflow
1. Install dependencies:
```bash
yarn add @jlongster/sql.js absurd-sql
```
2. Development commands:
- `yarn build` - Build the project
- `yarn jest` - Run tests
- `yarn serve` - Start development server
### 7. Testing Guidelines
- Write tests for both SharedArrayBuffer and fallback modes
- Use Jest for testing
- Include performance benchmarks for critical operations
### 8. Performance Considerations
- Use bulk operations when possible
- Monitor read/write performance
- Consider using transactions for multiple operations
- Avoid unnecessary database connections
### 9. Error Handling
- Implement proper error handling for:
- Worker initialization failures
- Database connection issues
- Concurrent access conflicts (in fallback mode)
- Storage quota exceeded scenarios
### 10. Security Best Practices
- Never expose database operations directly to the client
- Validate all SQL queries
- Implement proper access controls
- Handle sensitive data appropriately
### 11. Code Style
- Follow ESLint configuration
- Use async/await for asynchronous operations
- Document complex database operations
- Include comments for non-obvious optimizations
### 12. Debugging
- Use `jest-debug` for debugging tests
- Monitor IndexedDB usage in browser dev tools
- Check worker communication in console
- Use performance monitoring tools
## Common Patterns
### Worker Initialization
```javascript
// Main thread
import { initBackend } from 'absurd-sql/dist/indexeddb-main-thread';
function init() {
let worker = new Worker(new URL('./index.worker.js', import.meta.url));
initBackend(worker);
}
```
### Database Setup
```javascript
// Worker thread
import initSqlJs from '@jlongster/sql.js';
import { SQLiteFS } from 'absurd-sql';
import IndexedDBBackend from 'absurd-sql/dist/indexeddb-backend';
async function setupDatabase() {
let SQL = await initSqlJs({ locateFile: file => file });
let sqlFS = new SQLiteFS(SQL.FS, new IndexedDBBackend());
SQL.register_for_idb(sqlFS);
SQL.FS.mkdir('/sql');
SQL.FS.mount(sqlFS, {}, '/sql');
return new SQL.Database('/sql/db.sqlite', { filename: true });
}
```
## Troubleshooting
### Common Issues
1. SharedArrayBuffer not available
- Check COOP/COEP headers
- Verify browser support
- Test fallback mode
2. Worker initialization failures
- Check file paths
- Verify module imports
- Check browser console for errors
3. Performance issues
- Monitor IndexedDB usage
- Check for unnecessary operations
- Verify transaction usage
## Resources
- [Project Demo](https://priceless-keller-d097e5.netlify.app/)
- [Example Project](https://github.com/jlongster/absurd-example-project)
- [Blog Post](https://jlongster.com/future-sql-web)
- [SQL.js Documentation](https://github.com/sql-js/sql.js/)

2
.cursor/rules/crowd-funder-for-time-pwa/docs/camera-implementation.mdc

@ -1,7 +1,7 @@
---
description:
globs:
alwaysApply: true
alwaysApply: false
---
# Camera Implementation Documentation

1
.env.development

@ -9,4 +9,5 @@ VITE_DEFAULT_ENDORSER_API_SERVER=http://localhost:3000
# Using shared server by default to ease setup, which works for shared test users.
VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app
VITE_DEFAULT_PARTNER_API_SERVER=http://localhost:3000
#VITE_DEFAULT_PUSH_SERVER... can't be set up with localhost domain
VITE_PASSKEYS_ENABLED=true

6
.env.example

@ -1,6 +0,0 @@
# Admin DID credentials
ADMIN_DID=did:ethr:0x0000694B58C2cC69658993A90D3840C560f2F51F
ADMIN_PRIVATE_KEY=2b6472c026ec2aa2c4235c994a63868fc9212d18b58f6cbfe861b52e71330f5b
# API Configuration
ENDORSER_API_URL=https://test-api.endorser.ch/api/v2/claim

1
.env.production

@ -9,3 +9,4 @@ VITE_DEFAULT_ENDORSER_API_SERVER=https://api.endorser.ch
VITE_DEFAULT_IMAGE_API_SERVER=https://image-api.timesafari.app
VITE_DEFAULT_PARTNER_API_SERVER=https://partner-api.endorser.ch
VITE_DEFAULT_PUSH_SERVER=https://timesafari.app

1
.env.staging

@ -9,4 +9,5 @@ VITE_DEFAULT_ENDORSER_API_SERVER=https://test-api.endorser.ch
VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app
VITE_DEFAULT_PARTNER_API_SERVER=https://test-partner-api.endorser.ch
VITE_DEFAULT_PUSH_SERVER=https://test.timesafari.app
VITE_PASSKEYS_ENABLED=true

6
.eslintrc.js → .eslintrc.cjs

@ -4,6 +4,12 @@ module.exports = {
node: true,
es2022: true,
},
ignorePatterns: [
'node_modules/',
'dist/',
'dist-electron/',
'*.d.ts'
],
extends: [
"plugin:vue/vue3-recommended",
"eslint:recommended",

6
BUILDING.md

@ -84,7 +84,7 @@ Install dependencies:
* For test, build the app (because test server is not yet set up to build):
```bash
TIME_SAFARI_APP_TITLE="TimeSafari_Test" VITE_APP_SERVER=https://test.timesafari.app VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZYYPS272F VITE_DEFAULT_ENDORSER_API_SERVER=https://test-api.endorser.ch VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app VITE_DEFAULT_PARTNER_API_SERVER=https://test-partner-api.endorser.ch VITE_PASSKEYS_ENABLED=true npm run build
TIME_SAFARI_APP_TITLE="TimeSafari_Test" VITE_APP_SERVER=https://test.timesafari.app VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZYYPS272F VITE_DEFAULT_ENDORSER_API_SERVER=https://test-api.endorser.ch VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app VITE_DEFAULT_PARTNER_API_SERVER=https://test-partner-api.endorser.ch VITE_DEFAULT_PUSH_SERVER=https://test.timesafari.app VITE_PASSKEYS_ENABLED=true npm run build
```
... and transfer to the test server:
@ -241,7 +241,9 @@ docker run -d \
1. Build the electron app in production mode:
```bash
npm run build:electron-prod
npm run build:web
npm run build:electron
npm run electron:build-mac
```
2. Package the Electron app for macOS:

2
android/app/build.gradle

@ -91,6 +91,8 @@ dependencies {
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation project(':capacitor-android')
implementation project(':capacitor-community-sqlite')
implementation "androidx.biometric:biometric:1.2.0-alpha05"
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"

1
android/app/capacitor.build.gradle

@ -9,6 +9,7 @@ android {
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
implementation project(':capacitor-community-sqlite')
implementation project(':capacitor-mlkit-barcode-scanning')
implementation project(':capacitor-app')
implementation project(':capacitor-camera')

35
android/app/src/main/assets/capacitor.config.json

@ -16,6 +16,41 @@
}
]
}
},
"SQLite": {
"iosDatabaseLocation": "Library/CapacitorDatabase",
"iosIsEncryption": true,
"iosBiometric": {
"biometricAuth": true,
"biometricTitle": "Biometric login for TimeSafari"
},
"androidIsEncryption": true,
"androidBiometric": {
"biometricAuth": true,
"biometricTitle": "Biometric login for TimeSafari"
}
}
},
"ios": {
"contentInset": "always",
"allowsLinkPreview": true,
"scrollEnabled": true,
"limitsNavigationsToAppBoundDomains": true,
"backgroundColor": "#ffffff",
"allowNavigation": [
"*.timesafari.app",
"*.jsdelivr.net",
"api.endorser.ch"
]
},
"android": {
"allowMixedContent": false,
"captureInput": true,
"webContentsDebuggingEnabled": false,
"allowNavigation": [
"*.timesafari.app",
"*.jsdelivr.net",
"api.endorser.ch"
]
}
}

4
android/app/src/main/assets/capacitor.plugins.json

@ -1,4 +1,8 @@
[
{
"pkg": "@capacitor-community/sqlite",
"classpath": "com.getcapacitor.community.database.sqlite.CapacitorSQLitePlugin"
},
{
"pkg": "@capacitor-mlkit/barcode-scanning",
"classpath": "io.capawesome.capacitorjs.plugins.mlkit.barcodescanning.BarcodeScannerPlugin"

10
android/app/src/main/java/app/timesafari/MainActivity.java

@ -1,7 +1,15 @@
package app.timesafari;
import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
import com.getcapacitor.community.sqlite.SQLite;
public class MainActivity extends BridgeActivity {
// ... existing code ...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize SQLite
registerPlugin(SQLite.class);
}
}

3
android/capacitor.settings.gradle

@ -2,6 +2,9 @@
include ':capacitor-android'
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
include ':capacitor-community-sqlite'
project(':capacitor-community-sqlite').projectDir = new File('../node_modules/@capacitor-community/sqlite/android')
include ':capacitor-mlkit-barcode-scanning'
project(':capacitor-mlkit-barcode-scanning').projectDir = new File('../node_modules/@capacitor-mlkit/barcode-scanning/android')

46
capacitor.config.json

@ -1,10 +1,11 @@
{
"appId": "app.timesafari",
"appId": "com.timesafari.app",
"appName": "TimeSafari",
"webDir": "dist",
"bundledWebRuntime": false,
"server": {
"cleartext": true
"cleartext": true,
"androidScheme": "https"
},
"plugins": {
"App": {
@ -16,6 +17,47 @@
}
]
}
},
"SQLite": {
"iosDatabaseLocation": "Library/CapacitorDatabase",
"iosIsEncryption": true,
"iosBiometric": {
"biometricAuth": true,
"biometricTitle": "Biometric login for TimeSafari"
},
"androidIsEncryption": true,
"androidBiometric": {
"biometricAuth": true,
"biometricTitle": "Biometric login for TimeSafari"
}
},
"CapacitorSQLite": {
"electronIsEncryption": false,
"electronMacLocation": "~/Library/Application Support/TimeSafari",
"electronWindowsLocation": "C:\\ProgramData\\TimeSafari",
"electronLinuxLocation": "~/.local/share/TimeSafari"
}
},
"ios": {
"contentInset": "always",
"allowsLinkPreview": true,
"scrollEnabled": true,
"limitsNavigationsToAppBoundDomains": true,
"backgroundColor": "#ffffff",
"allowNavigation": [
"*.timesafari.app",
"*.jsdelivr.net",
"api.endorser.ch"
]
},
"android": {
"allowMixedContent": false,
"captureInput": true,
"webContentsDebuggingEnabled": false,
"allowNavigation": [
"*.timesafari.app",
"*.jsdelivr.net",
"api.endorser.ch"
]
}
}

399
doc/dexie-to-sqlite-mapping.md

@ -0,0 +1,399 @@
# Dexie to absurd-sql Mapping Guide
## Schema Mapping
### Current Dexie Schema
```typescript
// Current Dexie schema
const db = new Dexie('TimeSafariDB');
db.version(1).stores({
accounts: 'did, publicKeyHex, createdAt, updatedAt',
settings: 'key, value, updatedAt',
contacts: 'id, did, name, createdAt, updatedAt'
});
```
### New SQLite Schema
```sql
-- New SQLite schema
CREATE TABLE accounts (
did TEXT PRIMARY KEY,
public_key_hex TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE contacts (
id TEXT PRIMARY KEY,
did TEXT NOT NULL,
name TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
FOREIGN KEY (did) REFERENCES accounts(did)
);
-- Indexes for performance
CREATE INDEX idx_accounts_created_at ON accounts(created_at);
CREATE INDEX idx_contacts_did ON contacts(did);
CREATE INDEX idx_settings_updated_at ON settings(updated_at);
```
## Query Mapping
### 1. Account Operations
#### Get Account by DID
```typescript
// Dexie
const account = await db.accounts.get(did);
// absurd-sql
const result = await db.exec(`
SELECT * FROM accounts WHERE did = ?
`, [did]);
const account = result[0]?.values[0];
```
#### Get All Accounts
```typescript
// Dexie
const accounts = await db.accounts.toArray();
// absurd-sql
const result = await db.exec(`
SELECT * FROM accounts ORDER BY created_at DESC
`);
const accounts = result[0]?.values || [];
```
#### Add Account
```typescript
// Dexie
await db.accounts.add({
did,
publicKeyHex,
createdAt: Date.now(),
updatedAt: Date.now()
});
// absurd-sql
await db.run(`
INSERT INTO accounts (did, public_key_hex, created_at, updated_at)
VALUES (?, ?, ?, ?)
`, [did, publicKeyHex, Date.now(), Date.now()]);
```
#### Update Account
```typescript
// Dexie
await db.accounts.update(did, {
publicKeyHex,
updatedAt: Date.now()
});
// absurd-sql
await db.run(`
UPDATE accounts
SET public_key_hex = ?, updated_at = ?
WHERE did = ?
`, [publicKeyHex, Date.now(), did]);
```
### 2. Settings Operations
#### Get Setting
```typescript
// Dexie
const setting = await db.settings.get(key);
// absurd-sql
const result = await db.exec(`
SELECT * FROM settings WHERE key = ?
`, [key]);
const setting = result[0]?.values[0];
```
#### Set Setting
```typescript
// Dexie
await db.settings.put({
key,
value,
updatedAt: Date.now()
});
// absurd-sql
await db.run(`
INSERT INTO settings (key, value, updated_at)
VALUES (?, ?, ?)
ON CONFLICT(key) DO UPDATE SET
value = excluded.value,
updated_at = excluded.updated_at
`, [key, value, Date.now()]);
```
### 3. Contact Operations
#### Get Contacts by Account
```typescript
// Dexie
const contacts = await db.contacts
.where('did')
.equals(accountDid)
.toArray();
// absurd-sql
const result = await db.exec(`
SELECT * FROM contacts
WHERE did = ?
ORDER BY created_at DESC
`, [accountDid]);
const contacts = result[0]?.values || [];
```
#### Add Contact
```typescript
// Dexie
await db.contacts.add({
id: generateId(),
did: accountDid,
name,
createdAt: Date.now(),
updatedAt: Date.now()
});
// absurd-sql
await db.run(`
INSERT INTO contacts (id, did, name, created_at, updated_at)
VALUES (?, ?, ?, ?, ?)
`, [generateId(), accountDid, name, Date.now(), Date.now()]);
```
## Transaction Mapping
### Batch Operations
```typescript
// Dexie
await db.transaction('rw', [db.accounts, db.contacts], async () => {
await db.accounts.add(account);
await db.contacts.bulkAdd(contacts);
});
// absurd-sql
await db.exec('BEGIN TRANSACTION;');
try {
await db.run(`
INSERT INTO accounts (did, public_key_hex, created_at, updated_at)
VALUES (?, ?, ?, ?)
`, [account.did, account.publicKeyHex, account.createdAt, account.updatedAt]);
for (const contact of contacts) {
await db.run(`
INSERT INTO contacts (id, did, name, created_at, updated_at)
VALUES (?, ?, ?, ?, ?)
`, [contact.id, contact.did, contact.name, contact.createdAt, contact.updatedAt]);
}
await db.exec('COMMIT;');
} catch (error) {
await db.exec('ROLLBACK;');
throw error;
}
```
## Migration Helper Functions
### 1. Data Export (Dexie to JSON)
```typescript
async function exportDexieData(): Promise<MigrationData> {
const db = new Dexie('TimeSafariDB');
return {
accounts: await db.accounts.toArray(),
settings: await db.settings.toArray(),
contacts: await db.contacts.toArray(),
metadata: {
version: '1.0.0',
timestamp: Date.now(),
dexieVersion: Dexie.version
}
};
}
```
### 2. Data Import (JSON to absurd-sql)
```typescript
async function importToAbsurdSql(data: MigrationData): Promise<void> {
await db.exec('BEGIN TRANSACTION;');
try {
// Import accounts
for (const account of data.accounts) {
await db.run(`
INSERT INTO accounts (did, public_key_hex, created_at, updated_at)
VALUES (?, ?, ?, ?)
`, [account.did, account.publicKeyHex, account.createdAt, account.updatedAt]);
}
// Import settings
for (const setting of data.settings) {
await db.run(`
INSERT INTO settings (key, value, updated_at)
VALUES (?, ?, ?)
`, [setting.key, setting.value, setting.updatedAt]);
}
// Import contacts
for (const contact of data.contacts) {
await db.run(`
INSERT INTO contacts (id, did, name, created_at, updated_at)
VALUES (?, ?, ?, ?, ?)
`, [contact.id, contact.did, contact.name, contact.createdAt, contact.updatedAt]);
}
await db.exec('COMMIT;');
} catch (error) {
await db.exec('ROLLBACK;');
throw error;
}
}
```
### 3. Verification
```typescript
async function verifyMigration(dexieData: MigrationData): Promise<boolean> {
// Verify account count
const accountResult = await db.exec('SELECT COUNT(*) as count FROM accounts');
const accountCount = accountResult[0].values[0][0];
if (accountCount !== dexieData.accounts.length) {
return false;
}
// Verify settings count
const settingsResult = await db.exec('SELECT COUNT(*) as count FROM settings');
const settingsCount = settingsResult[0].values[0][0];
if (settingsCount !== dexieData.settings.length) {
return false;
}
// Verify contacts count
const contactsResult = await db.exec('SELECT COUNT(*) as count FROM contacts');
const contactsCount = contactsResult[0].values[0][0];
if (contactsCount !== dexieData.contacts.length) {
return false;
}
// Verify data integrity
for (const account of dexieData.accounts) {
const result = await db.exec(
'SELECT * FROM accounts WHERE did = ?',
[account.did]
);
const migratedAccount = result[0]?.values[0];
if (!migratedAccount ||
migratedAccount[1] !== account.publicKeyHex) { // public_key_hex is second column
return false;
}
}
return true;
}
```
## Performance Considerations
### 1. Indexing
- Dexie automatically creates indexes based on the schema
- absurd-sql requires explicit index creation
- Added indexes for frequently queried fields
- Use `PRAGMA journal_mode=MEMORY;` for better performance
### 2. Batch Operations
- Dexie has built-in bulk operations
- absurd-sql uses transactions for batch operations
- Consider chunking large datasets
- Use prepared statements for repeated queries
### 3. Query Optimization
- Dexie uses IndexedDB's native indexing
- absurd-sql requires explicit query optimization
- Use prepared statements for repeated queries
- Consider using `PRAGMA synchronous=NORMAL;` for better performance
## Error Handling
### 1. Common Errors
```typescript
// Dexie errors
try {
await db.accounts.add(account);
} catch (error) {
if (error instanceof Dexie.ConstraintError) {
// Handle duplicate key
}
}
// absurd-sql errors
try {
await db.run(`
INSERT INTO accounts (did, public_key_hex, created_at, updated_at)
VALUES (?, ?, ?, ?)
`, [account.did, account.publicKeyHex, account.createdAt, account.updatedAt]);
} catch (error) {
if (error.message.includes('UNIQUE constraint failed')) {
// Handle duplicate key
}
}
```
### 2. Transaction Recovery
```typescript
// Dexie transaction
try {
await db.transaction('rw', db.accounts, async () => {
// Operations
});
} catch (error) {
// Dexie automatically rolls back
}
// absurd-sql transaction
try {
await db.exec('BEGIN TRANSACTION;');
// Operations
await db.exec('COMMIT;');
} catch (error) {
await db.exec('ROLLBACK;');
throw error;
}
```
## Migration Strategy
1. **Preparation**
- Export all Dexie data
- Verify data integrity
- Create SQLite schema
- Setup indexes
2. **Migration**
- Import data in transactions
- Verify each batch
- Handle errors gracefully
- Maintain backup
3. **Verification**
- Compare record counts
- Verify data integrity
- Test common queries
- Validate relationships
4. **Cleanup**
- Remove Dexie database
- Clear IndexedDB storage
- Update application code
- Remove old dependencies

95
docs/migration-to-wa-sqlite.md → doc/migration-to-wa-sqlite.md

@ -1,8 +1,8 @@
# Migration Guide: Dexie to wa-sqlite
# Migration Guide: Dexie to absurd-sql
## Overview
This document outlines the migration process from Dexie.js to wa-sqlite for the TimeSafari app's storage implementation. The migration aims to provide a consistent SQLite-based storage solution across all platforms while maintaining data integrity and ensuring a smooth transition for users.
This document outlines the migration process from Dexie.js to absurd-sql for the TimeSafari app's storage implementation. The migration aims to provide a consistent SQLite-based storage solution across all platforms while maintaining data integrity and ensuring a smooth transition for users.
## Migration Goals
@ -43,12 +43,20 @@ This document outlines the migration process from Dexie.js to wa-sqlite for the
}
```
2. **Storage Requirements**
2. **Dependencies**
```json
{
"@jlongster/sql.js": "^1.8.0",
"absurd-sql": "^1.8.0"
}
```
3. **Storage Requirements**
- Sufficient IndexedDB quota
- Available disk space for SQLite
- Backup storage space
3. **Platform Support**
4. **Platform Support**
- Web: Modern browser with IndexedDB support
- iOS: iOS 13+ with SQLite support
- Android: Android 5+ with SQLite support
@ -60,9 +68,15 @@ This document outlines the migration process from Dexie.js to wa-sqlite for the
```typescript
// src/services/storage/migration/MigrationService.ts
import initSqlJs from '@jlongster/sql.js';
import { SQLiteFS } from 'absurd-sql';
import IndexedDBBackend from 'absurd-sql/dist/indexeddb-backend';
export class MigrationService {
private static instance: MigrationService;
private backup: MigrationBackup | null = null;
private sql: any = null;
private db: any = null;
async prepare(): Promise<void> {
try {
@ -75,8 +89,8 @@ export class MigrationService {
// 3. Verify backup integrity
await this.verifyBackup();
// 4. Initialize wa-sqlite
await this.initializeWaSqlite();
// 4. Initialize absurd-sql
await this.initializeAbsurdSql();
} catch (error) {
throw new StorageError(
'Migration preparation failed',
@ -86,6 +100,42 @@ export class MigrationService {
}
}
private async initializeAbsurdSql(): Promise<void> {
// Initialize SQL.js
this.sql = await initSqlJs({
locateFile: (file: string) => {
return new URL(`/node_modules/@jlongster/sql.js/dist/${file}`, import.meta.url).href;
}
});
// Setup SQLiteFS with IndexedDB backend
const sqlFS = new SQLiteFS(this.sql.FS, new IndexedDBBackend());
this.sql.register_for_idb(sqlFS);
// Create and mount filesystem
this.sql.FS.mkdir('/sql');
this.sql.FS.mount(sqlFS, {}, '/sql');
// Open database
const path = '/sql/db.sqlite';
if (typeof SharedArrayBuffer === 'undefined') {
let stream = this.sql.FS.open(path, 'a+');
await stream.node.contents.readIfFallback();
this.sql.FS.close(stream);
}
this.db = new this.sql.Database(path, { filename: true });
if (!this.db) {
throw new StorageError(
'Database initialization failed',
StorageErrorCodes.INITIALIZATION_FAILED
);
}
// Configure database
await this.db.exec(`PRAGMA journal_mode=MEMORY;`);
}
private async checkPrerequisites(): Promise<void> {
// Check IndexedDB availability
if (!window.indexedDB) {
@ -160,12 +210,11 @@ export class DataMigration {
}
private async migrateAccounts(accounts: Account[]): Promise<void> {
const db = await this.getWaSqliteConnection();
// Use transaction for atomicity
await db.transaction(async (tx) => {
await this.db.exec('BEGIN TRANSACTION;');
try {
for (const account of accounts) {
await tx.execute(`
await this.db.run(`
INSERT INTO accounts (did, public_key_hex, created_at, updated_at)
VALUES (?, ?, ?, ?)
`, [
@ -175,16 +224,18 @@ export class DataMigration {
account.updatedAt
]);
}
});
await this.db.exec('COMMIT;');
} catch (error) {
await this.db.exec('ROLLBACK;');
throw error;
}
}
private async verifyMigration(backup: MigrationBackup): Promise<void> {
const db = await this.getWaSqliteConnection();
// Verify account count
const accountCount = await db.selectValue(
'SELECT COUNT(*) FROM accounts'
);
const result = await this.db.exec('SELECT COUNT(*) as count FROM accounts');
const accountCount = result[0].values[0][0];
if (accountCount !== backup.accounts.length) {
throw new StorageError(
'Account count mismatch',
@ -214,8 +265,8 @@ export class RollbackService {
// 3. Verify restoration
await this.verifyRestoration(backup);
// 4. Clean up wa-sqlite
await this.cleanupWaSqlite();
// 4. Clean up absurd-sql
await this.cleanupAbsurdSql();
} catch (error) {
throw new StorageError(
'Rollback failed',
@ -371,6 +422,14 @@ button:hover {
```typescript
// src/services/storage/migration/__tests__/MigrationService.spec.ts
describe('MigrationService', () => {
it('should initialize absurd-sql correctly', async () => {
const service = MigrationService.getInstance();
await service.initializeAbsurdSql();
expect(service.isInitialized()).toBe(true);
expect(service.getDatabase()).toBeDefined();
});
it('should create valid backup', async () => {
const service = MigrationService.getInstance();
const backup = await service.createBackup();

339
doc/secure-storage-implementation.md

@ -0,0 +1,339 @@
# Secure Storage Implementation Guide for TimeSafari App
## Overview
This document outlines the implementation of secure storage for the TimeSafari app. The implementation focuses on:
1. **Platform-Specific Storage Solutions**:
- Web: SQLite with IndexedDB backend (absurd-sql)
- Electron: SQLite with Node.js backend
- Native: (Planned) SQLCipher with platform-specific secure storage
2. **Key Features**:
- SQLite-based storage using absurd-sql for web
- Platform-specific service factory pattern
- Consistent API across platforms
- Migration support from Dexie.js
## Quick Start
### 1. Installation
```bash
# Core dependencies
npm install @jlongster/sql.js
npm install absurd-sql
# Platform-specific dependencies (for future native support)
npm install @capacitor/preferences
npm install @capacitor-community/biometric-auth
```
### 2. Basic Usage
```typescript
// Using the platform service
import { PlatformServiceFactory } from '../services/PlatformServiceFactory';
// Get platform-specific service instance
const platformService = PlatformServiceFactory.getInstance();
// Example database operations
async function example() {
try {
// Query example
const result = await platformService.dbQuery(
"SELECT * FROM accounts WHERE did = ?",
[did]
);
// Execute example
await platformService.dbExec(
"INSERT INTO accounts (did, public_key_hex) VALUES (?, ?)",
[did, publicKeyHex]
);
} catch (error) {
console.error('Database operation failed:', error);
}
}
```
### 3. Platform Detection
```typescript
// src/services/PlatformServiceFactory.ts
export class PlatformServiceFactory {
static getInstance(): PlatformService {
if (process.env.ELECTRON) {
// Electron platform
return new ElectronPlatformService();
} else {
// Web platform (default)
return new AbsurdSqlDatabaseService();
}
}
}
```
### 4. Current Implementation Details
#### Web Platform (AbsurdSqlDatabaseService)
The web platform uses absurd-sql with IndexedDB backend:
```typescript
// src/services/AbsurdSqlDatabaseService.ts
export class AbsurdSqlDatabaseService implements PlatformService {
private static instance: AbsurdSqlDatabaseService | null = null;
private db: AbsurdSqlDatabase | null = null;
private initialized: boolean = false;
// Singleton pattern
static getInstance(): AbsurdSqlDatabaseService {
if (!AbsurdSqlDatabaseService.instance) {
AbsurdSqlDatabaseService.instance = new AbsurdSqlDatabaseService();
}
return AbsurdSqlDatabaseService.instance;
}
// Database operations
async dbQuery(sql: string, params: unknown[] = []): Promise<QueryExecResult[]> {
await this.waitForInitialization();
return this.queueOperation<QueryExecResult[]>("query", sql, params);
}
async dbExec(sql: string, params: unknown[] = []): Promise<void> {
await this.waitForInitialization();
await this.queueOperation<void>("run", sql, params);
}
}
```
Key features:
- Uses absurd-sql for SQLite in the browser
- Implements operation queuing for thread safety
- Handles initialization and connection management
- Provides consistent API across platforms
### 5. Migration from Dexie.js
The current implementation supports gradual migration from Dexie.js:
```typescript
// Example of dual-storage pattern
async function getAccount(did: string): Promise<Account | undefined> {
// Try SQLite first
const platform = PlatformServiceFactory.getInstance();
let account = await platform.dbQuery(
"SELECT * FROM accounts WHERE did = ?",
[did]
);
// Fallback to Dexie if needed
if (USE_DEXIE_DB) {
account = await db.accounts.get(did);
}
return account;
}
```
#### A. Modifying Code
When converting from Dexie.js to SQL-based implementation, follow these patterns:
1. **Database Access Pattern**
```typescript
// Before (Dexie)
const result = await db.table.where("field").equals(value).first();
// After (SQL)
const platform = PlatformServiceFactory.getInstance();
let result = await platform.dbQuery(
"SELECT * FROM table WHERE field = ?",
[value]
);
result = databaseUtil.mapQueryResultToValues(result);
// Fallback to Dexie if needed
if (USE_DEXIE_DB) {
result = await db.table.where("field").equals(value).first();
}
```
2. **Update Operations**
```typescript
// Before (Dexie)
await db.table.where("id").equals(id).modify(changes);
// After (SQL)
// For settings updates, use the utility methods:
await databaseUtil.updateDefaultSettings(changes);
// OR
await databaseUtil.updateAccountSettings(did, changes);
// For other tables, use direct SQL:
const platform = PlatformServiceFactory.getInstance();
await platform.dbExec(
"UPDATE table SET field1 = ?, field2 = ? WHERE id = ?",
[changes.field1, changes.field2, id]
);
// Fallback to Dexie if needed
if (USE_DEXIE_DB) {
await db.table.where("id").equals(id).modify(changes);
}
```
3. **Insert Operations**
```typescript
// Before (Dexie)
await db.table.add(item);
// After (SQL)
const platform = PlatformServiceFactory.getInstance();
const columns = Object.keys(item);
const values = Object.values(item);
const placeholders = values.map(() => '?').join(', ');
const sql = `INSERT INTO table (${columns.join(', ')}) VALUES (${placeholders})`;
await platform.dbExec(sql, values);
// Fallback to Dexie if needed
if (USE_DEXIE_DB) {
await db.table.add(item);
}
```
4. **Delete Operations**
```typescript
// Before (Dexie)
await db.table.where("id").equals(id).delete();
// After (SQL)
const platform = PlatformServiceFactory.getInstance();
await platform.dbExec("DELETE FROM table WHERE id = ?", [id]);
// Fallback to Dexie if needed
if (USE_DEXIE_DB) {
await db.table.where("id").equals(id).delete();
}
```
5. **Result Processing**
```typescript
// Before (Dexie)
const items = await db.table.toArray();
// After (SQL)
const platform = PlatformServiceFactory.getInstance();
let items = await platform.dbQuery("SELECT * FROM table");
items = databaseUtil.mapQueryResultToValues(items);
// Fallback to Dexie if needed
if (USE_DEXIE_DB) {
items = await db.table.toArray();
}
```
6. **Using Utility Methods**
When working with settings or other common operations, use the utility methods in `db/index.ts`:
```typescript
// Settings operations
await databaseUtil.updateDefaultSettings(settings);
await databaseUtil.updateAccountSettings(did, settings);
const settings = await databaseUtil.retrieveSettingsForDefaultAccount();
const settings = await databaseUtil.retrieveSettingsForActiveAccount();
// Logging operations
await databaseUtil.logToDb(message);
await databaseUtil.logConsoleAndDb(message, showInConsole);
```
Key Considerations:
- Always use `databaseUtil.mapQueryResultToValues()` to process SQL query results
- Use utility methods from `db/index.ts` when available instead of direct SQL
- Keep Dexie fallbacks wrapped in `if (USE_DEXIE_DB)` checks
- For queries that return results, use `let` variables to allow Dexie fallback to override
- For updates/inserts/deletes, execute both SQL and Dexie operations when `USE_DEXIE_DB` is true
Example Migration:
```typescript
// Before (Dexie)
export async function updateSettings(settings: Settings): Promise<void> {
await db.settings.put(settings);
}
// After (SQL)
export async function updateSettings(settings: Settings): Promise<void> {
const platform = PlatformServiceFactory.getInstance();
const { sql, params } = generateUpdateStatement(
settings,
"settings",
"id = ?",
[settings.id]
);
await platform.dbExec(sql, params);
}
```
Remember to:
- Create database access code to use the platform service, putting it in front of the Dexie version
- Instead of removing Dexie-specific code, keep it.
- For creates & updates & deletes, the duplicate code is fine.
- For queries where we use the results, make the setting from SQL into a 'let' variable, then wrap the Dexie code in a check for USE_DEXIE_DB from app.ts and if
it's true then use that result instead of the SQL code's result.
- Consider data migration needs, and warn if there are any potential migration problems
## Success Criteria
1. **Functionality**
- [x] Basic CRUD operations work correctly
- [x] Platform service factory pattern implemented
- [x] Error handling in place
- [ ] Native platform support (planned)
2. **Performance**
- [x] Database operations complete within acceptable time
- [x] Operation queuing for thread safety
- [x] Proper initialization handling
- [ ] Performance monitoring (planned)
3. **Security**
- [x] Basic data integrity
- [ ] Encryption (planned for native platforms)
- [ ] Secure key storage (planned)
- [ ] Platform-specific security features (planned)
4. **Testing**
- [x] Basic unit tests
- [ ] Comprehensive integration tests (planned)
- [ ] Platform-specific tests (planned)
- [ ] Migration tests (planned)
## Next Steps
1. **Native Platform Support**
- Implement SQLCipher for iOS/Android
- Add platform-specific secure storage
- Implement biometric authentication
2. **Enhanced Security**
- Add encryption for sensitive data
- Implement secure key storage
- Add platform-specific security features
3. **Testing and Monitoring**
- Add comprehensive test coverage
- Implement performance monitoring
- Add error tracking and analytics
4. **Documentation**
- Add API documentation
- Create migration guides
- Document security measures

329
doc/storage-implementation-checklist.md

@ -0,0 +1,329 @@
# Storage Implementation Checklist
## Core Services
### 1. Storage Service Layer
- [x] Create base `PlatformService` interface
- [x] Define common methods for all platforms
- [x] Add platform-specific method signatures
- [x] Include error handling types
- [x] Add migration support methods
- [x] Implement platform-specific services
- [x] `AbsurdSqlDatabaseService` (web)
- [x] Database initialization
- [x] VFS setup with IndexedDB backend
- [x] Connection management
- [x] Operation queuing
- [ ] `NativeSQLiteService` (iOS/Android) (planned)
- [ ] SQLCipher integration
- [ ] Native bridge setup
- [ ] File system access
- [ ] `ElectronSQLiteService` (planned)
- [ ] Node SQLite integration
- [ ] IPC communication
- [ ] File system access
### 2. Migration Services
- [x] Implement basic migration support
- [x] Dual-storage pattern (SQLite + Dexie)
- [x] Basic data verification
- [ ] Rollback procedures (planned)
- [ ] Progress tracking (planned)
- [ ] Create `MigrationUI` components (planned)
- [ ] Progress indicators
- [ ] Error handling
- [ ] User notifications
- [ ] Manual triggers
### 3. Security Layer
- [x] Basic data integrity
- [ ] Implement `EncryptionService` (planned)
- [ ] Key management
- [ ] Encryption/decryption
- [ ] Secure storage
- [ ] Add `BiometricService` (planned)
- [ ] Platform detection
- [ ] Authentication flow
- [ ] Fallback mechanisms
## Platform-Specific Implementation
### Web Platform
- [x] Setup absurd-sql
- [x] Install dependencies
```json
{
"@jlongster/sql.js": "^1.8.0",
"absurd-sql": "^1.8.0"
}
```
- [x] Configure VFS with IndexedDB backend
- [x] Setup worker threads
- [x] Implement operation queuing
- [x] Configure database pragmas
```sql
PRAGMA journal_mode=MEMORY;
PRAGMA synchronous=NORMAL;
PRAGMA foreign_keys=ON;
PRAGMA busy_timeout=5000;
```
- [x] Update build configuration
- [x] Modify `vite.config.ts`
- [x] Add worker configuration
- [x] Update chunk splitting
- [x] Configure asset handling
- [x] Implement IndexedDB backend
- [x] Create database service
- [x] Add operation queuing
- [x] Handle initialization
- [x] Implement atomic operations
### iOS Platform (Planned)
- [ ] Setup SQLCipher
- [ ] Install pod dependencies
- [ ] Configure encryption
- [ ] Setup keychain access
- [ ] Implement secure storage
- [ ] Update Capacitor config
- [ ] Modify `capacitor.config.ts`
- [ ] Add iOS permissions
- [ ] Configure backup
- [ ] Setup app groups
### Android Platform (Planned)
- [ ] Setup SQLCipher
- [ ] Add Gradle dependencies
- [ ] Configure encryption
- [ ] Setup keystore
- [ ] Implement secure storage
- [ ] Update Capacitor config
- [ ] Modify `capacitor.config.ts`
- [ ] Add Android permissions
- [ ] Configure backup
- [ ] Setup file provider
### Electron Platform (Planned)
- [ ] Setup Node SQLite
- [ ] Install dependencies
- [ ] Configure IPC
- [ ] Setup file system access
- [ ] Implement secure storage
- [ ] Update Electron config
- [ ] Modify `electron.config.ts`
- [ ] Add security policies
- [ ] Configure file access
- [ ] Setup auto-updates
## Data Models and Types
### 1. Database Schema
- [x] Define tables
```sql
-- Accounts table
CREATE TABLE accounts (
did TEXT PRIMARY KEY,
public_key_hex TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
-- Settings table
CREATE TABLE settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
-- Contacts table
CREATE TABLE contacts (
id TEXT PRIMARY KEY,
did TEXT NOT NULL,
name TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
FOREIGN KEY (did) REFERENCES accounts(did)
);
-- Indexes for performance
CREATE INDEX idx_accounts_created_at ON accounts(created_at);
CREATE INDEX idx_contacts_did ON contacts(did);
CREATE INDEX idx_settings_updated_at ON settings(updated_at);
```
- [x] Create indexes
- [x] Define constraints
- [ ] Add triggers (planned)
- [ ] Setup migrations (planned)
### 2. Type Definitions
- [x] Create interfaces
```typescript
interface Account {
did: string;
publicKeyHex: string;
createdAt: number;
updatedAt: number;
}
interface Setting {
key: string;
value: string;
updatedAt: number;
}
interface Contact {
id: string;
did: string;
name?: string;
createdAt: number;
updatedAt: number;
}
```
- [x] Add validation
- [x] Create DTOs
- [x] Define enums
- [x] Add type guards
## UI Components
### 1. Migration UI (Planned)
- [ ] Create components
- [ ] `MigrationProgress.vue`
- [ ] `MigrationError.vue`
- [ ] `MigrationSettings.vue`
- [ ] `MigrationStatus.vue`
### 2. Settings UI (Planned)
- [ ] Update components
- [ ] Add storage settings
- [ ] Add migration controls
- [ ] Add backup options
- [ ] Add security settings
### 3. Error Handling UI (Planned)
- [ ] Create components
- [ ] `StorageError.vue`
- [ ] `QuotaExceeded.vue`
- [ ] `MigrationFailed.vue`
- [ ] `RecoveryOptions.vue`
## Testing
### 1. Unit Tests
- [x] Basic service tests
- [x] Platform service tests
- [x] Database operation tests
- [ ] Security service tests (planned)
- [ ] Platform detection tests (planned)
### 2. Integration Tests (Planned)
- [ ] Test migrations
- [ ] Web platform tests
- [ ] iOS platform tests
- [ ] Android platform tests
- [ ] Electron platform tests
### 3. E2E Tests (Planned)
- [ ] Test workflows
- [ ] Account management
- [ ] Settings management
- [ ] Contact management
- [ ] Migration process
## Documentation
### 1. Technical Documentation
- [x] Update architecture docs
- [x] Add API documentation
- [ ] Create migration guides (planned)
- [ ] Document security measures (planned)
### 2. User Documentation (Planned)
- [ ] Update user guides
- [ ] Add troubleshooting guides
- [ ] Create FAQ
- [ ] Document new features
## Deployment
### 1. Build Process
- [x] Update build scripts
- [x] Add platform-specific builds
- [ ] Configure CI/CD (planned)
- [ ] Setup automated testing (planned)
### 2. Release Process (Planned)
- [ ] Create release checklist
- [ ] Add version management
- [ ] Setup rollback procedures
- [ ] Configure monitoring
## Monitoring and Analytics (Planned)
### 1. Error Tracking
- [ ] Setup error logging
- [ ] Add performance monitoring
- [ ] Configure alerts
- [ ] Create dashboards
### 2. Usage Analytics
- [ ] Add storage metrics
- [ ] Track migration success
- [ ] Monitor performance
- [ ] Collect user feedback
## Security Audit (Planned)
### 1. Code Review
- [ ] Review encryption
- [ ] Check access controls
- [ ] Verify data handling
- [ ] Audit dependencies
### 2. Penetration Testing
- [ ] Test data access
- [ ] Verify encryption
- [ ] Check authentication
- [ ] Review permissions
## Success Criteria
### 1. Performance
- [x] Query response time < 100ms
- [x] Operation queuing for thread safety
- [x] Proper initialization handling
- [ ] Migration time < 5s per 1000 records (planned)
- [ ] Storage overhead < 10% (planned)
- [ ] Memory usage < 50MB (planned)
### 2. Reliability
- [x] Basic data integrity
- [x] Operation queuing
- [ ] Automatic recovery (planned)
- [ ] Backup verification (planned)
- [ ] Transaction atomicity (planned)
- [ ] Data consistency (planned)
### 3. Security
- [x] Basic data integrity
- [ ] AES-256 encryption (planned)
- [ ] Secure key storage (planned)
- [ ] Access control (planned)
- [ ] Audit logging (planned)
### 4. User Experience
- [x] Basic database operations
- [ ] Smooth migration (planned)
- [ ] Clear error messages (planned)
- [ ] Progress indicators (planned)
- [ ] Recovery options (planned)

1310
docs/secure-storage-implementation.md

File diff suppressed because it is too large

55
electron/.gitignore

@ -0,0 +1,55 @@
# NPM renames .gitignore to .npmignore
# In order to prevent that, we remove the initial "."
# And the CLI then renames it
app
node_modules
build
dist
logs
# Node.js dependencies
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# Capacitor build outputs
web/
ios/
android/
electron/app/
# Capacitor SQLite plugin data (important!)
capacitor-sqlite/
# TypeScript / build output
dist/
build/
*.log
# Development / IDE files
.env.local
.env.development.local
.env.test.local
.env.production.local
# VS Code
.vscode/
!.vscode/extensions.json
# JetBrains IDEs (IntelliJ, WebStorm, etc.)
.idea/
*.iml
*.iws
# macOS specific
.DS_Store
*.swp
*~
*.tmp
# Windows specific
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/

BIN
electron/assets/appIcon.ico

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

BIN
electron/assets/appIcon.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

BIN
electron/assets/splash.gif

Binary file not shown.

After

Width:  |  Height:  |  Size: 159 KiB

BIN
electron/assets/splash.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

62
electron/capacitor.config.json

@ -0,0 +1,62 @@
{
"appId": "com.timesafari.app",
"appName": "TimeSafari",
"webDir": "dist",
"bundledWebRuntime": false,
"server": {
"cleartext": true,
"androidScheme": "https"
},
"plugins": {
"App": {
"appUrlOpen": {
"handlers": [
{
"url": "timesafari://*",
"autoVerify": true
}
]
}
},
"SQLite": {
"iosDatabaseLocation": "Library/CapacitorDatabase",
"iosIsEncryption": true,
"iosBiometric": {
"biometricAuth": true,
"biometricTitle": "Biometric login for TimeSafari"
},
"androidIsEncryption": true,
"androidBiometric": {
"biometricAuth": true,
"biometricTitle": "Biometric login for TimeSafari"
}
},
"CapacitorSQLite": {
"electronIsEncryption": false,
"electronMacLocation": "~/Library/Application Support/TimeSafari",
"electronWindowsLocation": "C:\\ProgramData\\TimeSafari"
}
},
"ios": {
"contentInset": "always",
"allowsLinkPreview": true,
"scrollEnabled": true,
"limitsNavigationsToAppBoundDomains": true,
"backgroundColor": "#ffffff",
"allowNavigation": [
"*.timesafari.app",
"*.jsdelivr.net",
"api.endorser.ch"
]
},
"android": {
"allowMixedContent": false,
"captureInput": true,
"webContentsDebuggingEnabled": false,
"allowNavigation": [
"*.timesafari.app",
"*.jsdelivr.net",
"api.endorser.ch"
]
}
}

28
electron/electron-builder.config.json

@ -0,0 +1,28 @@
{
"appId": "com.yourdoamnin.yourapp",
"directories": {
"buildResources": "resources"
},
"files": [
"assets/**/*",
"build/**/*",
"capacitor.config.*",
"app/**/*"
],
"publish": {
"provider": "github"
},
"nsis": {
"allowElevation": true,
"oneClick": false,
"allowToChangeInstallationDirectory": true
},
"win": {
"target": "nsis",
"icon": "assets/appIcon.ico"
},
"mac": {
"category": "your.app.category.type",
"target": "dmg"
}
}

75
electron/live-runner.js

@ -0,0 +1,75 @@
/* eslint-disable no-undef */
/* eslint-disable @typescript-eslint/no-var-requires */
const cp = require('child_process');
const chokidar = require('chokidar');
const electron = require('electron');
let child = null;
const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const reloadWatcher = {
debouncer: null,
ready: false,
watcher: null,
restarting: false,
};
///*
function runBuild() {
return new Promise((resolve, _reject) => {
let tempChild = cp.spawn(npmCmd, ['run', 'build']);
tempChild.once('exit', () => {
resolve();
});
tempChild.stdout.pipe(process.stdout);
});
}
//*/
async function spawnElectron() {
if (child !== null) {
child.stdin.pause();
child.kill();
child = null;
await runBuild();
}
child = cp.spawn(electron, ['--inspect=5858', './']);
child.on('exit', () => {
if (!reloadWatcher.restarting) {
process.exit(0);
}
});
child.stdout.pipe(process.stdout);
}
function setupReloadWatcher() {
reloadWatcher.watcher = chokidar
.watch('./src/**/*', {
ignored: /[/\\]\./,
persistent: true,
})
.on('ready', () => {
reloadWatcher.ready = true;
})
.on('all', (_event, _path) => {
if (reloadWatcher.ready) {
clearTimeout(reloadWatcher.debouncer);
reloadWatcher.debouncer = setTimeout(async () => {
console.log('Restarting');
reloadWatcher.restarting = true;
await spawnElectron();
reloadWatcher.restarting = false;
reloadWatcher.ready = false;
clearTimeout(reloadWatcher.debouncer);
reloadWatcher.debouncer = null;
reloadWatcher.watcher = null;
setupReloadWatcher();
}, 500);
}
});
}
(async () => {
await runBuild();
await spawnElectron();
setupReloadWatcher();
})();

5243
electron/package-lock.json

File diff suppressed because it is too large

51
electron/package.json

@ -0,0 +1,51 @@
{
"name": "TimeSafari",
"version": "1.0.0",
"description": "TimeSafari Electron App",
"author": {
"name": "",
"email": ""
},
"repository": {
"type": "git",
"url": ""
},
"license": "MIT",
"main": "build/src/index.js",
"scripts": {
"build": "tsc && electron-rebuild",
"electron:start-live": "node ./live-runner.js",
"electron:start": "npm run build && electron --inspect=5858 ./",
"electron:pack": "npm run build && electron-builder build --dir -c ./electron-builder.config.json",
"electron:make": "npm run build && electron-builder build -c ./electron-builder.config.json -p always"
},
"dependencies": {
"@capacitor-community/electron": "^5.0.0",
"@capacitor-community/sqlite": "^6.0.2",
"better-sqlite3-multiple-ciphers": "^11.10.0",
"chokidar": "~3.5.3",
"crypto": "^1.0.1",
"crypto-js": "^4.2.0",
"electron-is-dev": "~2.0.0",
"electron-json-storage": "^4.6.0",
"electron-serve": "~1.1.0",
"electron-unhandled": "~4.0.1",
"electron-updater": "^5.3.0",
"electron-window-state": "^5.0.3",
"jszip": "^3.10.1",
"node-fetch": "^2.6.7"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.13",
"@types/crypto-js": "^4.2.2",
"@types/electron-json-storage": "^4.5.4",
"electron": "^26.2.2",
"electron-builder": "~23.6.0",
"source-map-support": "^0.5.21",
"typescript": "^5.0.4"
},
"keywords": [
"capacitor",
"electron"
]
}

10
electron/resources/electron-publisher-custom.js

@ -0,0 +1,10 @@
/* eslint-disable no-undef */
/* eslint-disable @typescript-eslint/no-var-requires */
const electronPublish = require('electron-publish');
class Publisher extends electronPublish.Publisher {
async upload(task) {
console.log('electron-publisher-custom', task.file);
}
}
module.exports = Publisher;

110
electron/src/index.ts

@ -0,0 +1,110 @@
import type { CapacitorElectronConfig } from '@capacitor-community/electron';
import { getCapacitorElectronConfig, setupElectronDeepLinking } from '@capacitor-community/electron';
import type { MenuItemConstructorOptions } from 'electron';
import { app, MenuItem } from 'electron';
import electronIsDev from 'electron-is-dev';
import unhandled from 'electron-unhandled';
import { autoUpdater } from 'electron-updater';
import { ElectronCapacitorApp, setupContentSecurityPolicy, setupReloadWatcher } from './setup';
import { initializeSQLite, setupSQLiteHandlers } from './rt/sqlite-init';
// Graceful handling of unhandled errors.
unhandled();
// Define our menu templates (these are optional)
const trayMenuTemplate: (MenuItemConstructorOptions | MenuItem)[] = [new MenuItem({ label: 'Quit App', role: 'quit' })];
const appMenuBarMenuTemplate: (MenuItemConstructorOptions | MenuItem)[] = [
{ role: process.platform === 'darwin' ? 'appMenu' : 'fileMenu' },
{ role: 'viewMenu' },
];
// Get Config options from capacitor.config
const capacitorFileConfig: CapacitorElectronConfig = getCapacitorElectronConfig();
// Initialize our app. You can pass menu templates into the app here.
const myCapacitorApp = new ElectronCapacitorApp(capacitorFileConfig, trayMenuTemplate, appMenuBarMenuTemplate);
// If deeplinking is enabled then we will set it up here.
if (capacitorFileConfig.electron?.deepLinkingEnabled) {
setupElectronDeepLinking(myCapacitorApp, {
customProtocol: capacitorFileConfig.electron.deepLinkingCustomProtocol ?? 'mycapacitorapp',
});
}
// If we are in Dev mode, use the file watcher components.
if (electronIsDev) {
setupReloadWatcher(myCapacitorApp);
}
// Run Application
(async () => {
try {
// Wait for electron app to be ready.
await app.whenReady();
// Security - Set Content-Security-Policy based on whether or not we are in dev mode.
setupContentSecurityPolicy(myCapacitorApp.getCustomURLScheme());
// Initialize SQLite and register handlers BEFORE app initialization
console.log('[Main] Starting SQLite initialization...');
try {
// Register handlers first to prevent "no handler" errors
setupSQLiteHandlers();
console.log('[Main] SQLite handlers registered');
// Then initialize the plugin
await initializeSQLite();
console.log('[Main] SQLite plugin initialized successfully');
} catch (error) {
console.error('[Main] Failed to initialize SQLite:', error);
// Don't proceed with app initialization if SQLite fails
throw new Error(`SQLite initialization failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
// Initialize our app, build windows, and load content.
console.log('[Main] Starting app initialization...');
await myCapacitorApp.init();
console.log('[Main] App initialization complete');
// Check for updates if we are in a packaged app.
if (!electronIsDev) {
console.log('[Main] Checking for updates...');
autoUpdater.checkForUpdatesAndNotify();
}
} catch (error) {
console.error('[Main] Fatal error during app initialization:', error);
// Ensure we notify the user before quitting
const mainWindow = myCapacitorApp.getMainWindow();
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('app-error', {
type: 'initialization',
error: error instanceof Error ? error.message : 'Unknown error'
});
// Give the window time to show the error
setTimeout(() => app.quit(), 5000);
} else {
app.quit();
}
}
})();
// Handle when all of our windows are close (platforms have their own expectations).
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});
// When the dock icon is clicked.
app.on('activate', async function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (myCapacitorApp.getMainWindow().isDestroyed()) {
await myCapacitorApp.init();
}
});
// Place all ipc or other electron api calls and custom functionality under this line

97
electron/src/preload.ts

@ -0,0 +1,97 @@
/**
* Preload script for Electron
* Sets up secure IPC communication between renderer and main process
*
* @author Matthew Raymer
*/
import { contextBridge, ipcRenderer } from 'electron';
// Simple logger for preload script
const logger = {
log: (...args: unknown[]) => console.log('[Preload]', ...args),
error: (...args: unknown[]) => console.error('[Preload]', ...args),
info: (...args: unknown[]) => console.info('[Preload]', ...args),
warn: (...args: unknown[]) => console.warn('[Preload]', ...args),
debug: (...args: unknown[]) => console.debug('[Preload]', ...args),
};
// Types for SQLite connection options
interface SQLiteConnectionOptions {
database: string;
version?: number;
readOnly?: boolean;
readonly?: boolean; // Handle both cases
encryption?: string;
mode?: string;
useNative?: boolean;
[key: string]: unknown; // Allow other properties
}
// Create a proxy for the CapacitorSQLite plugin
const createSQLiteProxy = () => {
const MAX_RETRIES = 3;
const RETRY_DELAY = 1000; // 1 second
const withRetry = async <T>(operation: (...args: unknown[]) => Promise<T>, ...args: unknown[]): Promise<T> => {
let lastError: Error | null = null;
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
try {
return await operation(...args);
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
if (attempt < MAX_RETRIES) {
logger.warn(`SQLite operation failed (attempt ${attempt}/${MAX_RETRIES}), retrying...`, error);
await new Promise(resolve => setTimeout(resolve, RETRY_DELAY));
}
}
}
throw new Error(`SQLite operation failed after ${MAX_RETRIES} attempts: ${lastError?.message || 'Unknown error'}`);
};
const wrapOperation = (method: string) => {
return async (...args: unknown[]): Promise<unknown> => {
try {
// For createConnection, ensure readOnly is false
if (method === 'create-connection') {
const options = args[0] as SQLiteConnectionOptions;
if (options && typeof options === 'object') {
// Set readOnly to false and ensure mode is rwc
options.readOnly = false;
options.mode = 'rwc';
// Remove any lowercase readonly property if it exists
delete options.readonly;
}
}
return await withRetry(ipcRenderer.invoke, 'sqlite-' + method, ...args);
} catch (error) {
logger.error(`SQLite ${method} failed:`, error);
throw new Error(`Database operation failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
};
};
// Create a proxy that matches the CapacitorSQLite interface
return {
echo: wrapOperation('echo'),
createConnection: wrapOperation('create-connection'),
closeConnection: wrapOperation('close-connection'),
execute: wrapOperation('execute'),
query: wrapOperation('query'),
run: wrapOperation('run'),
isAvailable: wrapOperation('is-available'),
getPlatform: () => Promise.resolve('electron'),
// Add other methods as needed
};
};
// Expose only the CapacitorSQLite proxy
contextBridge.exposeInMainWorld('CapacitorSQLite', createSQLiteProxy());
// Log startup
logger.log('Script starting...');
// Handle window load
window.addEventListener('load', () => {
logger.log('Script complete');
});

6
electron/src/rt/electron-plugins.js

@ -0,0 +1,6 @@
/* eslint-disable @typescript-eslint/no-var-requires */
const CapacitorCommunitySqlite = require('../../../node_modules/@capacitor-community/sqlite/electron/dist/plugin.js');
module.exports = {
CapacitorCommunitySqlite,
}

88
electron/src/rt/electron-rt.ts

@ -0,0 +1,88 @@
import { randomBytes } from 'crypto';
import { ipcRenderer, contextBridge } from 'electron';
import { EventEmitter } from 'events';
////////////////////////////////////////////////////////
// eslint-disable-next-line @typescript-eslint/no-var-requires
const plugins = require('./electron-plugins');
const randomId = (length = 5) => randomBytes(length).toString('hex');
const contextApi: {
[plugin: string]: { [functionName: string]: () => Promise<any> };
} = {};
Object.keys(plugins).forEach((pluginKey) => {
Object.keys(plugins[pluginKey])
.filter((className) => className !== 'default')
.forEach((classKey) => {
const functionList = Object.getOwnPropertyNames(plugins[pluginKey][classKey].prototype).filter(
(v) => v !== 'constructor'
);
if (!contextApi[classKey]) {
contextApi[classKey] = {};
}
functionList.forEach((functionName) => {
if (!contextApi[classKey][functionName]) {
contextApi[classKey][functionName] = (...args) => ipcRenderer.invoke(`${classKey}-${functionName}`, ...args);
}
});
// Events
if (plugins[pluginKey][classKey].prototype instanceof EventEmitter) {
const listeners: { [key: string]: { type: string; listener: (...args: any[]) => void } } = {};
const listenersOfTypeExist = (type) =>
!!Object.values(listeners).find((listenerObj) => listenerObj.type === type);
Object.assign(contextApi[classKey], {
addListener(type: string, callback: (...args) => void) {
const id = randomId();
// Deduplicate events
if (!listenersOfTypeExist(type)) {
ipcRenderer.send(`event-add-${classKey}`, type);
}
const eventHandler = (_, ...args) => callback(...args);
ipcRenderer.addListener(`event-${classKey}-${type}`, eventHandler);
listeners[id] = { type, listener: eventHandler };
return id;
},
removeListener(id: string) {
if (!listeners[id]) {
throw new Error('Invalid id');
}
const { type, listener } = listeners[id];
ipcRenderer.removeListener(`event-${classKey}-${type}`, listener);
delete listeners[id];
if (!listenersOfTypeExist(type)) {
ipcRenderer.send(`event-remove-${classKey}-${type}`);
}
},
removeAllListeners(type: string) {
Object.entries(listeners).forEach(([id, listenerObj]) => {
if (!type || listenerObj.type === type) {
ipcRenderer.removeListener(`event-${classKey}-${listenerObj.type}`, listenerObj.listener);
ipcRenderer.send(`event-remove-${classKey}-${listenerObj.type}`);
delete listeners[id];
}
});
},
});
}
});
});
contextBridge.exposeInMainWorld('CapacitorCustomPlatform', {
name: 'electron',
plugins: contextApi,
});
////////////////////////////////////////////////////////

77
electron/src/rt/logger.ts

@ -0,0 +1,77 @@
/**
* Structured logging system for TimeSafari
*
* Provides consistent logging across the application with:
* - Timestamp tracking
* - Log levels (debug, info, warn, error)
* - Structured data support
* - Component tagging
*
* @author Matthew Raymer <matthew.raymer@anomalistdesign.com>
* @version 1.0.0
* @since 2025-06-01
*/
// Log levels
export enum LogLevel {
DEBUG = 'DEBUG',
INFO = 'INFO',
WARN = 'WARN',
ERROR = 'ERROR'
}
// Log entry interface
interface LogEntry {
timestamp: string;
level: LogLevel;
component: string;
message: string;
data?: unknown;
}
// Format log entry
const formatLogEntry = (entry: LogEntry): string => {
const { timestamp, level, component, message, data } = entry;
const dataStr = data ? ` ${JSON.stringify(data, null, 2)}` : '';
return `[${timestamp}] [${level}] [${component}] ${message}${dataStr}`;
};
// Create logger for a specific component
export const createLogger = (component: string) => {
const log = (level: LogLevel, message: string, data?: unknown) => {
const entry: LogEntry = {
timestamp: new Date().toISOString(),
level,
component,
message,
data
};
const formatted = formatLogEntry(entry);
switch (level) {
case LogLevel.DEBUG:
console.debug(formatted);
break;
case LogLevel.INFO:
console.info(formatted);
break;
case LogLevel.WARN:
console.warn(formatted);
break;
case LogLevel.ERROR:
console.error(formatted);
break;
}
};
return {
debug: (message: string, data?: unknown) => log(LogLevel.DEBUG, message, data),
info: (message: string, data?: unknown) => log(LogLevel.INFO, message, data),
warn: (message: string, data?: unknown) => log(LogLevel.WARN, message, data),
error: (message: string, data?: unknown) => log(LogLevel.ERROR, message, data)
};
};
// Create default logger for SQLite operations
export const logger = createLogger('SQLite');

584
electron/src/rt/sqlite-init.ts

@ -0,0 +1,584 @@
/**
* SQLite Initialization and Management for TimeSafari Electron
*
* This module handles the complete lifecycle of SQLite database initialization,
* connection management, and IPC communication in the TimeSafari Electron app.
*
* Key Features:
* - Database path management with proper permissions
* - Plugin initialization and state verification
* - Connection lifecycle management
* - PRAGMA configuration for optimal performance
* - Migration system integration
* - Error handling and recovery
* - IPC communication layer
*
* Database Configuration:
* - Uses WAL journal mode for better concurrency
* - Configures optimal PRAGMA settings
* - Implements connection pooling
* - Handles encryption (when enabled)
*
* State Management:
* - Tracks plugin initialization state
* - Monitors connection health
* - Manages transaction state
* - Implements recovery mechanisms
*
* Error Handling:
* - Custom SQLiteError class for detailed error tracking
* - Comprehensive error logging
* - Automatic recovery attempts
* - State verification before operations
*
* Security:
* - Proper file permissions (0o755)
* - Write access verification
* - Connection state validation
* - Transaction safety
*
* Performance:
* - WAL mode for better concurrency
* - Optimized PRAGMA settings
* - Connection pooling
* - Efficient state management
*
* @author Matthew Raymer <matthew.raymer@anomalistdesign.com>
* @version 1.0.0
* @since 2025-06-01
*/
import { app, ipcMain } from 'electron';
import { CapacitorSQLite } from '@capacitor-community/sqlite/electron/dist/plugin.js';
import * as SQLiteModule from '@capacitor-community/sqlite/electron/dist/plugin.js';
import fs from 'fs';
import path from 'path';
import os from 'os';
import { runMigrations } from './sqlite-migrations';
import { logger } from './logger';
// Types for state management
interface PluginState {
isInitialized: boolean;
isAvailable: boolean;
lastVerified: Date | null;
lastError: Error | null;
instance: any | null;
}
interface TransactionState {
isActive: boolean;
lastVerified: Date | null;
database: string | null;
}
// State tracking
let pluginState: PluginState = {
isInitialized: false,
isAvailable: false,
lastVerified: null,
lastError: null,
instance: null
};
let transactionState: TransactionState = {
isActive: false,
lastVerified: null,
database: null
};
// Constants
const MAX_RECOVERY_ATTEMPTS = 3;
const RECOVERY_DELAY_MS = 1000;
const VERIFICATION_TIMEOUT_MS = 5000;
// Error handling
class SQLiteError extends Error {
constructor(
message: string,
public context: string,
public originalError?: unknown
) {
super(message);
this.name = 'SQLiteError';
}
}
const handleError = (error: unknown, context: string): SQLiteError => {
const errorMessage = error instanceof Error
? error.message
: 'Unknown error occurred';
const errorStack = error instanceof Error
? error.stack
: undefined;
logger.error(`Error in ${context}:`, {
message: errorMessage,
stack: errorStack,
context,
timestamp: new Date().toISOString()
});
return new SQLiteError(`${context} failed: ${errorMessage}`, context, error);
};
// Add delay utility with timeout
const delay = (ms: number, timeoutMs: number = VERIFICATION_TIMEOUT_MS): Promise<void> => {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new SQLiteError('Operation timed out', 'delay'));
}, timeoutMs);
setTimeout(() => {
clearTimeout(timeout);
resolve();
}, ms);
});
};
// Plugin state verification
const verifyPluginState = async (): Promise<boolean> => {
if (!pluginState.instance || !pluginState.isInitialized) {
return false;
}
try {
// Test plugin responsiveness
const echoResult = await pluginState.instance.echo({ value: 'test' });
if (!echoResult || echoResult.value !== 'test') {
throw new SQLiteError('Plugin echo test failed', 'verifyPluginState');
}
pluginState.isAvailable = true;
pluginState.lastVerified = new Date();
pluginState.lastError = null;
return true;
} catch (error) {
pluginState.isAvailable = false;
pluginState.lastError = handleError(error, 'verifyPluginState');
return false;
}
};
// Transaction state verification
const verifyTransactionState = async (database: string): Promise<boolean> => {
if (!pluginState.instance || !pluginState.isAvailable) {
return false;
}
try {
// Check if we're in a transaction
const isActive = await pluginState.instance.isTransactionActive({ database });
transactionState.isActive = isActive;
transactionState.lastVerified = new Date();
transactionState.database = database;
return true;
} catch (error) {
transactionState.isActive = false;
transactionState.lastVerified = new Date();
transactionState.database = null;
logger.error('Transaction state verification failed:', error);
return false;
}
};
// Plugin initialization
const initializePlugin = async (): Promise<boolean> => {
logger.info('Starting plugin initialization');
try {
// Create plugin instance
let rawPlugin;
if (SQLiteModule.default?.CapacitorSQLite) {
logger.debug('Using default export CapacitorSQLite');
rawPlugin = new SQLiteModule.default.CapacitorSQLite();
} else {
logger.debug('Using direct CapacitorSQLite class');
rawPlugin = new CapacitorSQLite();
}
// Verify instance
if (!rawPlugin || typeof rawPlugin !== 'object') {
throw new SQLiteError('Invalid plugin instance created', 'initializePlugin');
}
// Test plugin functionality
const echoResult = await rawPlugin.echo({ value: 'test' });
if (!echoResult || echoResult.value !== 'test') {
throw new SQLiteError('Plugin echo test failed', 'initializePlugin');
}
// Update state only after successful verification
pluginState = {
isInitialized: true,
isAvailable: true,
lastVerified: new Date(),
lastError: null,
instance: rawPlugin
};
logger.info('Plugin initialized successfully');
return true;
} catch (error) {
pluginState = {
isInitialized: false,
isAvailable: false,
lastVerified: new Date(),
lastError: handleError(error, 'initializePlugin'),
instance: null
};
logger.error('Plugin initialization failed:', {
error: pluginState.lastError,
timestamp: new Date().toISOString()
});
return false;
}
};
// Recovery mechanism
const recoverPluginState = async (attempt: number = 1): Promise<boolean> => {
logger.info(`Attempting plugin state recovery (attempt ${attempt}/${MAX_RECOVERY_ATTEMPTS})`);
if (attempt > MAX_RECOVERY_ATTEMPTS) {
logger.error('Max recovery attempts reached');
return false;
}
try {
// Cleanup existing connection if any
if (pluginState.instance) {
try {
await pluginState.instance.closeConnection({ database: 'timesafari' });
logger.debug('Closed existing database connection during recovery');
} catch (error) {
logger.warn('Error closing connection during recovery:', error);
}
}
// Reset state
pluginState = {
isInitialized: false,
isAvailable: false,
lastVerified: new Date(),
lastError: null,
instance: null
};
// Wait before retry with exponential backoff
const backoffDelay = RECOVERY_DELAY_MS * Math.pow(2, attempt - 1);
await delay(backoffDelay);
// Reinitialize
const success = await initializePlugin();
if (!success && attempt < MAX_RECOVERY_ATTEMPTS) {
return recoverPluginState(attempt + 1);
}
return success;
} catch (error) {
logger.error('Plugin recovery failed:', error);
if (attempt < MAX_RECOVERY_ATTEMPTS) {
return recoverPluginState(attempt + 1);
}
return false;
}
};
/**
* Initializes database paths and ensures proper permissions
*
* This function:
* 1. Creates the database directory if it doesn't exist
* 2. Sets proper permissions (0o755)
* 3. Verifies write access
* 4. Returns the absolute path to the database directory
*
* @returns {Promise<string>} Absolute path to database directory
* @throws {SQLiteError} If directory creation or permission setting fails
*/
const initializeDatabasePaths = async (): Promise<string> => {
try {
// Get the absolute app data directory
const appDataDir = path.join(os.homedir(), 'Databases', 'TimeSafari');
logger.info('App data directory:', appDataDir);
// Ensure directory exists with proper permissions
if (!fs.existsSync(appDataDir)) {
await fs.promises.mkdir(appDataDir, {
recursive: true,
mode: 0o755
});
} else {
await fs.promises.chmod(appDataDir, 0o755);
}
// Verify directory permissions
const stats = await fs.promises.stat(appDataDir);
logger.info('Directory permissions:', {
mode: stats.mode.toString(8),
uid: stats.uid,
gid: stats.gid,
isDirectory: stats.isDirectory(),
isWritable: !!(stats.mode & 0o200)
});
// Test write access
const testFile = path.join(appDataDir, '.write-test');
await fs.promises.writeFile(testFile, 'test');
await fs.promises.unlink(testFile);
return appDataDir;
} catch (error) {
throw handleError(error, 'initializeDatabasePaths');
}
};
/**
* Main SQLite initialization function
*
* Orchestrates the complete database initialization process:
* 1. Sets up database paths
* 2. Initializes the SQLite plugin
* 3. Creates and verifies database connection
* 4. Configures database PRAGMAs
* 5. Runs database migrations
* 6. Handles errors and recovery
*
* Database Configuration:
* - Uses WAL journal mode
* - Enables foreign keys
* - Sets optimal page size and cache
* - Configures busy timeout
*
* Error Recovery:
* - Implements exponential backoff
* - Verifies plugin state
* - Attempts connection recovery
* - Maintains detailed error logs
*
* @throws {SQLiteError} If initialization fails and recovery is unsuccessful
*/
export async function initializeSQLite(): Promise<void> {
logger.info('Starting SQLite initialization');
try {
// Initialize database paths
const dbDir = await initializeDatabasePaths();
const dbPath = path.join(dbDir, 'timesafariSQLite.db');
// Initialize plugin
if (!await initializePlugin()) {
throw new SQLiteError('Plugin initialization failed', 'initializeSQLite');
}
// Verify plugin state
if (!await verifyPluginState()) {
throw new SQLiteError('Plugin state verification failed', 'initializeSQLite');
}
// Set up database connection
const connectionOptions = {
database: 'timesafari',
version: 1,
readOnly: false,
encryption: 'no-encryption',
useNative: true,
mode: 'rwc'
};
// Create and verify connection
logger.debug('Creating database connection:', connectionOptions);
await pluginState.instance.createConnection(connectionOptions);
await delay(500); // Wait for connection registration
const isRegistered = await pluginState.instance.isDatabase({
database: connectionOptions.database
});
if (!isRegistered) {
throw new SQLiteError('Database not registered', 'initializeSQLite');
}
// Open database
logger.debug('Opening database with options:', connectionOptions);
await pluginState.instance.open({
...connectionOptions,
mode: 'rwc'
});
// Set PRAGMAs with detailed logging
const pragmaStatements = [
'PRAGMA foreign_keys = ON;',
'PRAGMA journal_mode = WAL;', // Changed to WAL for better concurrency
'PRAGMA synchronous = NORMAL;',
'PRAGMA temp_store = MEMORY;',
'PRAGMA page_size = 4096;',
'PRAGMA cache_size = 2000;',
'PRAGMA busy_timeout = 15000;', // Increased to 15 seconds
'PRAGMA wal_autocheckpoint = 1000;' // Added WAL checkpoint setting
];
logger.debug('Setting database PRAGMAs');
for (const statement of pragmaStatements) {
try {
logger.debug('Executing PRAGMA:', statement);
const result = await pluginState.instance.execute({
database: connectionOptions.database,
statements: statement,
transaction: false
});
logger.debug('PRAGMA result:', { statement, result });
} catch (error) {
logger.error('PRAGMA execution failed:', {
statement,
error: error instanceof Error ? {
message: error.message,
stack: error.stack,
name: error.name
} : error
});
throw error;
}
}
// Run migrations with enhanced error logging
logger.info('Starting database migrations');
const migrationResults = await runMigrations(
pluginState.instance,
connectionOptions.database
);
// Check migration results with detailed logging
const failedMigrations = migrationResults.filter(r => !r.success);
if (failedMigrations.length > 0) {
logger.error('Migration failures:', {
totalMigrations: migrationResults.length,
failedCount: failedMigrations.length,
failures: failedMigrations.map(f => ({
version: f.version,
name: f.name,
error: f.error instanceof Error ? {
message: f.error.message,
stack: f.error.stack,
name: f.error.name
} : f.error,
state: f.state
}))
});
throw new SQLiteError(
'Database migrations failed',
'initializeSQLite',
failedMigrations
);
}
logger.info('SQLite initialization completed successfully');
} catch (error) {
const sqliteError = handleError(error, 'initializeSQLite');
logger.error('SQLite initialization failed:', {
error: sqliteError,
pluginState: {
isInitialized: pluginState.isInitialized,
isAvailable: pluginState.isAvailable,
lastVerified: pluginState.lastVerified,
lastError: pluginState.lastError
}
});
// Attempt recovery
if (await recoverPluginState()) {
logger.info('Recovery successful, retrying initialization');
return initializeSQLite();
}
throw sqliteError;
}
}
/**
* Sets up IPC handlers for SQLite operations
*
* Registers handlers for:
* - Plugin availability checks
* - Connection management
* - Query execution
* - Error retrieval
*
* Each handler includes:
* - State verification
* - Error handling
* - Detailed logging
* - Transaction safety
*
* Security:
* - Validates all incoming requests
* - Verifies plugin state
* - Maintains connection isolation
*
* @throws {Error} If handler registration fails
*/
export function setupSQLiteHandlers(): void {
// Remove existing handlers
const handlers = [
'sqlite-is-available',
'sqlite-echo',
'sqlite-create-connection',
'sqlite-execute',
'sqlite-query',
'sqlite-close-connection',
'sqlite-get-error'
];
handlers.forEach(handler => {
try {
ipcMain.removeHandler(handler);
} catch (error) {
logger.warn(`Error removing handler ${handler}:`, error);
}
});
// Register handlers
ipcMain.handle('sqlite-is-available', async () => {
try {
const isAvailable = await verifyPluginState();
logger.debug('Plugin availability check:', { isAvailable });
return isAvailable;
} catch (error) {
logger.error('Error checking plugin availability:', error);
return false;
}
});
ipcMain.handle('sqlite-get-error', async () => {
return pluginState.lastError ? {
message: pluginState.lastError.message,
stack: pluginState.lastError.stack,
name: pluginState.lastError.name,
context: (pluginState.lastError as SQLiteError).context
} : null;
});
// Add other handlers with proper state verification
ipcMain.handle('sqlite-create-connection', async (_event, options) => {
try {
if (!await verifyPluginState()) {
throw new SQLiteError('Plugin not available', 'sqlite-create-connection');
}
// ... rest of connection creation logic ...
} catch (error) {
throw handleError(error, 'sqlite-create-connection');
}
});
// ... other handlers ...
logger.info('SQLite IPC handlers registered successfully');
}

950
electron/src/rt/sqlite-migrations.ts

@ -0,0 +1,950 @@
/**
* SQLite Migration System for TimeSafari
*
* A robust migration system for managing database schema changes in the TimeSafari
* application. Provides versioned migrations with transaction safety, rollback
* support, and detailed logging.
*
* Core Features:
* - Versioned migrations with tracking
* - Atomic transactions per migration
* - Comprehensive error handling
* - SQL parsing and validation
* - State verification and recovery
* - Detailed logging and debugging
*
* Migration Process:
* 1. Version tracking via schema_version table
* 2. Transaction-based execution
* 3. Automatic rollback on failure
* 4. State verification before/after
* 5. Detailed error logging
*
* SQL Processing:
* - Handles single-line (--) and multi-line comments
* - Validates SQL statements
* - Proper statement separation
* - SQL injection prevention
* - Parameter binding safety
*
* Transaction Management:
* - Single transaction per migration
* - Automatic rollback on failure
* - State verification
* - Deadlock prevention
* - Connection isolation
*
* Error Handling:
* - Detailed error reporting
* - SQL validation
* - Transaction state tracking
* - Recovery mechanisms
* - Debug logging
*
* Security:
* - SQL injection prevention
* - Parameter validation
* - Transaction isolation
* - State verification
* - Error sanitization
*
* Performance:
* - Efficient SQL parsing
* - Optimized transactions
* - Minimal locking
* - Connection pooling
* - Statement reuse
*
* @author Matthew Raymer <matthew.raymer@anomalistdesign.com>
* @version 1.0.0
* @since 2025-06-01
*/
import { CapacitorSQLite } from '@capacitor-community/sqlite/electron/dist/plugin.js';
import { logger } from './logger';
// Types for migration system
interface Migration {
version: number;
name: string;
description: string;
sql: string;
rollback?: string;
}
interface MigrationResult {
success: boolean;
version: number;
name: string;
error?: Error;
state?: {
plugin: {
isAvailable: boolean;
lastChecked: Date;
};
transaction: {
isActive: boolean;
lastVerified: Date;
};
};
}
interface MigrationState {
currentVersion: number;
lastMigration: string;
lastApplied: Date;
isDirty: boolean;
}
// Constants
const MIGRATIONS_TABLE = `
CREATE TABLE IF NOT EXISTS schema_version (
version INTEGER NOT NULL,
name TEXT NOT NULL,
description TEXT,
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
checksum TEXT,
is_dirty BOOLEAN DEFAULT FALSE,
error_message TEXT,
error_stack TEXT,
error_context TEXT,
PRIMARY KEY (version)
);`;
// Constants for retry logic
const MAX_RETRY_ATTEMPTS = 3;
const RETRY_DELAY_MS = 1000;
const LOCK_TIMEOUT_MS = 10000; // 10 seconds total timeout for locks
/**
* Utility function to delay execution
* @param ms Milliseconds to delay
* @returns Promise that resolves after the delay
*/
const delay = (ms: number): Promise<void> => {
return new Promise(resolve => setTimeout(resolve, ms));
};
// SQL Parsing Utilities
interface ParsedSQL {
statements: string[];
errors: string[];
warnings: string[];
}
/**
* Removes SQL comments from a string while preserving statement structure
* @param sql The SQL string to process
* @returns SQL with comments removed
*/
const removeSQLComments = (sql: string): string => {
let result = '';
let inSingleLineComment = false;
let inMultiLineComment = false;
let inString = false;
let stringChar = '';
let i = 0;
while (i < sql.length) {
const char = sql[i];
const nextChar = sql[i + 1] || '';
// Handle string literals
if ((char === "'" || char === '"') && !inSingleLineComment && !inMultiLineComment) {
if (!inString) {
inString = true;
stringChar = char;
} else if (char === stringChar) {
inString = false;
}
result += char;
i++;
continue;
}
// Handle single-line comments
if (char === '-' && nextChar === '-' && !inString && !inMultiLineComment) {
inSingleLineComment = true;
i += 2;
continue;
}
// Handle multi-line comments
if (char === '/' && nextChar === '*' && !inString && !inSingleLineComment) {
inMultiLineComment = true;
i += 2;
continue;
}
if (char === '*' && nextChar === '/' && inMultiLineComment) {
inMultiLineComment = false;
i += 2;
continue;
}
// Handle newlines in single-line comments
if (char === '\n' && inSingleLineComment) {
inSingleLineComment = false;
result += '\n';
i++;
continue;
}
// Add character if not in any comment
if (!inSingleLineComment && !inMultiLineComment) {
result += char;
}
i++;
}
return result;
};
/**
* Formats a SQL statement for consistent processing
* @param sql The SQL statement to format
* @returns Formatted SQL statement
*/
const formatSQLStatement = (sql: string): string => {
return sql
.trim()
.replace(/\s+/g, ' ') // Replace multiple spaces with single space
.replace(/\s*;\s*$/, ';') // Ensure semicolon at end
.replace(/^\s*;\s*/, ''); // Remove leading semicolon
};
/**
* Validates a SQL statement for common issues
* @param statement The SQL statement to validate
* @returns Array of validation errors, empty if valid
*/
const validateSQLStatement = (statement: string): string[] => {
const errors: string[] = [];
const trimmed = statement.trim().toLowerCase();
// Check for empty statements
if (!trimmed) {
errors.push('Empty SQL statement');
return errors;
}
// Check for valid statement types
const validStarts = [
'create', 'alter', 'drop', 'insert', 'update', 'delete',
'select', 'pragma', 'begin', 'commit', 'rollback'
];
const startsWithValid = validStarts.some(start => trimmed.startsWith(start));
if (!startsWithValid) {
errors.push(`Invalid SQL statement type: ${trimmed.split(' ')[0]}`);
}
// Check for balanced parentheses
let parenCount = 0;
let inString = false;
let stringChar = '';
for (let i = 0; i < statement.length; i++) {
const char = statement[i];
if ((char === "'" || char === '"') && !inString) {
inString = true;
stringChar = char;
} else if (char === stringChar && inString) {
inString = false;
}
if (!inString) {
if (char === '(') parenCount++;
if (char === ')') parenCount--;
}
}
if (parenCount !== 0) {
errors.push('Unbalanced parentheses in SQL statement');
}
return errors;
};
/**
* Parses SQL into individual statements with validation
* @param sql The SQL to parse
* @returns ParsedSQL object containing statements and any errors/warnings
*/
const parseSQL = (sql: string): ParsedSQL => {
const result: ParsedSQL = {
statements: [],
errors: [],
warnings: []
};
try {
// Remove comments first
const cleanSQL = removeSQLComments(sql);
// Split on semicolons and process each statement
const rawStatements = cleanSQL
.split(';')
.map(s => formatSQLStatement(s))
.filter(s => s.length > 0);
// Validate each statement
for (const statement of rawStatements) {
const errors = validateSQLStatement(statement);
if (errors.length > 0) {
result.errors.push(...errors.map(e => `${e} in statement: ${statement.substring(0, 50)}...`));
} else {
result.statements.push(statement);
}
}
// Add warnings for potential issues
if (rawStatements.length === 0) {
result.warnings.push('No SQL statements found after parsing');
}
// Log parsing results
logger.debug('SQL parsing results:', {
statementCount: result.statements.length,
errorCount: result.errors.length,
warningCount: result.warnings.length,
statements: result.statements.map(s => s.substring(0, 50) + '...'),
errors: result.errors,
warnings: result.warnings
});
} catch (error) {
result.errors.push(`SQL parsing failed: ${error instanceof Error ? error.message : String(error)}`);
logger.error('SQL parsing error:', error);
}
return result;
};
// Initial migration for accounts table
const INITIAL_MIGRATION: Migration = {
version: 1,
name: '001_initial_accounts',
description: 'Initial schema with accounts table',
sql: `
/* Create accounts table with required fields */
CREATE TABLE IF NOT EXISTS accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
dateCreated TEXT NOT NULL,
derivationPath TEXT,
did TEXT NOT NULL,
identityEncrBase64 TEXT, -- encrypted & base64-encoded
mnemonicEncrBase64 TEXT, -- encrypted & base64-encoded
passkeyCredIdHex TEXT,
publicKeyHex TEXT NOT NULL
);
/* Create index on did for faster lookups */
CREATE INDEX IF NOT EXISTS idx_accounts_did ON accounts(did);
`,
rollback: `
/* Drop index first to avoid foreign key issues */
DROP INDEX IF EXISTS idx_accounts_did;
/* Drop the accounts table */
DROP TABLE IF EXISTS accounts;
`
};
// Migration registry
const MIGRATIONS: Migration[] = [
INITIAL_MIGRATION
];
// Helper functions
const verifyPluginState = async (plugin: any): Promise<boolean> => {
try {
const result = await plugin.echo({ value: 'test' });
return result?.value === 'test';
} catch (error) {
logger.error('Plugin state verification failed:', error);
return false;
}
};
// Helper function to verify transaction state without starting a transaction
const verifyTransactionState = async (
plugin: any,
database: string
): Promise<boolean> => {
try {
// Query SQLite's internal transaction state
const result = await plugin.query({
database,
statement: "SELECT * FROM sqlite_master WHERE type='table' AND name='schema_version';"
});
// If we can query, we're not in a transaction
return false;
} catch (error) {
// If error contains "transaction", we're probably in a transaction
const errorMsg = error instanceof Error ? error.message : String(error);
const inTransaction = errorMsg.toLowerCase().includes('transaction');
logger.debug('Transaction state check:', {
inTransaction,
error: error instanceof Error ? {
message: error.message,
name: error.name
} : error
});
return inTransaction;
}
};
const getCurrentVersion = async (
plugin: any,
database: string
): Promise<number> => {
try {
const result = await plugin.query({
database,
statement: 'SELECT version FROM schema_version ORDER BY version DESC LIMIT 1;'
});
return result?.values?.[0]?.version || 0;
} catch (error) {
logger.error('Error getting current version:', error);
return 0;
}
};
/**
* Helper function to execute SQL with retry logic for locked database
* @param plugin SQLite plugin instance
* @param database Database name
* @param operation Function to execute
* @param context Operation context for logging
*/
const executeWithRetry = async <T>(
plugin: any,
database: string,
operation: () => Promise<T>,
context: string
): Promise<T> => {
let lastError: Error | null = null;
let startTime = Date.now();
for (let attempt = 1; attempt <= MAX_RETRY_ATTEMPTS; attempt++) {
try {
// Check if we've exceeded the total timeout
if (Date.now() - startTime > LOCK_TIMEOUT_MS) {
throw new Error(`Operation timed out after ${LOCK_TIMEOUT_MS}ms`);
}
// Try the operation
return await operation();
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
const errorMsg = lastError.message.toLowerCase();
const isLockError = errorMsg.includes('database is locked') ||
errorMsg.includes('database is busy') ||
errorMsg.includes('database is locked (5)');
if (!isLockError || attempt === MAX_RETRY_ATTEMPTS) {
throw lastError;
}
logger.warn(`Database operation failed, retrying (${attempt}/${MAX_RETRY_ATTEMPTS}):`, {
context,
error: lastError.message,
attempt,
elapsedMs: Date.now() - startTime
});
// Exponential backoff
const backoffDelay = RETRY_DELAY_MS * Math.pow(2, attempt - 1);
await delay(Math.min(backoffDelay, LOCK_TIMEOUT_MS - (Date.now() - startTime)));
}
}
throw lastError || new Error(`Operation failed after ${MAX_RETRY_ATTEMPTS} attempts`);
};
// Helper function to execute a single SQL statement with retry logic
const executeSingleStatement = async (
plugin: any,
database: string,
statement: string,
values: any[] = []
): Promise<any> => {
logger.debug('Executing SQL statement:', {
statement: statement.substring(0, 100) + (statement.length > 100 ? '...' : ''),
values: values.map(v => ({
value: v,
type: typeof v,
isNull: v === null || v === undefined
}))
});
return executeWithRetry(
plugin,
database,
async () => {
// Validate values before execution
if (statement.includes('schema_version') && statement.includes('INSERT')) {
// Find the name parameter index in the SQL statement
const paramIndex = statement.toLowerCase().split(',').findIndex(p =>
p.trim().startsWith('name')
);
if (paramIndex !== -1 && values[paramIndex] !== undefined) {
const nameValue = values[paramIndex];
if (!nameValue || typeof nameValue !== 'string') {
throw new Error(`Invalid migration name type: ${typeof nameValue}`);
}
if (nameValue.trim().length === 0) {
throw new Error('Migration name cannot be empty');
}
// Ensure we're using the actual migration name, not the version
if (nameValue === values[0]?.toString()) {
throw new Error('Migration name cannot be the same as version number');
}
logger.debug('Validated migration name:', {
name: nameValue,
type: typeof nameValue,
length: nameValue.length
});
}
}
const result = await plugin.execute({
database,
statements: statement,
values,
transaction: false
});
logger.debug('SQL execution result:', {
statement: statement.substring(0, 100) + (statement.length > 100 ? '...' : ''),
result
});
return result;
},
'executeSingleStatement'
);
};
// Helper function to create migrations table if it doesn't exist
const ensureMigrationsTable = async (
plugin: any,
database: string
): Promise<void> => {
logger.debug('Ensuring migrations table exists');
try {
// Drop and recreate the table to ensure proper structure
await plugin.execute({
database,
statements: 'DROP TABLE IF EXISTS schema_version;',
transaction: false
});
// Create the table with proper constraints
await plugin.execute({
database,
statements: MIGRATIONS_TABLE,
transaction: false
});
// Verify table creation and structure
const tableInfo = await plugin.query({
database,
statement: "PRAGMA table_info(schema_version);"
});
logger.debug('Schema version table structure:', {
columns: tableInfo?.values?.map((row: any) => ({
name: row.name,
type: row.type,
notnull: row.notnull,
dflt_value: row.dflt_value
}))
});
// Verify table was created
const verifyCheck = await plugin.query({
database,
statement: "SELECT name FROM sqlite_master WHERE type='table' AND name='schema_version';"
});
if (!verifyCheck?.values?.length) {
throw new Error('Failed to create migrations table');
}
logger.debug('Migrations table created successfully');
} catch (error) {
logger.error('Error ensuring migrations table:', {
error: error instanceof Error ? {
message: error.message,
stack: error.stack,
name: error.name
} : error
});
throw error;
}
};
// Update the parseMigrationStatements function to use the new parser
const parseMigrationStatements = (sql: string): string[] => {
const parsed = parseSQL(sql);
if (parsed.errors.length > 0) {
throw new Error(`SQL validation failed:\n${parsed.errors.join('\n')}`);
}
if (parsed.warnings.length > 0) {
logger.warn('SQL parsing warnings:', parsed.warnings);
}
return parsed.statements;
};
// Add debug helper function
const debugTableState = async (
plugin: any,
database: string,
context: string
): Promise<void> => {
try {
const tableInfo = await plugin.query({
database,
statement: "PRAGMA table_info(schema_version);"
});
const tableData = await plugin.query({
database,
statement: "SELECT * FROM schema_version;"
});
logger.debug(`Table state (${context}):`, {
tableInfo: tableInfo?.values?.map((row: any) => ({
name: row.name,
type: row.type,
notnull: row.notnull,
dflt_value: row.dflt_value
})),
tableData: tableData?.values,
rowCount: tableData?.values?.length || 0
});
} catch (error) {
logger.error(`Error getting table state (${context}):`, error);
}
};
/**
* Executes a single migration with full transaction safety
*
* Process:
* 1. Verifies plugin and transaction state
* 2. Parses and validates SQL
* 3. Executes in transaction
* 4. Updates schema version
* 5. Verifies success
*
* Error Handling:
* - Automatic rollback on failure
* - Detailed error logging
* - State verification
* - Recovery attempts
*
* @param plugin SQLite plugin instance
* @param database Database name
* @param migration Migration to execute
* @returns {Promise<MigrationResult>} Result of migration execution
* @throws {Error} If migration fails and cannot be recovered
*/
const executeMigration = async (
plugin: any,
database: string,
migration: Migration
): Promise<MigrationResult> => {
const startTime = Date.now();
const statements = parseMigrationStatements(migration.sql);
let transactionStarted = false;
logger.info(`Starting migration ${migration.version}: ${migration.name}`, {
migration: {
version: migration.version,
name: migration.name,
description: migration.description,
statementCount: statements.length
}
});
try {
// Debug table state before migration
await debugTableState(plugin, database, 'before_migration');
// Ensure migrations table exists with retry
await executeWithRetry(
plugin,
database,
() => ensureMigrationsTable(plugin, database),
'ensureMigrationsTable'
);
// Verify plugin state
const pluginState = await verifyPluginState(plugin);
if (!pluginState) {
throw new Error('Plugin not available');
}
// Start transaction with retry
await executeWithRetry(
plugin,
database,
async () => {
await plugin.beginTransaction({ database });
transactionStarted = true;
},
'beginTransaction'
);
try {
// Execute each statement with retry
for (let i = 0; i < statements.length; i++) {
const statement = statements[i];
await executeWithRetry(
plugin,
database,
() => executeSingleStatement(plugin, database, statement),
`executeStatement_${i + 1}`
);
}
// Commit transaction before updating schema version
await executeWithRetry(
plugin,
database,
async () => {
await plugin.commitTransaction({ database });
transactionStarted = false;
},
'commitTransaction'
);
// Update schema version outside of transaction with enhanced debugging
await executeWithRetry(
plugin,
database,
async () => {
logger.debug('Preparing schema version update:', {
version: migration.version,
name: migration.name.trim(),
description: migration.description,
nameType: typeof migration.name,
nameLength: migration.name.length,
nameTrimmedLength: migration.name.trim().length,
nameIsEmpty: migration.name.trim().length === 0
});
// Use direct SQL with properly escaped values
const escapedName = migration.name.trim().replace(/'/g, "''");
const escapedDesc = (migration.description || '').replace(/'/g, "''");
const insertSql = `INSERT INTO schema_version (version, name, description) VALUES (${migration.version}, '${escapedName}', '${escapedDesc}')`;
logger.debug('Executing schema version update:', {
sql: insertSql,
originalValues: {
version: migration.version,
name: migration.name.trim(),
description: migration.description
}
});
// Debug table state before insert
await debugTableState(plugin, database, 'before_insert');
const result = await plugin.execute({
database,
statements: insertSql,
transaction: false
});
logger.debug('Schema version update result:', {
result,
sql: insertSql
});
// Debug table state after insert
await debugTableState(plugin, database, 'after_insert');
// Verify the insert
const verifyQuery = await plugin.query({
database,
statement: `SELECT * FROM schema_version WHERE version = ${migration.version} AND name = '${escapedName}'`
});
logger.debug('Schema version verification:', {
found: verifyQuery?.values?.length > 0,
rowCount: verifyQuery?.values?.length || 0,
data: verifyQuery?.values
});
},
'updateSchemaVersion'
);
const duration = Date.now() - startTime;
logger.info(`Migration ${migration.version} completed in ${duration}ms`);
return {
success: true,
version: migration.version,
name: migration.name,
state: {
plugin: { isAvailable: true, lastChecked: new Date() },
transaction: { isActive: false, lastVerified: new Date() }
}
};
} catch (error) {
// Rollback with retry
if (transactionStarted) {
try {
await executeWithRetry(
plugin,
database,
async () => {
// Record error in schema_version before rollback
await executeSingleStatement(
plugin,
database,
`INSERT INTO schema_version (
version, name, description, applied_at,
error_message, error_stack, error_context
) VALUES (?, ?, ?, CURRENT_TIMESTAMP, ?, ?, ?);`,
[
migration.version,
migration.name,
migration.description,
error instanceof Error ? error.message : String(error),
error instanceof Error ? error.stack : null,
'migration_execution'
]
);
await plugin.rollbackTransaction({ database });
},
'rollbackTransaction'
);
} catch (rollbackError) {
logger.error('Error during rollback:', {
originalError: error,
rollbackError
});
}
}
throw error;
}
} catch (error) {
// Debug table state on error
await debugTableState(plugin, database, 'on_error');
logger.error('Migration execution failed:', {
error: error instanceof Error ? {
message: error.message,
stack: error.stack,
name: error.name
} : error,
migration: {
version: migration.version,
name: migration.name,
nameType: typeof migration.name,
nameLength: migration.name.length,
nameTrimmedLength: migration.name.trim().length
}
});
return {
success: false,
version: migration.version,
name: migration.name,
error: error instanceof Error ? error : new Error(String(error)),
state: {
plugin: { isAvailable: true, lastChecked: new Date() },
transaction: { isActive: false, lastVerified: new Date() }
}
};
}
};
/**
* Main migration runner
*
* Orchestrates the complete migration process:
* 1. Verifies plugin state
* 2. Ensures migrations table
* 3. Determines pending migrations
* 4. Executes migrations in order
* 5. Verifies results
*
* Features:
* - Version-based ordering
* - Transaction safety
* - Error recovery
* - State verification
* - Detailed logging
*
* @param plugin SQLite plugin instance
* @param database Database name
* @returns {Promise<MigrationResult[]>} Results of all migrations
* @throws {Error} If migration process fails
*/
export async function runMigrations(
plugin: any,
database: string
): Promise<MigrationResult[]> {
logger.info('Starting migration process');
// Verify plugin is available
if (!await verifyPluginState(plugin)) {
throw new Error('SQLite plugin not available');
}
// Ensure migrations table exists before any migrations
try {
await ensureMigrationsTable(plugin, database);
} catch (error) {
logger.error('Failed to ensure migrations table:', error);
throw new Error('Failed to initialize migrations system');
}
// Get current version
const currentVersion = await getCurrentVersion(plugin, database);
logger.info(`Current database version: ${currentVersion}`);
// Find pending migrations
const pendingMigrations = MIGRATIONS.filter(m => m.version > currentVersion);
if (pendingMigrations.length === 0) {
logger.info('No pending migrations');
return [];
}
logger.info(`Found ${pendingMigrations.length} pending migrations`);
// Execute each migration
const results: MigrationResult[] = [];
for (const migration of pendingMigrations) {
const result = await executeMigration(plugin, database, migration);
results.push(result);
if (!result.success) {
logger.error(`Migration failed at version ${migration.version}`);
break;
}
}
return results;
}
// Export types for use in other modules
export type { Migration, MigrationResult, MigrationState };

244
electron/src/setup.ts

@ -0,0 +1,244 @@
import type { CapacitorElectronConfig } from '@capacitor-community/electron';
import {
CapElectronEventEmitter,
CapacitorSplashScreen,
setupCapacitorElectronPlugins,
} from '@capacitor-community/electron';
import chokidar from 'chokidar';
import type { MenuItemConstructorOptions } from 'electron';
import { app, BrowserWindow, Menu, MenuItem, nativeImage, Tray, session } from 'electron';
import electronIsDev from 'electron-is-dev';
import electronServe from 'electron-serve';
import windowStateKeeper from 'electron-window-state';
import { join } from 'path';
// Define components for a watcher to detect when the webapp is changed so we can reload in Dev mode.
const reloadWatcher = {
debouncer: null,
ready: false,
watcher: null,
};
export function setupReloadWatcher(electronCapacitorApp: ElectronCapacitorApp): void {
reloadWatcher.watcher = chokidar
.watch(join(app.getAppPath(), 'app'), {
ignored: /[/\\]\./,
persistent: true,
})
.on('ready', () => {
reloadWatcher.ready = true;
})
.on('all', (_event, _path) => {
if (reloadWatcher.ready) {
clearTimeout(reloadWatcher.debouncer);
reloadWatcher.debouncer = setTimeout(async () => {
electronCapacitorApp.getMainWindow().webContents.reload();
reloadWatcher.ready = false;
clearTimeout(reloadWatcher.debouncer);
reloadWatcher.debouncer = null;
reloadWatcher.watcher = null;
setupReloadWatcher(electronCapacitorApp);
}, 1500);
}
});
}
// Define our class to manage our app.
export class ElectronCapacitorApp {
private MainWindow: BrowserWindow | null = null;
private SplashScreen: CapacitorSplashScreen | null = null;
private TrayIcon: Tray | null = null;
private CapacitorFileConfig: CapacitorElectronConfig;
private TrayMenuTemplate: (MenuItem | MenuItemConstructorOptions)[] = [
new MenuItem({ label: 'Quit App', role: 'quit' }),
];
private AppMenuBarMenuTemplate: (MenuItem | MenuItemConstructorOptions)[] = [
{ role: process.platform === 'darwin' ? 'appMenu' : 'fileMenu' },
{ role: 'viewMenu' },
];
private mainWindowState;
private loadWebApp;
private customScheme: string;
constructor(
capacitorFileConfig: CapacitorElectronConfig,
trayMenuTemplate?: (MenuItemConstructorOptions | MenuItem)[],
appMenuBarMenuTemplate?: (MenuItemConstructorOptions | MenuItem)[]
) {
this.CapacitorFileConfig = capacitorFileConfig;
this.customScheme = this.CapacitorFileConfig.electron?.customUrlScheme ?? 'capacitor-electron';
if (trayMenuTemplate) {
this.TrayMenuTemplate = trayMenuTemplate;
}
if (appMenuBarMenuTemplate) {
this.AppMenuBarMenuTemplate = appMenuBarMenuTemplate;
}
// Setup our web app loader, this lets us load apps like react, vue, and angular without changing their build chains.
this.loadWebApp = electronServe({
directory: join(app.getAppPath(), 'app'),
scheme: this.customScheme,
});
}
// Helper function to load in the app.
private async loadMainWindow(thisRef: any) {
await thisRef.loadWebApp(thisRef.MainWindow);
}
// Expose the mainWindow ref for use outside of the class.
getMainWindow(): BrowserWindow {
return this.MainWindow;
}
getCustomURLScheme(): string {
return this.customScheme;
}
async init(): Promise<void> {
const icon = nativeImage.createFromPath(
join(app.getAppPath(), 'assets', process.platform === 'win32' ? 'appIcon.ico' : 'appIcon.png')
);
this.mainWindowState = windowStateKeeper({
defaultWidth: 1000,
defaultHeight: 800,
});
// Setup preload script path and construct our main window.
const preloadPath = join(app.getAppPath(), 'build', 'src', 'preload.js');
this.MainWindow = new BrowserWindow({
icon,
show: false,
x: this.mainWindowState.x,
y: this.mainWindowState.y,
width: this.mainWindowState.width,
height: this.mainWindowState.height,
webPreferences: {
nodeIntegration: true,
contextIsolation: true,
// Use preload to inject the electron varriant overrides for capacitor plugins.
// preload: join(app.getAppPath(), "node_modules", "@capacitor-community", "electron", "dist", "runtime", "electron-rt.js"),
preload: preloadPath,
},
});
this.mainWindowState.manage(this.MainWindow);
if (this.CapacitorFileConfig.backgroundColor) {
this.MainWindow.setBackgroundColor(this.CapacitorFileConfig.electron.backgroundColor);
}
// If we close the main window with the splashscreen enabled we need to destory the ref.
this.MainWindow.on('closed', () => {
if (this.SplashScreen?.getSplashWindow() && !this.SplashScreen.getSplashWindow().isDestroyed()) {
this.SplashScreen.getSplashWindow().close();
}
});
// When the tray icon is enabled, setup the options.
if (this.CapacitorFileConfig.electron?.trayIconAndMenuEnabled) {
this.TrayIcon = new Tray(icon);
this.TrayIcon.on('double-click', () => {
if (this.MainWindow) {
if (this.MainWindow.isVisible()) {
this.MainWindow.hide();
} else {
this.MainWindow.show();
this.MainWindow.focus();
}
}
});
this.TrayIcon.on('click', () => {
if (this.MainWindow) {
if (this.MainWindow.isVisible()) {
this.MainWindow.hide();
} else {
this.MainWindow.show();
this.MainWindow.focus();
}
}
});
this.TrayIcon.setToolTip(app.getName());
this.TrayIcon.setContextMenu(Menu.buildFromTemplate(this.TrayMenuTemplate));
}
// Setup the main manu bar at the top of our window.
Menu.setApplicationMenu(Menu.buildFromTemplate(this.AppMenuBarMenuTemplate));
// If the splashscreen is enabled, show it first while the main window loads then switch it out for the main window, or just load the main window from the start.
if (this.CapacitorFileConfig.electron?.splashScreenEnabled) {
this.SplashScreen = new CapacitorSplashScreen({
imageFilePath: join(
app.getAppPath(),
'assets',
this.CapacitorFileConfig.electron?.splashScreenImageName ?? 'splash.png'
),
windowWidth: 400,
windowHeight: 400,
});
this.SplashScreen.init(this.loadMainWindow, this);
} else {
this.loadMainWindow(this);
}
// Security
this.MainWindow.webContents.setWindowOpenHandler((details) => {
if (!details.url.includes(this.customScheme)) {
return { action: 'deny' };
} else {
return { action: 'allow' };
}
});
this.MainWindow.webContents.on('will-navigate', (event, _newURL) => {
if (!this.MainWindow.webContents.getURL().includes(this.customScheme)) {
event.preventDefault();
}
});
// Link electron plugins into the system.
setupCapacitorElectronPlugins();
// When the web app is loaded we hide the splashscreen if needed and show the mainwindow.
this.MainWindow.webContents.on('dom-ready', () => {
if (this.CapacitorFileConfig.electron?.splashScreenEnabled) {
this.SplashScreen.getSplashWindow().hide();
}
if (!this.CapacitorFileConfig.electron?.hideMainWindowOnLaunch) {
this.MainWindow.show();
}
setTimeout(() => {
if (electronIsDev) {
this.MainWindow.webContents.openDevTools();
}
CapElectronEventEmitter.emit('CAPELECTRON_DeeplinkListenerInitialized', '');
}, 400);
});
}
}
// Set a CSP up for our application based on the custom scheme
export function setupContentSecurityPolicy(customScheme: string): void {
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
callback({
responseHeaders: {
...details.responseHeaders,
'Content-Security-Policy': [
// Base CSP for both dev and prod
`default-src ${customScheme}://* 'unsafe-inline' data:;`,
// Allow Google Fonts
`style-src ${customScheme}://* 'unsafe-inline' https://fonts.googleapis.com;`,
`font-src ${customScheme}://* https://fonts.gstatic.com;`,
// Allow images and media
`img-src ${customScheme}://* data: https:;`,
// Allow connections to HTTPS resources
`connect-src ${customScheme}://* https:;`,
// Add dev-specific policies
...(electronIsDev ? [
`script-src ${customScheme}://* 'unsafe-inline' 'unsafe-eval' devtools://*;`,
`default-src ${customScheme}://* 'unsafe-inline' devtools://* 'unsafe-eval' data:;`
] : [])
].join(' ')
},
});
});
}

18
electron/tsconfig.json

@ -0,0 +1,18 @@
{
"compileOnSave": true,
"include": ["./src/**/*", "./capacitor.config.ts", "./capacitor.config.js"],
"compilerOptions": {
"outDir": "./build",
"importHelpers": true,
"target": "ES2020",
"module": "CommonJS",
"moduleResolution": "node",
"esModuleInterop": true,
"typeRoots": ["./node_modules/@types"],
"allowJs": true,
"rootDir": ".",
"skipLibCheck": true,
"resolveJsonModule": true
}
}

186
experiment.sh

@ -0,0 +1,186 @@
#!/bin/bash
# experiment.sh
# Author: Matthew Raymer
# Description: Build script for TimeSafari Electron application
# This script handles the complete build process for the TimeSafari Electron app,
# including web asset compilation, TypeScript compilation, and AppImage packaging.
# It ensures all dependencies are available and provides detailed build feedback.
#
# Build Process:
# 1. Environment setup and dependency checks
# 2. Web asset compilation (Vite)
# 3. TypeScript compilation
# 4. Electron main process build
# 5. AppImage packaging
#
# Dependencies:
# - Node.js and npm
# - TypeScript
# - Vite
# - electron-builder
#
# Usage: ./experiment.sh
#
# Exit Codes:
# 1 - Required command not found
# 2 - TypeScript installation failed
# 3 - TypeScript compilation failed
# 4 - Build process failed
# 5 - AppImage build failed
# Exit on any error
set -e
# ANSI color codes for better output formatting
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly NC='\033[0m' # No Color
# Logging functions
log_info() {
echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')] [INFO]${NC} $1"
}
log_success() {
echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] [SUCCESS]${NC} $1"
}
log_warn() {
echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] [WARN]${NC} $1"
}
log_error() {
echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] [ERROR]${NC} $1"
}
# Function to check if a command exists
check_command() {
if ! command -v "$1" &> /dev/null; then
log_error "$1 is required but not installed."
exit 1
fi
log_info "Found $1: $(command -v "$1")"
}
# Function to measure and log execution time
measure_time() {
local start_time=$(date +%s)
"$@"
local end_time=$(date +%s)
local duration=$((end_time - start_time))
log_success "Completed in ${duration} seconds"
}
# Function to find the AppImage
find_appimage() {
local appimage_path
appimage_path=$(find dist-electron-packages -name "*.AppImage" -type f -print -quit)
if [ -n "$appimage_path" ]; then
echo "$appimage_path"
else
log_warn "AppImage not found in expected location"
echo "dist-electron-packages/*.AppImage"
fi
}
# Print build header
echo -e "\n${BLUE}=== TimeSafari Electron Build Process ===${NC}\n"
log_info "Starting build process at $(date)"
# Check required commands
log_info "Checking required dependencies..."
check_command node
check_command npm
# Create application data directory
log_info "Setting up application directories..."
mkdir -p ~/.local/share/TimeSafari/timesafari
# Clean up previous builds
log_info "Cleaning previous builds..."
rm -rf dist* || log_warn "No previous builds to clean"
# Set environment variables for the build
log_info "Configuring build environment..."
export VITE_PLATFORM=electron
export VITE_PWA_ENABLED=false
export VITE_DISABLE_PWA=true
# Ensure TypeScript is installed
log_info "Verifying TypeScript installation..."
if [ ! -f "./node_modules/.bin/tsc" ]; then
log_info "Installing TypeScript..."
if ! npm install --save-dev typescript@~5.2.2; then
log_error "TypeScript installation failed!"
exit 2
fi
# Verify installation
if [ ! -f "./node_modules/.bin/tsc" ]; then
log_error "TypeScript installation verification failed!"
exit 2
fi
log_success "TypeScript installed successfully"
else
log_info "TypeScript already installed"
fi
# Get git hash for versioning
GIT_HASH=$(git log -1 --pretty=format:%h)
log_info "Using git hash: ${GIT_HASH}"
# Build web assets
log_info "Building web assets with Vite..."
if ! measure_time env VITE_GIT_HASH="$GIT_HASH" npx vite build --config vite.config.app.electron.mts --mode electron; then
log_error "Web asset build failed!"
exit 4
fi
# TypeScript compilation
log_info "Compiling TypeScript..."
if ! measure_time ./node_modules/.bin/tsc -p tsconfig.electron.json; then
log_error "TypeScript compilation failed!"
exit 3
fi
# Build electron main process
log_info "Building electron main process..."
if ! measure_time env VITE_GIT_HASH="$GIT_HASH" npx vite build --config vite.config.electron.mts --mode electron; then
log_error "Electron main process build failed!"
exit 4
fi
# Organize files
log_info "Organizing build artifacts..."
mkdir -p dist-electron/www
cp -r dist/* dist-electron/www/ || log_error "Failed to copy web assets"
mkdir -p dist-electron/resources
cp src/electron/preload.js dist-electron/resources/preload.js || log_error "Failed to copy preload script"
# Build the AppImage
log_info "Building AppImage package..."
if ! measure_time npx electron-builder --linux AppImage; then
log_error "AppImage build failed!"
exit 5
fi
# Print build summary
echo -e "\n${GREEN}=== Build Summary ===${NC}"
log_success "Build completed successfully!"
log_info "Build artifacts location: $(pwd)/dist-electron"
log_info "AppImage location: $(find_appimage)"
# Check for build warnings
if grep -q "default Electron icon is used" dist-electron-packages/builder-effective-config.yaml; then
log_warn "Using default Electron icon - consider adding a custom icon"
fi
if grep -q "chunks are larger than 1000 kB" dist-electron-packages/builder-effective-config.yaml; then
log_warn "Large chunks detected - consider implementing code splitting"
fi
echo -e "\n${GREEN}=== End of Build Process ===${NC}\n"
# Exit with success
exit 0

5
ios/App/App/AppDelegate.swift

@ -1,5 +1,6 @@
import UIKit
import Capacitor
import CapacitorCommunitySqlite
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
@ -7,6 +8,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Initialize SQLite
let sqlite = SQLite()
sqlite.initialize()
// Override point for customization after application launch.
return true
}

1
ios/App/Podfile

@ -11,6 +11,7 @@ install! 'cocoapods', :disable_input_output_paths => true
def capacitor_pods
pod 'Capacitor', :path => '../../node_modules/@capacitor/ios'
pod 'CapacitorCordova', :path => '../../node_modules/@capacitor/ios'
pod 'CapacitorCommunitySqlite', :path => '../../node_modules/@capacitor-community/sqlite'
pod 'CapacitorMlkitBarcodeScanning', :path => '../../node_modules/@capacitor-mlkit/barcode-scanning'
pod 'CapacitorApp', :path => '../../node_modules/@capacitor/app'
pod 'CapacitorCamera', :path => '../../node_modules/@capacitor/camera'

29
main.js

@ -1,29 +0,0 @@
const { app, BrowserWindow } = require('electron');
const path = require('path');
function createWindow() {
const win = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
win.loadFile(path.join(__dirname, 'dist-electron/www/index.html'));
}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});

5039
package-lock.json

File diff suppressed because it is too large

57
package.json

@ -11,7 +11,7 @@
"build": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --config vite.config.mts",
"lint": "eslint --ext .js,.ts,.vue --ignore-path .gitignore src",
"lint-fix": "eslint --ext .js,.ts,.vue --ignore-path .gitignore --fix src",
"prebuild": "eslint --ext .js,.ts,.vue --ignore-path .gitignore src && node sw_combine.js",
"prebuild": "eslint --ext .js,.ts,.vue --ignore-path .gitignore src && node sw_combine.cjs && node scripts/copy-wasm.cjs",
"test:all": "npm run test:prerequisites && npm run build && npm run test:web && npm run test:mobile",
"test:prerequisites": "node scripts/check-prerequisites.js",
"test:web": "npx playwright test -c playwright.config-local.ts --trace on",
@ -22,14 +22,15 @@
"check:ios-device": "xcrun xctrace list devices 2>&1 | grep -w 'Booted' || (echo 'No iOS simulator running' && exit 1)",
"clean:electron": "rimraf dist-electron",
"build:pywebview": "vite build --config vite.config.pywebview.mts",
"build:electron": "npm run clean:electron && tsc -p tsconfig.electron.json && vite build --config vite.config.electron.mts && node scripts/build-electron.js",
"build:capacitor": "vite build --mode capacitor --config vite.config.capacitor.mts",
"build:web": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --config vite.config.web.mts",
"build:web:electron": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --config vite.config.web.mts && VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --config vite.config.electron.mts --mode electron",
"build:electron": "npm run clean:electron && npm run build:web:electron && tsc -p tsconfig.electron.json && vite build --config vite.config.electron.mts && node scripts/build-electron.cjs",
"build:capacitor": "vite build --mode capacitor --config vite.config.capacitor.mts",
"electron:dev": "npm run build && electron .",
"electron:start": "electron .",
"clean:android": "adb uninstall app.timesafari.app || true",
"build:android": "npm run clean:android && rm -rf dist && npm run build:web && npm run build:capacitor && cd android && ./gradlew clean && ./gradlew assembleDebug && cd .. && npx cap sync android && npx capacitor-assets generate --android && npx cap open android",
"electron:build-linux": "npm run build:electron && electron-builder --linux AppImage",
"electron:build-linux": "electron-builder --linux AppImage",
"electron:build-linux-deb": "npm run build:electron && electron-builder --linux deb",
"electron:build-linux-prod": "NODE_ENV=production npm run build:electron && electron-builder --linux AppImage",
"build:electron-prod": "NODE_ENV=production npm run build:electron",
@ -46,6 +47,7 @@
"electron:build-mac-universal": "npm run build:electron-prod && electron-builder --mac --universal"
},
"dependencies": {
"@capacitor-community/sqlite": "^6.0.2",
"@capacitor-mlkit/barcode-scanning": "^6.0.0",
"@capacitor/android": "^6.2.0",
"@capacitor/app": "^6.0.0",
@ -56,18 +58,19 @@
"@capacitor/ios": "^6.2.0",
"@capacitor/share": "^6.0.3",
"@capawesome/capacitor-file-picker": "^6.2.0",
"@dicebear/collection": "^5.4.1",
"@dicebear/core": "^5.4.1",
"@dicebear/collection": "^5.4.3",
"@dicebear/core": "^5.4.3",
"@ethersproject/hdnode": "^5.7.0",
"@ethersproject/wallet": "^5.8.0",
"@fortawesome/fontawesome-svg-core": "^6.5.1",
"@fortawesome/free-solid-svg-icons": "^6.5.1",
"@fortawesome/vue-fontawesome": "^3.0.6",
"@jlongster/sql.js": "^1.6.7",
"@peculiar/asn1-ecc": "^2.3.8",
"@peculiar/asn1-schema": "^2.3.8",
"@pvermeer/dexie-encrypted-addon": "^3.0.0",
"@simplewebauthn/browser": "^10.0.0",
"@simplewebauthn/server": "^10.0.0",
"@simplewebauthn/server": "^10.0.1",
"@tweenjs/tween.js": "^21.1.1",
"@types/qrcode": "^1.5.5",
"@veramo/core": "^5.6.0",
@ -81,8 +84,10 @@
"@vue-leaflet/vue-leaflet": "^0.10.1",
"@vueuse/core": "^12.3.0",
"@zxing/text-encoding": "^0.9.0",
"absurd-sql": "^0.0.54",
"asn1-ber": "^1.2.2",
"axios": "^1.6.8",
"better-sqlite3-multiple-ciphers": "^11.10.0",
"cbor-x": "^1.5.9",
"class-transformer": "^0.5.1",
"dexie": "^3.2.7",
@ -90,22 +95,23 @@
"did-jwt": "^7.4.7",
"did-resolver": "^4.1.0",
"dotenv": "^16.0.3",
"ethereum-cryptography": "^2.1.3",
"electron-json-storage": "^4.6.0",
"ethereum-cryptography": "^2.2.1",
"ethereumjs-util": "^7.1.5",
"jdenticon": "^3.2.0",
"jdenticon": "^3.3.0",
"js-generate-password": "^0.1.9",
"js-yaml": "^4.1.0",
"jsqr": "^1.4.0",
"leaflet": "^1.9.4",
"localstorage-slim": "^2.7.0",
"lru-cache": "^10.2.0",
"lru-cache": "^10.4.3",
"luxon": "^3.4.4",
"merkletreejs": "^0.3.11",
"nostr-tools": "^2.10.4",
"nostr-tools": "^2.13.1",
"notiwind": "^2.0.2",
"papaparse": "^5.4.1",
"pina": "^0.20.2204228",
"pinia-plugin-persistedstate": "^3.2.1",
"pinia-plugin-persistedstate": "^3.2.3",
"qr-code-generator-vue3": "^1.4.21",
"qrcode": "^1.5.4",
"ramda": "^0.29.1",
@ -121,12 +127,13 @@
"vue-axios": "^3.5.2",
"vue-facing-decorator": "^3.0.4",
"vue-picture-cropper": "^0.7.0",
"vue-qrcode-reader": "^5.5.3",
"vue-qrcode-reader": "^5.7.2",
"vue-router": "^4.5.0",
"web-did-resolver": "^2.0.27",
"web-did-resolver": "^2.0.30",
"zod": "^3.24.2"
},
"devDependencies": {
"@capacitor-community/electron": "^5.0.1",
"@capacitor/assets": "^3.0.5",
"@playwright/test": "^1.45.2",
"@types/dom-webcodecs": "^0.1.7",
@ -141,10 +148,12 @@
"@types/ua-parser-js": "^0.7.39",
"@typescript-eslint/eslint-plugin": "^6.21.0",
"@typescript-eslint/parser": "^6.21.0",
"@vitejs/plugin-vue": "^5.2.1",
"@vitejs/plugin-vue": "^5.2.4",
"@vue/eslint-config-typescript": "^11.0.3",
"autoprefixer": "^10.4.19",
"browserify-fs": "^1.0.0",
"concurrently": "^8.2.2",
"crypto-browserify": "^3.12.1",
"electron": "^33.2.1",
"electron-builder": "^25.1.8",
"eslint": "^8.57.0",
@ -155,15 +164,17 @@
"markdownlint": "^0.37.4",
"markdownlint-cli": "^0.44.0",
"npm-check-updates": "^17.1.13",
"path-browserify": "^1.0.1",
"postcss": "^8.4.38",
"prettier": "^3.2.5",
"rimraf": "^6.0.1",
"source-map-support": "^0.5.21",
"tailwindcss": "^3.4.1",
"typescript": "~5.2.2",
"vite": "^5.2.0",
"vite-plugin-pwa": "^0.19.8"
"vite-plugin-pwa": "^1.0.0"
},
"main": "./dist-electron/main.js",
"main": "./dist-electron/main.mjs",
"build": {
"appId": "app.timesafari",
"productName": "TimeSafari",
@ -172,12 +183,17 @@
},
"files": [
"dist-electron/**/*",
"dist/**/*"
"dist/**/*",
"capacitor.config.json"
],
"extraResources": [
{
"from": "dist",
"from": "dist-electron/www",
"to": "www"
},
{
"from": "dist-electron/resources/preload.js",
"to": "preload.js"
}
],
"linux": {
@ -215,5 +231,6 @@
}
]
}
}
},
"type": "module"
}

0
postcss.config.js → postcss.config.cjs

1
requirements.txt

@ -1,5 +1,6 @@
eth_keys
pywebview
pyinstaller>=6.12.0
setuptools>=69.0.0 # Required for distutils for electron-builder on macOS
# For development
watchdog>=3.0.0 # For file watching support

85
scripts/build-electron.cjs

@ -0,0 +1,85 @@
const fs = require("fs");
const fse = require("fs-extra");
const path = require("path");
const { execSync } = require('child_process');
console.log("Starting Electron build finalization...");
// Define paths
const distPath = path.join(__dirname, "..", "dist");
const electronDistPath = path.join(__dirname, "..", "dist-electron");
const wwwPath = path.join(electronDistPath, "www");
const builtIndexPath = path.join(distPath, "index.html");
const finalIndexPath = path.join(wwwPath, "index.html");
// Ensure target directory exists
if (!fs.existsSync(wwwPath)) {
fs.mkdirSync(wwwPath, { recursive: true });
}
// Copy assets directory
const assetsSrc = path.join(distPath, "assets");
const assetsDest = path.join(wwwPath, "assets");
if (fs.existsSync(assetsSrc)) {
fse.copySync(assetsSrc, assetsDest, { overwrite: true });
}
// Copy favicon.ico
const faviconSrc = path.join(distPath, "favicon.ico");
if (fs.existsSync(faviconSrc)) {
fs.copyFileSync(faviconSrc, path.join(wwwPath, "favicon.ico"));
}
// Copy manifest.webmanifest
const manifestSrc = path.join(distPath, "manifest.webmanifest");
if (fs.existsSync(manifestSrc)) {
fs.copyFileSync(manifestSrc, path.join(wwwPath, "manifest.webmanifest"));
}
// Load and modify index.html from Vite output
let indexContent = fs.readFileSync(builtIndexPath, "utf-8");
// Inject the window.process shim after the first <script> block
indexContent = indexContent.replace(
/<script[^>]*type="module"[^>]*>/,
match => `${match}\n window.process = { env: { VITE_PLATFORM: 'electron' } };`
);
// Write the modified index.html to dist-electron/www
fs.writeFileSync(finalIndexPath, indexContent);
// Copy preload script to resources
const preloadSrc = path.join(electronDistPath, "preload.js");
const preloadDest = path.join(electronDistPath, "resources", "preload.js");
// Ensure resources directory exists
const resourcesDir = path.join(electronDistPath, "resources");
if (!fs.existsSync(resourcesDir)) {
fs.mkdirSync(resourcesDir, { recursive: true });
}
if (fs.existsSync(preloadSrc)) {
fs.copyFileSync(preloadSrc, preloadDest);
console.log("Preload script copied to resources directory");
} else {
console.error("Preload script not found at:", preloadSrc);
}
// Copy capacitor.config.json to dist-electron
try {
console.log("Copying capacitor.config.json to dist-electron...");
const configPath = path.join(process.cwd(), 'capacitor.config.json');
const targetPath = path.join(process.cwd(), 'dist-electron', 'capacitor.config.json');
if (!fs.existsSync(configPath)) {
throw new Error('capacitor.config.json not found in project root');
}
fs.copyFileSync(configPath, targetPath);
console.log("Successfully copied capacitor.config.json");
} catch (error) {
console.error("Failed to copy capacitor.config.json:", error);
throw error;
}
console.log("Electron index.html copied and patched for Electron context.");

243
scripts/build-electron.js

@ -1,243 +0,0 @@
const fs = require('fs');
const path = require('path');
console.log('Starting electron build process...');
// Copy web files
const webDistPath = path.join(__dirname, '..', 'dist');
const electronDistPath = path.join(__dirname, '..', 'dist-electron');
const wwwPath = path.join(electronDistPath, 'www');
// Create www directory if it doesn't exist
if (!fs.existsSync(wwwPath)) {
fs.mkdirSync(wwwPath, { recursive: true });
}
// Copy web files to www directory
fs.cpSync(webDistPath, wwwPath, { recursive: true });
// Fix asset paths in index.html
const indexPath = path.join(wwwPath, 'index.html');
let indexContent = fs.readFileSync(indexPath, 'utf8');
// Fix asset paths
indexContent = indexContent
.replace(/\/assets\//g, './assets/')
.replace(/href="\//g, 'href="./')
.replace(/src="\//g, 'src="./');
fs.writeFileSync(indexPath, indexContent);
// Check for remaining /assets/ paths
console.log('After path fixing, checking for remaining /assets/ paths:', indexContent.includes('/assets/'));
console.log('Sample of fixed content:', indexContent.substring(0, 500));
console.log('Copied and fixed web files in:', wwwPath);
// Copy main process files
console.log('Copying main process files...');
// Create the main process file with inlined logger
const mainContent = `const { app, BrowserWindow } = require("electron");
const path = require("path");
const fs = require("fs");
// Inline logger implementation
const logger = {
log: (...args) => console.log(...args),
error: (...args) => console.error(...args),
info: (...args) => console.info(...args),
warn: (...args) => console.warn(...args),
debug: (...args) => console.debug(...args),
};
// Check if running in dev mode
const isDev = process.argv.includes("--inspect");
function createWindow() {
// Add before createWindow function
const preloadPath = path.join(__dirname, "preload.js");
logger.log("Checking preload path:", preloadPath);
logger.log("Preload exists:", fs.existsSync(preloadPath));
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
webSecurity: true,
allowRunningInsecureContent: false,
preload: path.join(__dirname, "preload.js"),
},
});
// Always open DevTools for now
mainWindow.webContents.openDevTools();
// Intercept requests to fix asset paths
mainWindow.webContents.session.webRequest.onBeforeRequest(
{
urls: [
"file://*/*/assets/*",
"file://*/assets/*",
"file:///assets/*", // Catch absolute paths
"<all_urls>", // Catch all URLs as a fallback
],
},
(details, callback) => {
let url = details.url;
// Handle paths that don't start with file://
if (!url.startsWith("file://") && url.includes("/assets/")) {
url = \`file://\${path.join(__dirname, "www", url)}\`;
}
// Handle absolute paths starting with /assets/
if (url.includes("/assets/") && !url.includes("/www/assets/")) {
const baseDir = url.includes("dist-electron")
? url.substring(
0,
url.indexOf("/dist-electron") + "/dist-electron".length,
)
: \`file://\${__dirname}\`;
const assetPath = url.split("/assets/")[1];
const newUrl = \`\${baseDir}/www/assets/\${assetPath}\`;
callback({ redirectURL: newUrl });
return;
}
callback({}); // No redirect for other URLs
},
);
if (isDev) {
// Debug info
logger.log("Debug Info:");
logger.log("Running in dev mode:", isDev);
logger.log("App is packaged:", app.isPackaged);
logger.log("Process resource path:", process.resourcesPath);
logger.log("App path:", app.getAppPath());
logger.log("__dirname:", __dirname);
logger.log("process.cwd():", process.cwd());
}
const indexPath = path.join(__dirname, "www", "index.html");
if (isDev) {
logger.log("Loading index from:", indexPath);
logger.log("www path:", path.join(__dirname, "www"));
logger.log("www assets path:", path.join(__dirname, "www", "assets"));
}
if (!fs.existsSync(indexPath)) {
logger.error(\`Index file not found at: \${indexPath}\`);
throw new Error("Index file not found");
}
// Add CSP headers to allow API connections, Google Fonts, and zxing-wasm
mainWindow.webContents.session.webRequest.onHeadersReceived(
(details, callback) => {
callback({
responseHeaders: {
...details.responseHeaders,
"Content-Security-Policy": [
"default-src 'self';" +
"connect-src 'self' https://api.endorser.ch https://*.timesafari.app https://*.jsdelivr.net;" +
"img-src 'self' data: https: blob:;" +
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://*.jsdelivr.net;" +
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;" +
"font-src 'self' data: https://fonts.gstatic.com;" +
"style-src-elem 'self' 'unsafe-inline' https://fonts.googleapis.com;" +
"worker-src 'self' blob:;",
],
},
});
},
);
// Load the index.html
mainWindow
.loadFile(indexPath)
.then(() => {
logger.log("Successfully loaded index.html");
if (isDev) {
mainWindow.webContents.openDevTools();
logger.log("DevTools opened - running in dev mode");
}
})
.catch((err) => {
logger.error("Failed to load index.html:", err);
logger.error("Attempted path:", indexPath);
});
// Listen for console messages from the renderer
mainWindow.webContents.on("console-message", (_event, _level, message) => {
logger.log("Renderer Console:", message);
});
// Add right after creating the BrowserWindow
mainWindow.webContents.on(
"did-fail-load",
(_event, errorCode, errorDescription) => {
logger.error("Page failed to load:", errorCode, errorDescription);
},
);
mainWindow.webContents.on("preload-error", (_event, preloadPath, error) => {
logger.error("Preload script error:", preloadPath, error);
});
mainWindow.webContents.on(
"console-message",
(_event, _level, message, line, sourceId) => {
logger.log("Renderer Console:", line, sourceId, message);
},
);
// Enable remote debugging when in dev mode
if (isDev) {
mainWindow.webContents.openDevTools();
}
}
// Handle app ready
app.whenReady().then(createWindow);
// Handle all windows closed
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// Handle any errors
process.on("uncaughtException", (error) => {
logger.error("Uncaught Exception:", error);
});
`;
// Write the main process file
const mainDest = path.join(electronDistPath, 'main.js');
fs.writeFileSync(mainDest, mainContent);
// Copy preload script if it exists
const preloadSrc = path.join(__dirname, '..', 'src', 'electron', 'preload.js');
const preloadDest = path.join(electronDistPath, 'preload.js');
if (fs.existsSync(preloadSrc)) {
console.log(`Copying ${preloadSrc} to ${preloadDest}`);
fs.copyFileSync(preloadSrc, preloadDest);
}
// Verify build structure
console.log('\nVerifying build structure:');
console.log('Files in dist-electron:', fs.readdirSync(electronDistPath));
console.log('Build completed successfully!');

15
scripts/copy-wasm.cjs

@ -0,0 +1,15 @@
const fs = require('fs');
const path = require('path');
// Create public/wasm directory if it doesn't exist
const wasmDir = path.join(__dirname, '../public/wasm');
if (!fs.existsSync(wasmDir)) {
fs.mkdirSync(wasmDir, { recursive: true });
}
// Copy the WASM file from node_modules to public/wasm
const sourceFile = path.join(__dirname, '../node_modules/@jlongster/sql.js/dist/sql-wasm.wasm');
const targetFile = path.join(wasmDir, 'sql-wasm.wasm');
fs.copyFileSync(sourceFile, targetFile);
console.log('WASM file copied successfully!');

20
src/App.vue

@ -330,8 +330,11 @@
<script lang="ts">
import { Vue, Component } from "vue-facing-decorator";
import { logConsoleAndDb, retrieveSettingsForActiveAccount } from "./db/index";
import { NotificationIface } from "./constants/app";
import { NotificationIface, USE_DEXIE_DB } from "./constants/app";
import * as databaseUtil from "./db/databaseUtil";
import { retrieveSettingsForActiveAccount } from "./db/index";
import { logConsoleAndDb } from "./db/databaseUtil";
import { logger } from "./utils/logger";
interface Settings {
@ -396,7 +399,11 @@ export default class App extends Vue {
try {
logger.log("Retrieving settings for the active account...");
const settings: Settings = await retrieveSettingsForActiveAccount();
let settings: Settings =
await databaseUtil.retrieveSettingsForActiveAccount();
if (USE_DEXIE_DB) {
settings = await retrieveSettingsForActiveAccount();
}
logger.log("Retrieved settings:", settings);
const notifyingNewActivity = !!settings?.notifyingNewActivityTime;
@ -452,9 +459,10 @@ export default class App extends Vue {
return true;
}
const serverSubscription = {
...subscription,
};
const serverSubscription =
typeof subscription === "object" && subscription !== null
? { ...subscription }
: {};
if (!allGoingOff) {
serverSubscription["notifyType"] = notification.title;
logger.log(

11
src/components/DataExportSection.vue

@ -62,7 +62,7 @@ backup and database export, with platform-specific download instructions. * *
<script lang="ts">
import { Component, Prop, Vue } from "vue-facing-decorator";
import { NotificationIface } from "../constants/app";
import { AppString, NotificationIface, USE_DEXIE_DB } from "../constants/app";
import { db } from "../db/index";
import { logger } from "../utils/logger";
import { PlatformServiceFactory } from "../services/PlatformServiceFactory";
@ -131,12 +131,15 @@ export default class DataExportSection extends Vue {
*/
public async exportDatabase() {
try {
if (!USE_DEXIE_DB) {
throw new Error("Not implemented");
}
const blob = await db.export({
prettyJson: true,
transform: (table, value, key) => {
if (table === "contacts") {
// Dexie inserts a number 0 when some are undefined, so we need to totally remove them.
Object.keys(value).forEach(prop => {
Object.keys(value).forEach((prop) => {
if (value[prop] === undefined) {
delete value[prop];
}
@ -145,7 +148,7 @@ export default class DataExportSection extends Vue {
return { value, key };
},
});
const fileName = `${db.name}-backup.json`;
const fileName = `${AppString.APP_NAME_NO_SPACES}-backup.json`;
if (this.platformCapabilities.hasFileDownload) {
// Web platform: Use download link
@ -159,6 +162,8 @@ export default class DataExportSection extends Vue {
// Native platform: Write to app directory
const content = await blob.text();
await this.platformService.writeAndShareFile(fileName, content);
} else {
throw new Error("This platform does not support file downloads.");
}
this.$notify(

33
src/components/FeedFilters.vue

@ -99,8 +99,12 @@ import {
LTileLayer,
} from "@vue-leaflet/vue-leaflet";
import { Router } from "vue-router";
import { USE_DEXIE_DB } from "@/constants/app";
import * as databaseUtil from "../db/databaseUtil";
import { MASTER_SETTINGS_KEY } from "../db/tables/settings";
import { db, retrieveSettingsForActiveAccount } from "../db/index";
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
@Component({
components: {
@ -122,7 +126,10 @@ export default class FeedFilters extends Vue {
async open(onCloseIfChanged: () => void) {
this.onCloseIfChanged = onCloseIfChanged;
const settings = await retrieveSettingsForActiveAccount();
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
if (USE_DEXIE_DB) {
settings = await retrieveSettingsForActiveAccount();
}
this.hasVisibleDid = !!settings.filterFeedByVisible;
this.isNearby = !!settings.filterFeedByNearby;
if (settings.searchBoxes && settings.searchBoxes.length > 0) {
@ -144,20 +151,36 @@ export default class FeedFilters extends Vue {
async toggleNearby() {
this.settingChanged = true;
this.isNearby = !this.isNearby;
const platformService = PlatformServiceFactory.getInstance();
await platformService.dbExec(
`UPDATE settings SET filterFeedByNearby = ? WHERE id = ?`,
[this.isNearby, MASTER_SETTINGS_KEY],
);
if (USE_DEXIE_DB) {
await db.settings.update(MASTER_SETTINGS_KEY, {
filterFeedByNearby: this.isNearby,
});
}
}
async clearAll() {
if (this.hasVisibleDid || this.isNearby) {
this.settingChanged = true;
}
const platformService = PlatformServiceFactory.getInstance();
await platformService.dbExec(
`UPDATE settings SET filterFeedByNearby = ? AND filterFeedByVisible = ? WHERE id = ?`,
[false, false, MASTER_SETTINGS_KEY],
);
if (USE_DEXIE_DB) {
await db.settings.update(MASTER_SETTINGS_KEY, {
filterFeedByNearby: false,
filterFeedByVisible: false,
});
}
this.hasVisibleDid = false;
this.isNearby = false;
@ -168,10 +191,18 @@ export default class FeedFilters extends Vue {
this.settingChanged = true;
}
const platformService = PlatformServiceFactory.getInstance();
await platformService.dbExec(
`UPDATE settings SET filterFeedByNearby = ? AND filterFeedByVisible = ? WHERE id = ?`,
[true, true, MASTER_SETTINGS_KEY],
);
if (USE_DEXIE_DB) {
await db.settings.update(MASTER_SETTINGS_KEY, {
filterFeedByNearby: true,
filterFeedByVisible: true,
});
}
this.hasVisibleDid = true;
this.isNearby = true;

32
src/components/GiftedDialog.vue

@ -89,7 +89,7 @@
<script lang="ts">
import { Vue, Component, Prop } from "vue-facing-decorator";
import { NotificationIface } from "../constants/app";
import { NotificationIface, USE_DEXIE_DB } from "../constants/app";
import {
createAndSubmitGive,
didInfo,
@ -98,8 +98,10 @@ import {
import * as libsUtil from "../libs/util";
import { db, retrieveSettingsForActiveAccount } from "../db/index";
import { Contact } from "../db/tables/contacts";
import * as databaseUtil from "../db/databaseUtil";
import { retrieveAccountDids } from "../libs/util";
import { logger } from "../utils/logger";
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
@Component
export default class GiftedDialog extends Vue {
@ -144,11 +146,23 @@ export default class GiftedDialog extends Vue {
this.offerId = offerId || "";
try {
const settings = await retrieveSettingsForActiveAccount();
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
if (USE_DEXIE_DB) {
settings = await retrieveSettingsForActiveAccount();
}
this.apiServer = settings.apiServer || "";
this.activeDid = settings.activeDid || "";
const platformService = PlatformServiceFactory.getInstance();
const result = await platformService.dbQuery(`SELECT * FROM contacts`);
if (result) {
this.allContacts = databaseUtil.mapQueryResultToValues(
result,
) as unknown as Contact[];
}
if (USE_DEXIE_DB) {
this.allContacts = await db.contacts.toArray();
}
this.allMyDids = await retrieveAccountDids();
@ -306,10 +320,7 @@ export default class GiftedDialog extends Vue {
this.fromProjectId,
);
if (
result.type === "error" ||
this.isGiveCreationError(result.response)
) {
if (!result.success) {
const errorMessage = this.getGiveCreationErrorMessage(result);
logger.error("Error with give creation result:", result);
this.$notify(
@ -356,15 +367,6 @@ export default class GiftedDialog extends Vue {
// Helper functions for readability
/**
* @param result response "data" from the server
* @returns true if the result indicates an error
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
isGiveCreationError(result: any) {
return result.status !== 201 || result.data?.error;
}
/**
* @param result direct response eg. ErrorResult or SuccessResult (potentially with embedded "data")
* @returns best guess at an error message

26
src/components/GiftedPrompts.vue

@ -74,10 +74,12 @@
import { Vue, Component } from "vue-facing-decorator";
import { Router } from "vue-router";
import { AppString, NotificationIface } from "../constants/app";
import { AppString, NotificationIface, USE_DEXIE_DB } from "../constants/app";
import { db } from "../db/index";
import { Contact } from "../db/tables/contacts";
import * as databaseUtil from "../db/databaseUtil";
import { GiverReceiverInputInfo } from "../libs/util";
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
@Component
export default class GivenPrompts extends Vue {
@ -127,8 +129,16 @@ export default class GivenPrompts extends Vue {
this.visible = true;
this.callbackOnFullGiftInfo = callbackOnFullGiftInfo;
await db.open();
const platformService = PlatformServiceFactory.getInstance();
const result = await platformService.dbQuery(
"SELECT COUNT(*) FROM contacts",
);
if (result) {
this.numContacts = result.values[0][0] as number;
}
if (USE_DEXIE_DB) {
this.numContacts = await db.contacts.count();
}
this.shownContactDbIndices = new Array<boolean>(this.numContacts); // all undefined to start
}
@ -229,10 +239,22 @@ export default class GivenPrompts extends Vue {
this.nextIdeaPastContacts();
} else {
// get the contact at that offset
const platformService = PlatformServiceFactory.getInstance();
const result = await platformService.dbQuery(
"SELECT * FROM contacts LIMIT 1 OFFSET ?",
[someContactDbIndex],
);
if (result) {
this.currentContact = databaseUtil.mapQueryResultToValues(result)[
someContactDbIndex
] as unknown as Contact;
}
if (USE_DEXIE_DB) {
await db.open();
this.currentContact = await db.contacts
.offset(someContactDbIndex)
.first();
}
this.shownContactDbIndices[someContactDbIndex] = true;
}
}

13
src/components/ImageMethodDialog.vue

@ -247,11 +247,16 @@ import axios from "axios";
import { ref } from "vue";
import { Component, Vue } from "vue-facing-decorator";
import VuePictureCropper, { cropper } from "vue-picture-cropper";
import { DEFAULT_IMAGE_API_SERVER, NotificationIface } from "../constants/app";
import {
DEFAULT_IMAGE_API_SERVER,
NotificationIface,
USE_DEXIE_DB,
} from "../constants/app";
import { retrieveSettingsForActiveAccount } from "../db/index";
import { accessToken } from "../libs/crypto";
import { logger } from "../utils/logger";
import { PlatformServiceFactory } from "../services/PlatformServiceFactory";
import * as databaseUtil from "../db/databaseUtil";
const inputImageFileNameRef = ref<Blob>();
@ -333,9 +338,11 @@ export default class ImageMethodDialog extends Vue {
* @throws {Error} When settings retrieval fails
*/
async mounted() {
logger.log("ImageMethodDialog mounted");
try {
const settings = await retrieveSettingsForActiveAccount();
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
if (USE_DEXIE_DB) {
settings = await retrieveSettingsForActiveAccount();
}
this.activeDid = settings.activeDid || "";
} catch (error: unknown) {
logger.error("Error retrieving settings from database:", error);

32
src/components/MembersList.vue

@ -172,8 +172,10 @@ import {
} from "../libs/endorserServer";
import { decryptMessage } from "../libs/crypto";
import { Contact } from "../db/tables/contacts";
import * as databaseUtil from "../db/databaseUtil";
import * as libsUtil from "../libs/util";
import { NotificationIface } from "../constants/app";
import { NotificationIface, USE_DEXIE_DB } from "../constants/app";
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
interface Member {
admitted: boolean;
@ -209,7 +211,10 @@ export default class MembersList extends Vue {
contacts: Array<Contact> = [];
async created() {
const settings = await retrieveSettingsForActiveAccount();
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
if (USE_DEXIE_DB) {
settings = await retrieveSettingsForActiveAccount();
}
this.activeDid = settings.activeDid || "";
this.apiServer = settings.apiServer || "";
this.firstName = settings.firstName || "";
@ -355,8 +360,17 @@ export default class MembersList extends Vue {
}
async loadContacts() {
const platformService = PlatformServiceFactory.getInstance();
const result = await platformService.dbQuery("SELECT * FROM contacts");
if (result) {
this.contacts = databaseUtil.mapQueryResultToValues(
result,
) as unknown as Contact[];
}
if (USE_DEXIE_DB) {
this.contacts = await db.contacts.toArray();
}
}
getContactFor(did: string): Contact | undefined {
return this.contacts.find((contact) => contact.did === did);
@ -439,7 +453,14 @@ export default class MembersList extends Vue {
if (result.success) {
decrMember.isRegistered = true;
if (oldContact) {
const platformService = PlatformServiceFactory.getInstance();
await platformService.dbExec(
"UPDATE contacts SET registered = ? WHERE did = ?",
[true, decrMember.did],
);
if (USE_DEXIE_DB) {
await db.contacts.update(decrMember.did, { registered: true });
}
oldContact.registered = true;
}
this.$notify(
@ -492,7 +513,14 @@ export default class MembersList extends Vue {
name: member.name,
};
const platformService = PlatformServiceFactory.getInstance();
await platformService.dbExec(
"INSERT INTO contacts (did, name) VALUES (?, ?)",
[member.did, member.name],
);
if (USE_DEXIE_DB) {
await db.contacts.add(newContact);
}
this.contacts.push(newContact);
this.$notify(

22
src/components/OfferDialog.vue

@ -82,12 +82,13 @@
<script lang="ts">
import { Vue, Component, Prop } from "vue-facing-decorator";
import { NotificationIface } from "../constants/app";
import { NotificationIface, USE_DEXIE_DB } from "../constants/app";
import {
createAndSubmitOffer,
serverMessageForUser,
} from "../libs/endorserServer";
import * as libsUtil from "../libs/util";
import * as databaseUtil from "../db/databaseUtil";
import { retrieveSettingsForActiveAccount } from "../db/index";
import { logger } from "../utils/logger";
@ -116,7 +117,10 @@ export default class OfferDialog extends Vue {
this.recipientDid = recipientDid;
this.recipientName = recipientName;
const settings = await retrieveSettingsForActiveAccount();
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
if (USE_DEXIE_DB) {
settings = await retrieveSettingsForActiveAccount();
}
this.apiServer = settings.apiServer || "";
this.activeDid = settings.activeDid || "";
@ -245,10 +249,7 @@ export default class OfferDialog extends Vue {
this.projectId,
);
if (
result.type === "error" ||
this.isOfferCreationError(result.response)
) {
if (!result.success) {
const errorMessage = this.getOfferCreationErrorMessage(result);
logger.error("Error with offer creation result:", result);
this.$notify(
@ -292,15 +293,6 @@ export default class OfferDialog extends Vue {
// Helper functions for readability
/**
* @param result response "data" from the server
* @returns true if the result indicates an error
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
isOfferCreationError(result: any) {
return result.status !== 201 || result.data?.error;
}
/**
* @param result direct response eg. ErrorResult or SuccessResult (potentially with embedded "data")
* @returns best guess at an error message

36
src/components/OnboardingDialog.vue

@ -201,13 +201,16 @@
import { Component, Vue } from "vue-facing-decorator";
import { Router } from "vue-router";
import { NotificationIface } from "../constants/app";
import { NotificationIface, USE_DEXIE_DB } from "../constants/app";
import {
db,
retrieveSettingsForActiveAccount,
updateAccountSettings,
} from "../db/index";
import * as databaseUtil from "../db/databaseUtil";
import { OnboardPage } from "../libs/util";
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
import { Contact } from "@/db/tables/contacts";
@Component({
computed: {
@ -222,7 +225,7 @@ export default class OnboardingDialog extends Vue {
$router!: Router;
activeDid = "";
firstContactName = null;
firstContactName = "";
givenName = "";
isRegistered = false;
numContacts = 0;
@ -231,29 +234,54 @@ export default class OnboardingDialog extends Vue {
async open(page: OnboardPage) {
this.page = page;
const settings = await retrieveSettingsForActiveAccount();
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
if (USE_DEXIE_DB) {
settings = await retrieveSettingsForActiveAccount();
}
this.activeDid = settings.activeDid || "";
this.isRegistered = !!settings.isRegistered;
const platformService = PlatformServiceFactory.getInstance();
const dbContacts = await platformService.dbQuery("SELECT * FROM contacts");
if (dbContacts) {
this.numContacts = dbContacts.values.length;
const firstContact = dbContacts.values[0];
const fullContact = databaseUtil.mapColumnsToValues(dbContacts.columns, [
firstContact,
]) as unknown as Contact;
this.firstContactName = fullContact.name || "";
}
if (USE_DEXIE_DB) {
const contacts = await db.contacts.toArray();
this.numContacts = contacts.length;
if (this.numContacts > 0) {
this.firstContactName = contacts[0].name;
this.firstContactName = contacts[0].name || "";
}
}
this.visible = true;
if (this.page === OnboardPage.Create) {
// we'll assume that they've been through all the other pages
await databaseUtil.updateAccountSettings(this.activeDid, {
finishedOnboarding: true,
});
if (USE_DEXIE_DB) {
await updateAccountSettings(this.activeDid, {
finishedOnboarding: true,
});
}
}
}
async onClickClose(done?: boolean, goHome?: boolean) {
this.visible = false;
if (done) {
await databaseUtil.updateAccountSettings(this.activeDid, {
finishedOnboarding: true,
});
if (USE_DEXIE_DB) {
await updateAccountSettings(this.activeDid, {
finishedOnboarding: true,
});
}
if (goHome) {
this.$router.push({ name: "home" });
}

14
src/components/PhotoDialog.vue

@ -119,7 +119,12 @@ PhotoDialog.vue */
import axios from "axios";
import { Component, Vue } from "vue-facing-decorator";
import VuePictureCropper, { cropper } from "vue-picture-cropper";
import { DEFAULT_IMAGE_API_SERVER, NotificationIface } from "../constants/app";
import {
DEFAULT_IMAGE_API_SERVER,
NotificationIface,
USE_DEXIE_DB,
} from "../constants/app";
import * as databaseUtil from "../db/databaseUtil";
import { retrieveSettingsForActiveAccount } from "../db/index";
import { accessToken } from "../libs/crypto";
import { logger } from "../utils/logger";
@ -173,9 +178,12 @@ export default class PhotoDialog extends Vue {
* @throws {Error} When settings retrieval fails
*/
async mounted() {
logger.log("PhotoDialog mounted");
// logger.log("PhotoDialog mounted");
try {
const settings = await retrieveSettingsForActiveAccount();
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
if (USE_DEXIE_DB) {
settings = await retrieveSettingsForActiveAccount();
}
this.activeDid = settings.activeDid || "";
this.isRegistered = !!settings.isRegistered;
logger.log("isRegistered:", this.isRegistered);

12
src/components/PushNotificationPermission.vue

@ -102,7 +102,12 @@
<script lang="ts">
import { Component, Vue } from "vue-facing-decorator";
import { DEFAULT_PUSH_SERVER, NotificationIface } from "../constants/app";
import {
DEFAULT_PUSH_SERVER,
NotificationIface,
USE_DEXIE_DB,
} from "../constants/app";
import * as databaseUtil from "../db/databaseUtil";
import {
logConsoleAndDb,
retrieveSettingsForActiveAccount,
@ -169,7 +174,10 @@ export default class PushNotificationPermission extends Vue {
this.isVisible = true;
this.pushType = pushType;
try {
const settings = await retrieveSettingsForActiveAccount();
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
if (USE_DEXIE_DB) {
settings = await retrieveSettingsForActiveAccount();
}
let pushUrl = DEFAULT_PUSH_SERVER;
if (settings?.webPushServer) {
pushUrl = settings.webPushServer;

8
src/components/TopMessage.vue

@ -15,7 +15,8 @@
<script lang="ts">
import { Component, Vue, Prop } from "vue-facing-decorator";
import { AppString, NotificationIface } from "../constants/app";
import { AppString, NotificationIface, USE_DEXIE_DB } from "../constants/app";
import * as databaseUtil from "../db/databaseUtil";
import { retrieveSettingsForActiveAccount } from "../db/index";
@Component
@ -28,7 +29,10 @@ export default class TopMessage extends Vue {
async mounted() {
try {
const settings = await retrieveSettingsForActiveAccount();
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
if (USE_DEXIE_DB) {
settings = await retrieveSettingsForActiveAccount();
}
if (
settings.warnIfTestServer &&
settings.apiServer !== AppString.PROD_ENDORSER_API_SERVER

13
src/components/UserNameDialog.vue

@ -37,8 +37,9 @@
<script lang="ts">
import { Vue, Component, Prop } from "vue-facing-decorator";
import { NotificationIface } from "../constants/app";
import { NotificationIface, USE_DEXIE_DB } from "../constants/app";
import { db, retrieveSettingsForActiveAccount } from "../db/index";
import * as databaseUtil from "../db/databaseUtil";
import { MASTER_SETTINGS_KEY } from "../db/tables/settings";
@Component
@ -61,15 +62,23 @@ export default class UserNameDialog extends Vue {
*/
async open(aCallback?: (name?: string) => void) {
this.callback = aCallback || this.callback;
const settings = await retrieveSettingsForActiveAccount();
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
if (USE_DEXIE_DB) {
settings = await retrieveSettingsForActiveAccount();
}
this.givenName = settings.firstName || "";
this.visible = true;
}
async onClickSaveChanges() {
await databaseUtil.updateDefaultSettings({
firstName: this.givenName,
});
if (USE_DEXIE_DB) {
await db.settings.update(MASTER_SETTINGS_KEY, {
firstName: this.givenName,
});
}
this.visible = false;
this.callback(this.givenName);
}

7
src/components/World/components/objects/landmarks.js

@ -3,6 +3,8 @@ import * as THREE from "three";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader";
import * as SkeletonUtils from "three/addons/utils/SkeletonUtils";
import * as TWEEN from "@tweenjs/tween.js";
import { USE_DEXIE_DB } from "../../../../constants/app";
import * as databaseUtil from "../../../../db/databaseUtil";
import { retrieveSettingsForActiveAccount } from "../../../../db";
import { getHeaders } from "../../../../libs/endorserServer";
import { logger } from "../../../../utils/logger";
@ -14,7 +16,10 @@ export async function loadLandmarks(vue, world, scene, loop) {
vue.setWorldProperty("animationDurationSeconds", ANIMATION_DURATION_SECS);
try {
const settings = await retrieveSettingsForActiveAccount();
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
if (USE_DEXIE_DB) {
settings = await retrieveSettingsForActiveAccount();
}
const activeDid = settings.activeDid || "";
const apiServer = settings.apiServer;
const headers = await getHeaders(activeDid);

5
src/constants/app.ts

@ -7,6 +7,7 @@ export enum AppString {
// This is used in titles and verbiage inside the app.
// There is also an app name without spaces, for packaging in the package.json file used in the manifest.
APP_NAME = "Time Safari",
APP_NAME_NO_SPACES = "TimeSafari",
PROD_ENDORSER_API_SERVER = "https://api.endorser.ch",
TEST_ENDORSER_API_SERVER = "https://test-api.endorser.ch",
@ -43,13 +44,15 @@ export const DEFAULT_PARTNER_API_SERVER =
AppString.TEST_PARTNER_API_SERVER;
export const DEFAULT_PUSH_SERVER =
window.location.protocol + "//" + window.location.host;
import.meta.env.VITE_DEFAULT_PUSH_SERVER || "https://timesafari.app";
export const IMAGE_TYPE_PROFILE = "profile";
export const PASSKEYS_ENABLED =
!!import.meta.env.VITE_PASSKEYS_ENABLED || false;
export const USE_DEXIE_DB = false;
/**
* The possible values for "group" and "type" are in App.vue.
* Some of this comes from the notiwind package, some is custom.

134
src/db-sql/migration.ts

@ -0,0 +1,134 @@
import migrationService from "../services/migrationService";
import type { QueryExecResult } from "../interfaces/database";
import { DEFAULT_ENDORSER_API_SERVER } from "@/constants/app";
import { arrayBufferToBase64 } from "@/libs/crypto";
// Generate a random secret for the secret table
// It's not really secure to maintain the secret next to the user's data.
// However, until we have better hooks into a real wallet or reliable secure
// storage, we'll do this for user convenience. As they sign more records
// and integrate with more people, they'll value it more and want to be more
// secure, so we'll prompt them to take steps to back it up, properly encrypt,
// etc. At the beginning, we'll prompt for a password, then we'll prompt for a
// PWA so it's not in a browser... and then we hope to be integrated with a
// real wallet or something else more secure.
// One might ask: why encrypt at all? We figure a basic encryption is better
// than none. Plus, we expect to support their own password or keystore or
// external wallet as better signing options in the future, so it's gonna be
// important to have the structure where each account access might require
// user action.
// (Once upon a time we stored the secret in localStorage, but it frequently
// got erased, even though the IndexedDB still had the identity data. This
// ended up throwing lots of errors to the user... and they'd end up in a state
// where they couldn't take action because they couldn't unlock that identity.)
const randomBytes = crypto.getRandomValues(new Uint8Array(32));
const secretBase64 = arrayBufferToBase64(randomBytes);
// Each migration can include multiple SQL statements (with semicolons)
const MIGRATIONS = [
{
name: "001_initial",
// see ../db/tables files for explanations of the fields
sql: `
CREATE TABLE IF NOT EXISTS accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
dateCreated TEXT NOT NULL,
derivationPath TEXT,
did TEXT NOT NULL,
identityEncrBase64 TEXT, -- encrypted & base64-encoded
mnemonicEncrBase64 TEXT, -- encrypted & base64-encoded
passkeyCredIdHex TEXT,
publicKeyHex TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_accounts_did ON accounts(did);
CREATE TABLE IF NOT EXISTS secret (
id INTEGER PRIMARY KEY AUTOINCREMENT,
secretBase64 TEXT NOT NULL
);
INSERT INTO secret (id, secretBase64) VALUES (1, '${secretBase64}');
CREATE TABLE IF NOT EXISTS settings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
accountDid TEXT,
activeDid TEXT,
apiServer TEXT,
filterFeedByNearby BOOLEAN,
filterFeedByVisible BOOLEAN,
finishedOnboarding BOOLEAN,
firstName TEXT,
hideRegisterPromptOnNewContact BOOLEAN,
isRegistered BOOLEAN,
lastName TEXT,
lastAckedOfferToUserJwtId TEXT,
lastAckedOfferToUserProjectsJwtId TEXT,
lastNotifiedClaimId TEXT,
lastViewedClaimId TEXT,
notifyingNewActivityTime TEXT,
notifyingReminderMessage TEXT,
notifyingReminderTime TEXT,
partnerApiServer TEXT,
passkeyExpirationMinutes INTEGER,
profileImageUrl TEXT,
searchBoxes TEXT, -- Stored as JSON string
showContactGivesInline BOOLEAN,
showGeneralAdvanced BOOLEAN,
showShortcutBvc BOOLEAN,
vapid TEXT,
warnIfProdServer BOOLEAN,
warnIfTestServer BOOLEAN,
webPushServer TEXT
);
CREATE INDEX IF NOT EXISTS idx_settings_accountDid ON settings(accountDid);
INSERT INTO settings (id, apiServer) VALUES (1, '${DEFAULT_ENDORSER_API_SERVER}');
CREATE TABLE IF NOT EXISTS contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
did TEXT NOT NULL,
name TEXT,
contactMethods TEXT, -- Stored as JSON string
nextPubKeyHashB64 TEXT,
notes TEXT,
profileImageUrl TEXT,
publicKeyBase64 TEXT,
seesMe BOOLEAN,
registered BOOLEAN
);
CREATE INDEX IF NOT EXISTS idx_contacts_did ON contacts(did);
CREATE INDEX IF NOT EXISTS idx_contacts_name ON contacts(name);
CREATE TABLE IF NOT EXISTS logs (
date TEXT NOT NULL,
message TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS temp (
id TEXT PRIMARY KEY,
blobB64 TEXT
);
`,
},
];
export async function registerMigrations(): Promise<void> {
// Register all migrations
for (const migration of MIGRATIONS) {
await migrationService.registerMigration(migration);
}
}
export async function runMigrations(
sqlExec: (sql: string, params?: unknown[]) => Promise<Array<QueryExecResult>>,
): Promise<void> {
await registerMigrations();
await migrationService.runMigrations(sqlExec);
}

267
src/db/databaseUtil.ts

@ -0,0 +1,267 @@
/**
* This file is the SQL replacement of the index.ts file in the db directory.
* That file will eventually be deleted.
*/
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
import { MASTER_SETTINGS_KEY, Settings } from "./tables/settings";
import { logger } from "@/utils/logger";
import { DEFAULT_ENDORSER_API_SERVER } from "@/constants/app";
import { QueryExecResult } from "@/interfaces/database";
export async function updateDefaultSettings(
settingsChanges: Settings,
): Promise<boolean> {
delete settingsChanges.accountDid; // just in case
// ensure there is no "id" that would override the key
delete settingsChanges.id;
try {
const platformService = PlatformServiceFactory.getInstance();
const { sql, params } = generateUpdateStatement(
settingsChanges,
"settings",
"id = ?",
[MASTER_SETTINGS_KEY],
);
const result = await platformService.dbExec(sql, params);
return result.changes === 1;
} catch (error) {
logger.error("Error updating default settings:", error);
if (error instanceof Error) {
throw error; // Re-throw if it's already an Error with a message
} else {
throw new Error(
`Failed to update settings. We recommend you try again or restart the app.`,
);
}
}
}
export async function updateAccountSettings(
accountDid: string,
settingsChanges: Settings,
): Promise<boolean> {
settingsChanges.accountDid = accountDid;
delete settingsChanges.id; // key off account, not ID
const platform = PlatformServiceFactory.getInstance();
// First try to update existing record
const { sql: updateSql, params: updateParams } = generateUpdateStatement(
settingsChanges,
"settings",
"accountDid = ?",
[accountDid],
);
const updateResult = await platform.dbExec(updateSql, updateParams);
// If no record was updated, insert a new one
if (updateResult.changes === 1) {
return true;
} else {
const columns = Object.keys(settingsChanges);
const values = Object.values(settingsChanges);
const placeholders = values.map(() => "?").join(", ");
const insertSql = `INSERT INTO settings (${columns.join(", ")}) VALUES (${placeholders})`;
const result = await platform.dbExec(insertSql, values);
return result.changes === 1;
}
}
const DEFAULT_SETTINGS: Settings = {
id: MASTER_SETTINGS_KEY,
activeDid: undefined,
apiServer: DEFAULT_ENDORSER_API_SERVER,
};
// retrieves default settings
export async function retrieveSettingsForDefaultAccount(): Promise<Settings> {
const platform = PlatformServiceFactory.getInstance();
const result = await platform.dbQuery("SELECT * FROM settings WHERE id = ?", [
MASTER_SETTINGS_KEY,
]);
if (!result) {
return DEFAULT_SETTINGS;
} else {
const settings = mapColumnsToValues(
result.columns,
result.values,
)[0] as Settings;
if (settings.searchBoxes) {
// @ts-expect-error - the searchBoxes field is a string in the DB
settings.searchBoxes = JSON.parse(settings.searchBoxes);
}
return settings;
}
}
export async function retrieveSettingsForActiveAccount(): Promise<Settings> {
const defaultSettings = await retrieveSettingsForDefaultAccount();
if (!defaultSettings.activeDid) {
return defaultSettings;
} else {
const platform = PlatformServiceFactory.getInstance();
const result = await platform.dbQuery(
"SELECT * FROM settings WHERE accountDid = ?",
[defaultSettings.activeDid],
);
const overrideSettings = result
? (mapColumnsToValues(result.columns, result.values)[0] as Settings)
: {};
const overrideSettingsFiltered = Object.fromEntries(
Object.entries(overrideSettings).filter(([_, v]) => v !== null),
);
const settings = { ...defaultSettings, ...overrideSettingsFiltered };
if (settings.searchBoxes) {
// @ts-expect-error - the searchBoxes field is a string in the DB
settings.searchBoxes = JSON.parse(settings.searchBoxes);
}
return settings;
}
}
let lastCleanupDate: string | null = null;
/**
* Logs a message to the database with proper handling of concurrent writes
* @param message - The message to log
* @author Matthew Raymer
*/
export async function logToDb(message: string): Promise<void> {
const platform = PlatformServiceFactory.getInstance();
const todayKey = new Date().toDateString();
const nowKey = new Date().toISOString();
try {
// Try to insert first, if it fails due to UNIQUE constraint, update instead
await platform.dbExec("INSERT INTO logs (date, message) VALUES (?, ?)", [
nowKey,
message,
]);
// Clean up old logs (keep only last 7 days) - do this less frequently
// Only clean up if the date is different from the last cleanup
if (!lastCleanupDate || lastCleanupDate !== todayKey) {
const sevenDaysAgo = new Date(
new Date().getTime() - 7 * 24 * 60 * 60 * 1000,
);
await platform.dbExec("DELETE FROM logs WHERE date < ?", [
sevenDaysAgo.toDateString(),
]);
lastCleanupDate = todayKey;
}
} catch (error) {
// Log to console as fallback
// eslint-disable-next-line no-console
console.error(
"Error logging to database:",
error,
" ... for original message:",
message,
);
}
}
// similar method is in the sw_scripts/additional-scripts.js file
export async function logConsoleAndDb(
message: string,
isError = false,
): Promise<void> {
if (isError) {
logger.error(`${new Date().toISOString()} ${message}`);
} else {
logger.log(`${new Date().toISOString()} ${message}`);
}
await logToDb(message);
}
/**
* Generates an SQL INSERT statement and parameters from a model object.
* @param model The model object containing fields to update
* @param tableName The name of the table to update
* @returns Object containing the SQL statement and parameters array
*/
export function generateInsertStatement(
model: Record<string, unknown>,
tableName: string,
): { sql: string; params: unknown[] } {
const columns = Object.keys(model).filter((key) => model[key] !== undefined);
const values = Object.values(model).filter((value) => value !== undefined);
const placeholders = values.map(() => "?").join(", ");
const insertSql = `INSERT INTO ${tableName} (${columns.join(", ")}) VALUES (${placeholders})`;
return {
sql: insertSql,
params: values,
};
}
/**
* Generates an SQL UPDATE statement and parameters from a model object.
* @param model The model object containing fields to update
* @param tableName The name of the table to update
* @param whereClause The WHERE clause for the update (e.g. "id = ?")
* @param whereParams Parameters for the WHERE clause
* @returns Object containing the SQL statement and parameters array
*/
export function generateUpdateStatement(
model: Record<string, unknown>,
tableName: string,
whereClause: string,
whereParams: unknown[] = [],
): { sql: string; params: unknown[] } {
// Filter out undefined/null values and create SET clause
const setClauses: string[] = [];
const params: unknown[] = [];
Object.entries(model).forEach(([key, value]) => {
if (value !== undefined) {
setClauses.push(`${key} = ?`);
params.push(value);
}
});
if (setClauses.length === 0) {
throw new Error("No valid fields to update");
}
const sql = `UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE ${whereClause}`;
return {
sql,
params: [...params, ...whereParams],
};
}
export function mapQueryResultToValues(
record: QueryExecResult | undefined,
): Array<Record<string, unknown>> {
if (!record) {
return [];
}
return mapColumnsToValues(record.columns, record.values) as Array<
Record<string, unknown>
>;
}
/**
* Maps an array of column names to an array of value arrays, creating objects where each column name
* is mapped to its corresponding value.
* @param columns Array of column names to use as object keys
* @param values Array of value arrays, where each inner array corresponds to one row of data
* @returns Array of objects where each object maps column names to their corresponding values
*/
export function mapColumnsToValues(
columns: string[],
values: unknown[][],
): Array<Record<string, unknown>> {
return values.map((row) => {
const obj: Record<string, unknown> = {};
columns.forEach((column, index) => {
obj[column] = row[index];
});
return obj;
});
}

56
src/db/index.ts

@ -1,3 +1,9 @@
/**
* This is the original IndexedDB version of the database.
* It will eventually be replaced fully by the SQL version in databaseUtil.ts.
* Turn this on or off with the USE_DEXIE_DB constant in constants/app.ts.
*/
import BaseDexie, { Table } from "dexie";
import { encrypted, Encryption } from "@pvermeer/dexie-encrypted-addon";
import * as R from "ramda";
@ -26,8 +32,8 @@ type NonsensitiveTables = {
};
// Using 'unknown' instead of 'any' for stricter typing and to avoid TypeScript warnings
export type SecretDexie<T extends unknown = SecretTable> = BaseDexie & T;
export type SensitiveDexie<T extends unknown = SensitiveTables> = BaseDexie & T;
type SecretDexie<T extends unknown = SecretTable> = BaseDexie & T;
type SensitiveDexie<T extends unknown = SensitiveTables> = BaseDexie & T;
export type NonsensitiveDexie<T extends unknown = NonsensitiveTables> =
BaseDexie & T;
@ -90,40 +96,40 @@ db.on("populate", async () => {
try {
await db.settings.add(DEFAULT_SETTINGS);
} catch (error) {
console.error("Error populating the database with default settings:", error);
logger.error("Error populating the database with default settings:", error);
}
});
// Helper function to safely open the database with retries
async function safeOpenDatabase(retries = 1, delay = 500): Promise<void> {
// console.log("Starting safeOpenDatabase with retries:", retries);
// logger.log("Starting safeOpenDatabase with retries:", retries);
for (let i = 0; i < retries; i++) {
try {
// console.log(`Attempt ${i + 1}: Checking if database is open...`);
// logger.log(`Attempt ${i + 1}: Checking if database is open...`);
if (!db.isOpen()) {
// console.log(`Attempt ${i + 1}: Database is closed, attempting to open...`);
// logger.log(`Attempt ${i + 1}: Database is closed, attempting to open...`);
// Create a promise that rejects after 5 seconds
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => reject(new Error('Database open timed out')), 500);
setTimeout(() => reject(new Error("Database open timed out")), 500);
});
// Race between the open operation and the timeout
const openPromise = db.open();
// console.log(`Attempt ${i + 1}: Waiting for db.open() promise...`);
// logger.log(`Attempt ${i + 1}: Waiting for db.open() promise...`);
await Promise.race([openPromise, timeoutPromise]);
// If we get here, the open succeeded
// console.log(`Attempt ${i + 1}: Database opened successfully`);
// logger.log(`Attempt ${i + 1}: Database opened successfully`);
return;
}
// console.log(`Attempt ${i + 1}: Database was already open`);
// logger.log(`Attempt ${i + 1}: Database was already open`);
return;
} catch (error) {
console.error(`Attempt ${i + 1}: Database open failed:`, error);
logger.error(`Attempt ${i + 1}: Database open failed:`, error);
if (i < retries - 1) {
console.log(`Attempt ${i + 1}: Waiting ${delay}ms before retry...`);
await new Promise(resolve => setTimeout(resolve, delay));
logger.log(`Attempt ${i + 1}: Waiting ${delay}ms before retry...`);
await new Promise((resolve) => setTimeout(resolve, delay));
} else {
throw error;
}
@ -139,23 +145,29 @@ export async function updateDefaultSettings(
delete settingsChanges.id;
try {
try {
// console.log("Database state before open:", db.isOpen() ? "open" : "closed");
// console.log("Database name:", db.name);
// console.log("Database version:", db.verno);
// logger.log("Database state before open:", db.isOpen() ? "open" : "closed");
// logger.log("Database name:", db.name);
// logger.log("Database version:", db.verno);
await safeOpenDatabase();
} catch (openError: unknown) {
console.error("Failed to open database:", openError);
const errorMessage = openError instanceof Error ? openError.message : String(openError);
throw new Error(`Database connection failed: ${errorMessage}. Please try again or restart the app.`);
logger.error("Failed to open database:", openError, String(openError));
throw new Error(
`The database connection failed. We recommend you try again or restart the app.`,
);
}
const result = await db.settings.update(MASTER_SETTINGS_KEY, settingsChanges);
const result = await db.settings.update(
MASTER_SETTINGS_KEY,
settingsChanges,
);
return result;
} catch (error) {
console.error("Error updating default settings:", error);
logger.error("Error updating default settings:", error);
if (error instanceof Error) {
throw error; // Re-throw if it's already an Error with a message
} else {
throw new Error(`Failed to update settings: ${error}`);
throw new Error(
`Failed to update settings. We recommend you try again or restart the app.`,
);
}
}
}

6
src/db/tables/accounts.ts

@ -45,6 +45,12 @@ export type Account = {
publicKeyHex: string;
};
// When finished with USE_DEXIE_DB, move these fields to Account and move identity and mnemonic here.
export type AccountEncrypted = Account & {
identityEncrBase64: string;
mnemonicEncrBase64: string;
};
/**
* Schema for the accounts table in the database.
* Fields starting with a $ character are encrypted.

751
src/electron/main.ts

@ -1,168 +1,550 @@
import { app, BrowserWindow } from "electron";
import path from "path";
import { app, BrowserWindow, ipcMain } from "electron";
import { Capacitor } from "@capacitor/core";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
// Get __dirname equivalent in ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Set global variables that the plugin needs
global.__dirname = __dirname;
global.__filename = __filename;
// Now import the plugin after setting up globals
import { CapacitorSQLite } from "@capacitor-community/sqlite/electron/dist/plugin.js";
// Simple logger implementation
const logger = {
// eslint-disable-next-line no-console
log: (...args: unknown[]) => console.log(...args),
log: (...args: unknown[]) => console.log("[Main]", ...args),
// eslint-disable-next-line no-console
error: (...args: unknown[]) => console.error(...args),
error: (...args: unknown[]) => console.error("[Main]", ...args),
// eslint-disable-next-line no-console
info: (...args: unknown[]) => console.info(...args),
info: (...args: unknown[]) => console.info("[Main]", ...args),
// eslint-disable-next-line no-console
warn: (...args: unknown[]) => console.warn(...args),
warn: (...args: unknown[]) => console.warn("[Main]", ...args),
// eslint-disable-next-line no-console
debug: (...args: unknown[]) => console.debug(...args),
debug: (...args: unknown[]) => console.debug("[Main]", ...args),
};
logger.info("Starting main process initialization...");
// Initialize Capacitor for Electron in main process
try {
logger.info("About to initialize Capacitor...");
logger.info("Capacitor before init:", {
hasPlatform: "platform" in Capacitor,
hasIsNativePlatform: "isNativePlatform" in Capacitor,
platformType: typeof Capacitor.platform,
isNativePlatformType: typeof Capacitor.isNativePlatform,
});
// Try direct assignment first
try {
(Capacitor as unknown as { platform: string }).platform = "electron";
(Capacitor as unknown as { isNativePlatform: boolean }).isNativePlatform =
true;
logger.info("Direct assignment successful");
} catch (e) {
logger.warn("Direct assignment failed, trying defineProperty:", e);
Object.defineProperty(Capacitor, "isNativePlatform", {
get: () => true,
configurable: true,
});
Object.defineProperty(Capacitor, "platform", {
get: () => "electron",
configurable: true,
});
}
logger.info("Capacitor after init:", {
platform: Capacitor.platform,
isNativePlatform: Capacitor.isNativePlatform,
platformType: typeof Capacitor.platform,
isNativePlatformType: typeof Capacitor.isNativePlatform,
});
} catch (error) {
logger.error("Failed to initialize Capacitor:", error);
throw error;
}
// Database path resolution utilities
const getAppDataPath = async (): Promise<string> => {
try {
// Read config file directly
const configPath = path.join(__dirname, "..", "capacitor.config.json");
const configContent = await fs.promises.readFile(configPath, "utf-8");
const config = JSON.parse(configContent);
const linuxPath = config?.plugins?.CapacitorSQLite?.electronLinuxLocation;
if (linuxPath) {
// Expand ~ to home directory
const expandedPath = linuxPath.replace(/^~/, process.env.HOME || "");
logger.info("[Electron] Using configured database path:", expandedPath);
return expandedPath;
}
// Fallback to app.getPath if config path is not available
const userDataPath = app.getPath("userData");
logger.info("[Electron] Using fallback user data path:", userDataPath);
return userDataPath;
} catch (error) {
logger.error("[Electron] Error getting app data path:", error);
// Fallback to app.getPath if anything fails
const userDataPath = app.getPath("userData");
logger.info(
"[Electron] Using fallback user data path after error:",
userDataPath,
);
return userDataPath;
}
};
const validateAndNormalizePath = async (filePath: string): Promise<string> => {
// Resolve any relative paths
const resolvedPath = path.resolve(filePath);
// Ensure it's an absolute path
if (!path.isAbsolute(resolvedPath)) {
throw new Error(`Database path must be absolute: ${resolvedPath}`);
}
// Ensure it's within the app data directory
const appDataPath = await getAppDataPath();
if (!resolvedPath.startsWith(appDataPath)) {
throw new Error(
`Database path must be within app data directory: ${resolvedPath}`,
);
}
// Normalize the path
const normalizedPath = path.normalize(resolvedPath);
logger.info("[Electron] Validated database path:", {
original: filePath,
resolved: resolvedPath,
normalized: normalizedPath,
appDataPath,
isAbsolute: path.isAbsolute(normalizedPath),
isWithinAppData: normalizedPath.startsWith(appDataPath),
});
return normalizedPath;
};
const ensureDirectoryExists = async (dirPath: string): Promise<void> => {
try {
// Normalize the path first
const normalizedPath = path.normalize(dirPath);
// Check if directory exists
if (!fs.existsSync(normalizedPath)) {
logger.info("[Electron] Creating database directory:", normalizedPath);
await fs.promises.mkdir(normalizedPath, { recursive: true });
}
// Verify directory permissions
try {
await fs.promises.access(
normalizedPath,
fs.constants.R_OK | fs.constants.W_OK,
);
logger.info(
"[Electron] Database directory permissions verified:",
normalizedPath,
);
} catch (error) {
logger.error("[Electron] Database directory permission error:", error);
throw new Error(`Database directory not accessible: ${normalizedPath}`);
}
// Test write permissions
const testFile = path.join(normalizedPath, ".write-test");
try {
await fs.promises.writeFile(testFile, "test");
await fs.promises.unlink(testFile);
logger.info(
"[Electron] Database directory write test passed:",
normalizedPath,
);
} catch (error) {
logger.error("[Electron] Database directory write test failed:", error);
throw new Error(`Database directory not writable: ${normalizedPath}`);
}
} catch (error) {
logger.error(
"[Electron] Failed to ensure database directory exists:",
error,
);
throw error;
}
};
// Initialize database paths
let dbPath: string | undefined;
let dbDir: string | undefined;
let dbPathInitialized = false;
let dbPathInitializationPromise: Promise<void> | null = null;
const initializeDatabasePaths = async (): Promise<void> => {
// Prevent multiple simultaneous initializations
if (dbPathInitializationPromise) {
return dbPathInitializationPromise;
}
if (dbPathInitialized) {
return;
}
dbPathInitializationPromise = (async () => {
try {
// Get the base directory from config
dbDir = await getAppDataPath();
logger.info("[Electron] Database directory:", dbDir);
// Ensure the directory exists and is writable
await ensureDirectoryExists(dbDir);
// Construct the database path
dbPath = await validateAndNormalizePath(
path.join(dbDir, "timesafari.db"),
);
logger.info("[Electron] Database path initialized:", dbPath);
// Verify the database file if it exists
if (fs.existsSync(dbPath)) {
try {
await fs.promises.access(
dbPath,
fs.constants.R_OK | fs.constants.W_OK,
);
logger.info(
"[Electron] Existing database file permissions verified:",
dbPath,
);
} catch (error) {
logger.error("[Electron] Database file permission error:", error);
throw new Error(`Database file not accessible: ${dbPath}`);
}
}
dbPathInitialized = true;
} catch (error) {
logger.error("[Electron] Failed to initialize database paths:", error);
throw error;
} finally {
dbPathInitializationPromise = null;
}
})();
return dbPathInitializationPromise;
};
// Initialize SQLite plugin
let sqlitePlugin: any = null;
let sqliteInitialized = false;
let sqliteInitializationPromise: Promise<void> | null = null;
async function initializeSQLite() {
// Prevent multiple simultaneous initializations
if (sqliteInitializationPromise) {
return sqliteInitializationPromise;
}
if (sqliteInitialized) {
return;
}
sqliteInitializationPromise = (async () => {
try {
logger.info("[Electron] Initializing SQLite plugin...");
sqlitePlugin = new CapacitorSQLite();
// Initialize database paths first
await initializeDatabasePaths();
if (!dbPath) {
throw new Error("Database path not initialized");
}
// Test the plugin
const echoResult = await sqlitePlugin.echo({ value: "test" });
logger.info("[Electron] SQLite plugin echo test:", echoResult);
// Initialize database connection using validated dbPath
const connectionOptions = {
database: dbPath,
version: 1,
readOnly: false,
encryption: "no-encryption",
useNative: true,
mode: "rwc", // Force read-write-create mode
};
logger.info(
"[Electron] Creating initial connection with options:",
connectionOptions,
);
// Log the actual path being used
logger.info("[Electron] Using database path:", dbPath);
logger.info("[Electron] Path exists:", fs.existsSync(dbPath));
logger.info("[Electron] Path is absolute:", path.isAbsolute(dbPath));
const db = await sqlitePlugin.createConnection(connectionOptions);
if (!db || typeof db !== "object") {
throw new Error(
`Failed to create database connection - invalid response. Path used: ${dbPath}`,
);
}
// Wait a moment for the connection to be fully established
await new Promise((resolve) => setTimeout(resolve, 100));
// Verify the connection is working
try {
const result = await db.query("PRAGMA journal_mode;");
logger.info("[Electron] Database connection verified:", result);
} catch (error) {
logger.error(
"[Electron] Database connection verification failed:",
error,
);
throw error;
}
sqliteInitialized = true;
logger.info("[Electron] SQLite plugin initialized successfully");
} catch (error) {
logger.error("[Electron] Failed to initialize SQLite plugin:", error);
throw error;
} finally {
sqliteInitializationPromise = null;
}
})();
return sqliteInitializationPromise;
}
// Initialize app when ready
app.whenReady().then(async () => {
logger.info("App is ready, starting initialization...");
// Create window first
const mainWindow = createWindow();
// Initialize database in background
initializeSQLite().catch((error) => {
logger.error(
"[Electron] Database initialization failed, but continuing:",
error,
);
// Notify renderer about database status
if (!mainWindow.isDestroyed()) {
mainWindow.webContents.send("database-status", {
status: "error",
error: error.message,
});
}
});
// Handle window close
mainWindow.on("closed", () => {
logger.info("[Electron] Main window closed");
});
// Handle window close request
mainWindow.on("close", (event) => {
logger.info("[Electron] Window close requested");
// Prevent immediate close if we're in the middle of something
if (mainWindow.webContents.isLoading()) {
event.preventDefault();
logger.info("[Electron] Deferring window close due to loading state");
mainWindow.webContents.once("did-finish-load", () => {
mainWindow.close();
});
}
});
});
// Check if running in dev mode
const isDev = process.argv.includes("--inspect");
// const isDev = process.argv.includes("--inspect");
function createWindow(): void {
// Add before createWindow function
const preloadPath = path.join(__dirname, "preload.js");
logger.log("Checking preload path:", preloadPath);
logger.log("Preload exists:", fs.existsSync(preloadPath));
function createWindow(): BrowserWindow {
// Resolve preload path based on environment
const preloadPath = app.isPackaged
? path.join(process.resourcesPath, "preload.js")
: path.join(__dirname, "preload.js");
// Create the browser window.
logger.log("[Electron] Preload path:", preloadPath);
logger.log("[Electron] Preload exists:", fs.existsSync(preloadPath));
// Log environment and paths
logger.log("[Electron] process.cwd():", process.cwd());
logger.log("[Electron] __dirname:", __dirname);
logger.log("[Electron] app.getAppPath():", app.getAppPath());
logger.log("[Electron] app.isPackaged:", app.isPackaged);
logger.log("[Electron] process.resourcesPath:", process.resourcesPath);
// List files in __dirname and __dirname/www
try {
logger.log("Files in __dirname:", fs.readdirSync(__dirname));
const wwwDir = path.join(__dirname, "www");
if (fs.existsSync(wwwDir)) {
logger.log("Files in www:", fs.readdirSync(wwwDir));
} else {
logger.log("www directory does not exist in __dirname");
}
} catch (e) {
logger.error("Error reading directories:", e);
}
// Create the browser window with proper error handling
const mainWindow = new BrowserWindow({
width: 1200,
height: 800,
show: false, // Don't show until ready
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: false,
preload: preloadPath,
webSecurity: true,
allowRunningInsecureContent: false,
preload: path.join(__dirname, "preload.js"),
},
});
// Always open DevTools for now
mainWindow.webContents.openDevTools();
// Show window when ready
mainWindow.once("ready-to-show", () => {
logger.info("[Electron] Window ready to show");
mainWindow.show();
});
// Intercept requests to fix asset paths
mainWindow.webContents.session.webRequest.onBeforeRequest(
{
urls: [
"file://*/*/assets/*",
"file://*/assets/*",
"file:///assets/*", // Catch absolute paths
"<all_urls>", // Catch all URLs as a fallback
],
},
(details, callback) => {
let url = details.url;
// Handle paths that don't start with file://
if (!url.startsWith("file://") && url.includes("/assets/")) {
url = `file://${path.join(__dirname, "www", url)}`;
}
// Handle absolute paths starting with /assets/
if (url.includes("/assets/") && !url.includes("/www/assets/")) {
const baseDir = url.includes("dist-electron")
? url.substring(
0,
url.indexOf("/dist-electron") + "/dist-electron".length,
)
: `file://${__dirname}`;
const assetPath = url.split("/assets/")[1];
const newUrl = `${baseDir}/www/assets/${assetPath}`;
callback({ redirectURL: newUrl });
return;
}
// Handle window errors
mainWindow.webContents.on("render-process-gone", (_event, details) => {
logger.error("[Electron] Render process gone:", details);
});
callback({}); // No redirect for other URLs
},
mainWindow.webContents.on(
"did-fail-load",
(_event, errorCode, errorDescription) => {
logger.error(
"[Electron] Page failed to load:",
errorCode,
errorDescription,
);
if (isDev) {
// Debug info
logger.log("Debug Info:");
logger.log("Running in dev mode:", isDev);
logger.log("App is packaged:", app.isPackaged);
logger.log("Process resource path:", process.resourcesPath);
logger.log("App path:", app.getAppPath());
logger.log("__dirname:", __dirname);
logger.log("process.cwd():", process.cwd());
}
const indexPath = path.join(__dirname, "www", "index.html");
if (isDev) {
logger.log("Loading index from:", indexPath);
logger.log("www path:", path.join(__dirname, "www"));
logger.log("www assets path:", path.join(__dirname, "www", "assets"));
}
if (!fs.existsSync(indexPath)) {
logger.error(`Index file not found at: ${indexPath}`);
throw new Error("Index file not found");
}
// Add CSP headers to allow API connections
mainWindow.webContents.session.webRequest.onHeadersReceived(
(details, callback) => {
callback({
responseHeaders: {
...details.responseHeaders,
"Content-Security-Policy": [
"default-src 'self';" +
"connect-src 'self' https://api.endorser.ch https://*.timesafari.app;" +
"img-src 'self' data: https: blob:;" +
"script-src 'self' 'unsafe-inline' 'unsafe-eval';" +
"style-src 'self' 'unsafe-inline';" +
"font-src 'self' data:;",
],
},
});
logger.error("[Electron] Failed URL:", mainWindow.webContents.getURL());
},
);
// Load the index.html
mainWindow
.loadFile(indexPath)
.then(() => {
logger.log("Successfully loaded index.html");
if (isDev) {
mainWindow.webContents.openDevTools();
logger.log("DevTools opened - running in dev mode");
let indexPath: string;
let fileUrl: string;
if (app.isPackaged) {
indexPath = path.join(process.resourcesPath, "www", "index.html");
fileUrl = `file://${indexPath}`;
logger.info(
"[Electron] App is packaged. Using process.resourcesPath for index.html",
);
} else {
indexPath = path.resolve(__dirname, "www", "index.html");
fileUrl = `file://${indexPath}`;
logger.info(
"[Electron] App is not packaged. Using __dirname for index.html",
);
}
})
.catch((err) => {
logger.error("Failed to load index.html:", err);
logger.error("Attempted path:", indexPath);
});
// Listen for console messages from the renderer
mainWindow.webContents.on("console-message", (_event, _level, message) => {
logger.log("Renderer Console:", message);
});
logger.info("[Electron] Resolved index.html path:", indexPath);
logger.info("[Electron] Using file URL:", fileUrl);
// Add right after creating the BrowserWindow
mainWindow.webContents.on(
"did-fail-load",
(_event, errorCode, errorDescription) => {
logger.error("Page failed to load:", errorCode, errorDescription);
},
// Load the index.html with retry logic
const loadIndexHtml = async (retryCount = 0): Promise<void> => {
try {
if (mainWindow.isDestroyed()) {
logger.error(
"[Electron] Window was destroyed before loading index.html",
);
return;
}
const exists = fs.existsSync(indexPath);
logger.info(`[Electron] fs.existsSync for index.html: ${exists}`);
if (!exists) {
throw new Error(`index.html not found at path: ${indexPath}`);
}
mainWindow.webContents.on("preload-error", (_event, preloadPath, error) => {
logger.error("Preload script error:", preloadPath, error);
// Try to read the file to verify it's accessible
const stats = fs.statSync(indexPath);
logger.info("[Electron] index.html stats:", {
size: stats.size,
mode: stats.mode,
uid: stats.uid,
gid: stats.gid,
});
mainWindow.webContents.on(
"console-message",
(_event, _level, message, line, sourceId) => {
logger.log("Renderer Console:", line, sourceId, message);
},
// Try loadURL first
try {
logger.info("[Electron] Attempting to load index.html via loadURL");
await mainWindow.loadURL(fileUrl);
logger.info("[Electron] Successfully loaded index.html via loadURL");
} catch (loadUrlError) {
logger.warn(
"[Electron] loadURL failed, trying loadFile:",
loadUrlError,
);
// Fallback to loadFile
await mainWindow.loadFile(indexPath);
logger.info("[Electron] Successfully loaded index.html via loadFile");
}
} catch (error: unknown) {
const errorMessage =
error instanceof Error ? error.message : "Unknown error occurred";
logger.error("[Electron] Error loading index.html:", errorMessage);
// Retry logic
if (retryCount < 3 && !mainWindow.isDestroyed()) {
logger.info(
`[Electron] Retrying index.html load (attempt ${retryCount + 1})`,
);
await new Promise((resolve) => setTimeout(resolve, 1000)); // Wait 1 second
return loadIndexHtml(retryCount + 1);
}
// If we've exhausted retries, show error in window
if (!mainWindow.isDestroyed()) {
const errorHtml = `
<html>
<body style="font-family: sans-serif; padding: 20px;">
<h1>Error Loading Application</h1>
<p>Failed to load the application after multiple attempts.</p>
<pre style="background: #f0f0f0; padding: 10px; border-radius: 4px;">${errorMessage}</pre>
</body>
</html>
`;
await mainWindow.loadURL(
`data:text/html,${encodeURIComponent(errorHtml)}`,
);
}
}
};
// Enable remote debugging when in dev mode
if (isDev) {
mainWindow.webContents.openDevTools();
// Start loading the index.html
loadIndexHtml().catch((error: unknown) => {
logger.error("[Electron] Fatal error loading index.html:", error);
});
// Only open DevTools if not in production
if (!app.isPackaged) {
mainWindow.webContents.openDevTools({ mode: "detach" });
}
return mainWindow;
}
// Handle app ready
@ -185,3 +567,126 @@ app.on("activate", () => {
process.on("uncaughtException", (error) => {
logger.error("Uncaught Exception:", error);
});
// Set up IPC handlers for SQLite operations
ipcMain.handle("check-sqlite-availability", () => {
return sqlitePlugin !== null;
});
ipcMain.handle("sqlite-echo", async (_event, value) => {
try {
return await sqlitePlugin.echo({ value });
} catch (error) {
logger.error(
"Error in sqlite-echo:",
error,
JSON.stringify(error),
(error as any)?.stack,
);
throw error;
}
});
ipcMain.handle("sqlite-create-connection", async (_event, options) => {
try {
// Ensure database is initialized
await initializeSQLite();
if (!dbPath) {
throw new Error("Database path not initialized");
}
// Override any provided database path with our resolved path
const connectionOptions = {
...options,
database: dbPath,
readOnly: false,
mode: "rwc", // Force read-write-create mode
encryption: "no-encryption",
useNative: true,
};
logger.info(
"[Electron] Creating database connection with options:",
connectionOptions,
);
const result = await sqlitePlugin.createConnection(connectionOptions);
if (!result || typeof result !== "object") {
throw new Error(
"Failed to create database connection - invalid response",
);
}
// Wait a moment for the connection to be fully established
await new Promise((resolve) => setTimeout(resolve, 100));
try {
// Verify connection is not read-only
const testResult = await result.query({
statement: "PRAGMA journal_mode;",
});
if (testResult?.values?.[0]?.journal_mode === "off") {
logger.error(
"[Electron] Connection opened in read-only mode despite options",
);
throw new Error("Database connection opened in read-only mode");
}
} catch (queryError) {
logger.error("[Electron] Error verifying connection:", queryError);
throw queryError;
}
logger.info("[Electron] Database connection created successfully");
return result;
} catch (error) {
logger.error("[Electron] Error in sqlite-create-connection:", error);
throw error;
}
});
ipcMain.handle("sqlite-execute", async (_event, options) => {
try {
return await sqlitePlugin.execute(options);
} catch (error) {
logger.error(
"Error in sqlite-execute:",
error,
JSON.stringify(error),
(error as any)?.stack,
);
throw error;
}
});
ipcMain.handle("sqlite-query", async (_event, options) => {
try {
return await sqlitePlugin.query(options);
} catch (error) {
logger.error(
"Error in sqlite-query:",
error,
JSON.stringify(error),
(error as any)?.stack,
);
throw error;
}
});
ipcMain.handle("sqlite-close-connection", async (_event, options) => {
try {
return await sqlitePlugin.closeConnection(options);
} catch (error) {
logger.error(
"Error in sqlite-close-connection:",
error,
JSON.stringify(error),
(error as any)?.stack,
);
throw error;
}
});
ipcMain.handle("sqlite-is-available", async () => {
return sqlitePlugin !== null;
});

113
src/electron/preload.js

@ -2,24 +2,33 @@ const { contextBridge, ipcRenderer } = require("electron");
const logger = {
log: (message, ...args) => {
// Always log in development, log with context in production
if (process.env.NODE_ENV !== "production") {
/* eslint-disable no-console */
console.log(message, ...args);
console.log(`[Preload] ${message}`, ...args);
/* eslint-enable no-console */
}
},
warn: (message, ...args) => {
if (process.env.NODE_ENV !== "production") {
// Always log warnings
/* eslint-disable no-console */
console.warn(message, ...args);
console.warn(`[Preload] ${message}`, ...args);
/* eslint-enable no-console */
}
},
error: (message, ...args) => {
// Always log errors
/* eslint-disable no-console */
console.error(message, ...args); // Errors should always be logged
console.error(`[Preload] ${message}`, ...args);
/* eslint-enable no-console */
},
info: (message, ...args) => {
// Always log info in development, log with context in production
if (process.env.NODE_ENV !== "production") {
/* eslint-disable no-console */
console.info(`[Preload] ${message}`, ...args);
/* eslint-enable no-console */
}
},
};
// Use a more direct path resolution approach
@ -41,7 +50,10 @@ const getPath = (pathType) => {
}
};
logger.log("Preload script starting...");
logger.info("Preload script starting...");
// Force electron platform in the renderer process
window.process = { env: { VITE_PLATFORM: "electron" } };
try {
contextBridge.exposeInMainWorld("electronAPI", {
@ -65,6 +77,7 @@ try {
env: {
isElectron: true,
isDev: process.env.NODE_ENV === "development",
platform: "electron", // Explicitly set platform
},
// Path utilities
getBasePath: () => {
@ -72,7 +85,93 @@ try {
},
});
logger.log("Preload script completed successfully");
// Create a proxy for the CapacitorSQLite plugin
const createSQLiteProxy = () => {
const MAX_RETRIES = 3;
const RETRY_DELAY = 1000; // 1 second
const withRetry = async (operation, ...args) => {
let lastError;
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
try {
return await operation(...args);
} catch (error) {
lastError = error;
if (attempt < MAX_RETRIES) {
logger.warn(
`SQLite operation failed (attempt ${attempt}/${MAX_RETRIES}), retrying...`,
error,
);
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
}
}
}
throw new Error(
`SQLite operation failed after ${MAX_RETRIES} attempts: ${lastError?.message || "Unknown error"}`,
);
};
const wrapOperation = (method) => {
return async (...args) => {
try {
return await withRetry(
ipcRenderer.invoke,
"sqlite-" + method,
...args,
);
} catch (error) {
logger.error(`SQLite ${method} failed:`, error);
throw new Error(
`Database operation failed: ${error.message || "Unknown error"}`,
);
}
};
};
// Create a proxy that matches the CapacitorSQLite interface
return {
echo: wrapOperation("echo"),
createConnection: wrapOperation("create-connection"),
closeConnection: wrapOperation("close-connection"),
execute: wrapOperation("execute"),
query: wrapOperation("query"),
run: wrapOperation("run"),
isAvailable: wrapOperation("is-available"),
getPlatform: () => Promise.resolve("electron"),
// Add other methods as needed
};
};
// Expose only the CapacitorSQLite proxy
contextBridge.exposeInMainWorld("CapacitorSQLite", createSQLiteProxy());
// Remove the duplicate electron.sqlite bridge
contextBridge.exposeInMainWorld("electron", {
// Keep other electron APIs but remove sqlite
getPath,
send: (channel, data) => {
const validChannels = ["toMain"];
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, data);
}
},
receive: (channel, func) => {
const validChannels = ["fromMain"];
if (validChannels.includes(channel)) {
ipcRenderer.on(channel, (event, ...args) => func(...args));
}
},
env: {
isElectron: true,
isDev: process.env.NODE_ENV === "development",
platform: "electron",
},
getBasePath: () => {
return process.env.NODE_ENV === "development" ? "/" : "./";
},
});
logger.info("Preload script completed successfully");
} catch (error) {
logger.error("Error in preload script:", error);
}

59
src/interfaces/absurd-sql.d.ts

@ -0,0 +1,59 @@
import type { QueryExecResult, SqlValue } from "./database";
declare module "@jlongster/sql.js" {
interface SQL {
Database: new (path: string, options?: { filename: boolean }) => AbsurdSqlDatabase;
FS: {
mkdir: (path: string) => void;
mount: (fs: any, options: any, path: string) => void;
open: (path: string, flags: string) => any;
close: (stream: any) => void;
};
register_for_idb: (fs: any) => void;
}
interface AbsurdSqlDatabase {
exec: (sql: string, params?: unknown[]) => Promise<QueryExecResult[]>;
run: (
sql: string,
params?: unknown[],
) => Promise<{ changes: number; lastId?: number }>;
}
const initSqlJs: (options?: {
locateFile?: (file: string) => string;
}) => Promise<SQL>;
export default initSqlJs;
}
declare module "absurd-sql" {
import type { SQL } from "@jlongster/sql.js";
export class SQLiteFS {
constructor(fs: any, backend: any);
}
}
declare module "absurd-sql/dist/indexeddb-backend" {
export default class IndexedDBBackend {
constructor();
}
}
declare module "absurd-sql/dist/indexeddb-main-thread" {
export interface SQLiteOptions {
filename?: string;
autoLoad?: boolean;
debug?: boolean;
}
export interface SQLiteDatabase {
exec: (sql: string, params?: unknown[]) => Promise<QueryExecResult[]>;
close: () => Promise<void>;
}
export function initSqlJs(options?: any): Promise<any>;
export function createDatabase(options?: SQLiteOptions): Promise<SQLiteDatabase>;
export function openDatabase(options?: SQLiteOptions): Promise<SQLiteDatabase>;
}

55
src/interfaces/claims.ts

@ -1,15 +1,24 @@
import { GenericVerifiableCredential } from "./common";
/**
* Types of Claims
*
* Note that these are for the claims that get signed.
* Records that are the latest edited entities are in the records.ts file.
*
*/
export interface AgreeVerifiableCredential {
"@context": string;
import { ClaimObject } from "./common";
export interface AgreeActionClaim extends ClaimObject {
"@context": "https://schema.org";
"@type": string;
object: Record<string, unknown>;
}
// Note that previous VCs may have additional fields.
// https://endorser.ch/doc/html/transactions.html#id4
export interface GiveVerifiableCredential extends GenericVerifiableCredential {
"@context"?: string;
export interface GiveActionClaim extends ClaimObject {
// context is optional because it might be embedded in another claim, eg. an AgreeAction
"@context"?: "https://schema.org";
"@type": "GiveAction";
agent?: { identifier: string };
description?: string;
@ -17,16 +26,25 @@ export interface GiveVerifiableCredential extends GenericVerifiableCredential {
identifier?: string;
image?: string;
object?: { amountOfThisGood: number; unitCode: string };
provider?: GenericVerifiableCredential;
provider?: ClaimObject;
recipient?: { identifier: string };
}
export interface JoinActionClaim extends ClaimObject {
agent?: { identifier: string };
event?: { organizer?: { name: string }; name?: string; startTime?: string };
}
// Note that previous VCs may have additional fields.
// https://endorser.ch/doc/html/transactions.html#id8
export interface OfferVerifiableCredential extends GenericVerifiableCredential {
"@context"?: string;
export interface OfferClaim extends ClaimObject {
"@context": "https://schema.org";
"@type": "Offer";
agent?: { identifier: string };
description?: string;
fulfills?: { "@type": string; identifier?: string; lastClaimId?: string }[];
identifier?: string;
image?: string;
includesObject?: { amountOfThisGood: number; unitCode: string };
itemOffered?: {
description?: string;
@ -37,14 +55,18 @@ export interface OfferVerifiableCredential extends GenericVerifiableCredential {
name?: string;
};
};
offeredBy?: { identifier: string };
offeredBy?: {
type?: "Person";
identifier: string;
};
provider?: ClaimObject;
recipient?: { identifier: string };
validThrough?: string;
}
// Note that previous VCs may have additional fields.
// https://endorser.ch/doc/html/transactions.html#id7
export interface PlanVerifiableCredential extends GenericVerifiableCredential {
export interface PlanActionClaim extends ClaimObject {
"@context": "https://schema.org";
"@type": "PlanAction";
name: string;
@ -58,11 +80,18 @@ export interface PlanVerifiableCredential extends GenericVerifiableCredential {
}
// AKA Registration & RegisterAction
export interface RegisterVerifiableCredential {
"@context": string;
export interface RegisterActionClaim extends ClaimObject {
"@context": "https://schema.org";
"@type": "RegisterAction";
agent: { identifier: string };
identifier?: string;
object: string;
object?: string;
participant?: { identifier: string };
}
export interface TenureClaim extends ClaimObject {
"@context": "https://endorser.ch";
"@type": "Tenure";
party?: { identifier: string };
spatialUnit?: { geo?: { polygon?: string } };
}

74
src/interfaces/common.ts

@ -34,3 +34,77 @@ export interface ErrorResult extends ResultWithType {
type: "error";
error: InternalError;
}
export interface KeyMeta {
did: string;
publicKeyHex: string;
derivationPath?: string;
passkeyCredIdHex?: string; // The Webauthn credential ID in hex, if this is from a passkey
}
export interface KeyMetaMaybeWithPrivate extends KeyMeta {
mnemonic?: string; // 12 or 24 words encoding the seed
identity?: string; // Stringified IIdentifier object from Veramo
}
export interface KeyMetaWithPrivate extends KeyMeta {
mnemonic: string; // 12 or 24 words encoding the seed
identity: string; // Stringified IIdentifier object from Veramo
}
export interface QuantitativeValue extends GenericVerifiableCredential {
"@type": "QuantitativeValue";
"@context"?: string;
amountOfThisGood: number;
unitCode: string;
}
export interface AxiosErrorResponse {
message?: string;
response?: {
data?: {
error?: {
message?: string;
};
[key: string]: unknown;
};
status?: number;
config?: unknown;
};
config?: unknown;
[key: string]: unknown;
}
export interface UserInfo {
did: string;
name: string;
publicEncKey: string;
registered: boolean;
profileImageUrl?: string;
nextPublicEncKeyHash?: string;
}
export interface CreateAndSubmitClaimResult {
success: boolean;
error?: string;
handleId?: string;
}
export interface Agent {
identifier?: string;
did?: string;
}
export interface ClaimObject {
"@type": string;
"@context"?: string;
[key: string]: unknown;
}
export interface VerifiableCredentialClaim {
"@context"?: string;
"@type": string;
type: string[];
credentialSubject: ClaimObject;
[key: string]: unknown;
}

17
src/interfaces/database.ts

@ -0,0 +1,17 @@
export type SqlValue = string | number | null | Uint8Array;
export interface QueryExecResult {
columns: Array<string>;
values: Array<Array<SqlValue>>;
}
export interface DatabaseService {
initialize(): Promise<void>;
query(sql: string, params?: unknown[]): Promise<QueryExecResult[]>;
run(
sql: string,
params?: unknown[],
): Promise<{ changes: number; lastId?: number }>;
getOneRow(sql: string, params?: unknown[]): Promise<unknown[] | undefined>;
getAll(sql: string, params?: unknown[]): Promise<unknown[][]>;
}

40
src/interfaces/index.ts

@ -1,7 +1,37 @@
export * from "./claims";
export * from "./claims-result";
export * from "./common";
export type {
// From common.ts
GenericCredWrapper,
GenericVerifiableCredential,
KeyMeta,
// Exclude types that are also exported from other files
// GiveVerifiableCredential,
// OfferVerifiableCredential,
// RegisterVerifiableCredential,
// PlanSummaryRecord,
// UserInfo,
} from "./common";
export type {
// From claims.ts
GiveActionClaim,
OfferClaim,
RegisterActionClaim,
} from "./claims";
export type {
// From claims-result.ts
CreateAndSubmitClaimResult,
} from "./claims-result";
export type {
// From records.ts
PlanSummaryRecord,
} from "./records";
export type {
// From user.ts
UserInfo,
} from "./user";
export * from "./limits";
export * from "./records";
export * from "./user";
export * from "./deepLinks";

8
src/interfaces/records.ts

@ -1,14 +1,14 @@
import { GiveVerifiableCredential, OfferVerifiableCredential } from "./claims";
import { GiveActionClaim, OfferClaim } from "./claims";
// a summary record; the VC is found the fullClaim field
export interface GiveSummaryRecord {
[x: string]: PropertyKey | undefined | GiveVerifiableCredential;
[x: string]: PropertyKey | undefined | GiveActionClaim;
type?: string;
agentDid: string;
amount: number;
amountConfirmed: number;
description: string;
fullClaim: GiveVerifiableCredential;
fullClaim: GiveActionClaim;
fulfillsHandleId: string;
fulfillsPlanHandleId?: string;
fulfillsType?: string;
@ -26,7 +26,7 @@ export interface OfferSummaryRecord {
amount: number;
amountGiven: number;
amountGivenConfirmed: number;
fullClaim: OfferVerifiableCredential;
fullClaim: OfferClaim;
fulfillsPlanHandleId: string;
handleId: string;
issuerDid: string;

116
src/libs/crypto/index.ts

@ -159,7 +159,7 @@ export const nextDerivationPath = (origDerivPath: string) => {
};
// Base64 encoding/decoding utilities for browser
function base64ToArrayBuffer(base64: string): Uint8Array {
export function base64ToArrayBuffer(base64: string): Uint8Array {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
@ -168,7 +168,7 @@ function base64ToArrayBuffer(base64: string): Uint8Array {
return bytes;
}
function arrayBufferToBase64(buffer: ArrayBuffer): string {
export function arrayBufferToBase64(buffer: ArrayBuffer): string {
const binary = String.fromCharCode(...new Uint8Array(buffer));
return btoa(binary);
}
@ -178,7 +178,7 @@ const IV_LENGTH = 12;
const KEY_LENGTH = 256;
const ITERATIONS = 100000;
// Encryption helper function
// Message encryption helper function, used for onboarding meeting messages
export async function encryptMessage(message: string, password: string) {
const encoder = new TextEncoder();
const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
@ -226,7 +226,7 @@ export async function encryptMessage(message: string, password: string) {
return btoa(JSON.stringify(result));
}
// Decryption helper function
// Message decryption helper function, used for onboarding meeting messages
export async function decryptMessage(encryptedJson: string, password: string) {
const decoder = new TextDecoder();
const { salt, iv, encrypted } = JSON.parse(atob(encryptedJson));
@ -273,7 +273,7 @@ export async function decryptMessage(encryptedJson: string, password: string) {
}
// Test function to verify encryption/decryption
export async function testEncryptionDecryption() {
export async function testMessageEncryptionDecryption() {
try {
const testMessage = "Hello, this is a test message! 🚀";
const testPassword = "myTestPassword123";
@ -299,9 +299,111 @@ export async function testEncryptionDecryption() {
logger.log("\nTesting with wrong password...");
try {
await decryptMessage(encrypted, "wrongPassword");
logger.log("Should not reach here");
logger.log("Incorrectly decrypted with wrong password ❌");
} catch (error) {
logger.log("Correctly failed with wrong password ✅");
logger.log("Correctly failed to decrypt with wrong password ✅");
}
return success;
} catch (error) {
logger.error("Test failed with error:", error);
return false;
}
}
// Simple encryption using Node's crypto, used for the initial encryption of the identity and mnemonic
export async function simpleEncrypt(
text: string,
secret: ArrayBuffer,
): Promise<ArrayBuffer> {
const iv = crypto.getRandomValues(new Uint8Array(16));
// Derive a 256-bit key from the secret using SHA-256
const keyData = await crypto.subtle.digest("SHA-256", secret);
const key = await crypto.subtle.importKey(
"raw",
keyData,
{ name: "AES-GCM" },
false,
["encrypt"],
);
const encrypted = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv },
key,
new TextEncoder().encode(text),
);
// Combine IV and encrypted data
const result = new Uint8Array(iv.length + encrypted.byteLength);
result.set(iv);
result.set(new Uint8Array(encrypted), iv.length);
return result.buffer;
}
// Simple decryption using Node's crypto, used for the default decryption of identity and mnemonic
export async function simpleDecrypt(
encryptedText: ArrayBuffer,
secret: ArrayBuffer,
): Promise<string> {
const data = new Uint8Array(encryptedText);
// Extract IV and encrypted data
const iv = data.slice(0, 16);
const encrypted = data.slice(16);
// Derive the same 256-bit key from the secret using SHA-256
const keyData = await crypto.subtle.digest("SHA-256", secret);
const key = await crypto.subtle.importKey(
"raw",
keyData,
{ name: "AES-GCM" },
false,
["decrypt"],
);
const decrypted = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv },
key,
encrypted,
);
return new TextDecoder().decode(decrypted);
}
// Test function for simple encryption/decryption
export async function testSimpleEncryptionDecryption() {
try {
const testMessage = "Hello, this is a test message! 🚀";
const testSecret = crypto.getRandomValues(new Uint8Array(32));
logger.log("Original message:", testMessage);
// Test encryption
logger.log("Encrypting...");
const encrypted = await simpleEncrypt(testMessage, testSecret);
const encryptedBase64 = arrayBufferToBase64(encrypted);
logger.log("Encrypted result:", encryptedBase64);
// Test decryption
logger.log("Decrypting...");
const encryptedArrayBuffer = base64ToArrayBuffer(encryptedBase64);
const decrypted = await simpleDecrypt(encryptedArrayBuffer, testSecret);
logger.log("Decrypted result:", decrypted);
// Verify
const success = testMessage === decrypted;
logger.log("Test " + (success ? "PASSED ✅" : "FAILED ❌"));
logger.log("Messages match:", success);
// Test with wrong secret
logger.log("\nTesting with wrong secret...");
try {
await simpleDecrypt(encryptedArrayBuffer, new Uint8Array(32));
logger.log("Incorrectly decrypted with wrong secret ❌");
} catch (error) {
logger.log("Correctly failed to decrypt with wrong secret ✅");
}
return success;

21
src/libs/crypto/vc/index.ts

@ -17,29 +17,12 @@ import { didEthLocalResolver } from "./did-eth-local-resolver";
import { PEER_DID_PREFIX, verifyPeerSignature } from "./didPeer";
import { base64urlDecodeString, createDidPeerJwt } from "./passkeyDidPeer";
import { urlBase64ToUint8Array } from "./util";
import { KeyMeta, KeyMetaWithPrivate } from "../../../interfaces/common";
export const ETHR_DID_PREFIX = "did:ethr:";
export const JWT_VERIFY_FAILED_CODE = "JWT_VERIFY_FAILED";
export const UNSUPPORTED_DID_METHOD_CODE = "UNSUPPORTED_DID_METHOD";
/**
* Meta info about a key
*/
export interface KeyMeta {
/**
* Decentralized ID for the key
*/
did: string;
/**
* Stringified IIDentifier object from Veramo
*/
identity?: string;
/**
* The Webauthn credential ID in hex, if this is from a passkey
*/
passkeyCredIdHex?: string;
}
const ethLocalResolver = new Resolver({ ethr: didEthLocalResolver });
/**
@ -51,7 +34,7 @@ export function isFromPasskey(keyMeta?: KeyMeta): boolean {
}
export async function createEndorserJwtForKey(
account: KeyMeta,
account: KeyMetaWithPrivate,
payload: object,
expiresIn?: number,
) {

157
src/libs/crypto/vc/passkeyDidPeer.ts

@ -1,7 +1,6 @@
import { Buffer } from "buffer/";
import { JWTPayload } from "did-jwt";
import { DIDResolutionResult } from "did-resolver";
import { sha256 } from "ethereum-cryptography/sha256.js";
import { p256 } from "@noble/curves/p256";
import {
startAuthentication,
startRegistration,
@ -11,12 +10,13 @@ import {
generateRegistrationOptions,
verifyAuthenticationResponse,
verifyRegistrationResponse,
VerifyAuthenticationResponseOpts,
} from "@simplewebauthn/server";
import { VerifyAuthenticationResponseOpts } from "@simplewebauthn/server/esm/authentication/verifyAuthenticationResponse";
import {
Base64URLString,
PublicKeyCredentialCreationOptionsJSON,
PublicKeyCredentialRequestOptionsJSON,
AuthenticatorAssertionResponse,
} from "@simplewebauthn/types";
import { AppString } from "../../../constants/app";
@ -194,16 +194,19 @@ export class PeerSetup {
},
};
const credential = await navigator.credentials.get(options);
const credential = (await navigator.credentials.get(
options,
)) as PublicKeyCredential;
// console.log("nav credential get", credential);
this.authenticatorData = credential?.response.authenticatorData;
const response = credential?.response as AuthenticatorAssertionResponse;
this.authenticatorData = response?.authenticatorData;
const authenticatorDataBase64Url = arrayBufferToBase64URLString(
this.authenticatorData as ArrayBuffer,
);
this.clientDataJsonBase64Url = arrayBufferToBase64URLString(
credential?.response.clientDataJSON,
response?.clientDataJSON,
);
// Our custom type of JWANT means the signature is based on a concatenation of the two Webauthn properties
@ -228,9 +231,7 @@ export class PeerSetup {
.replace(/\//g, "_")
.replace(/=+$/, "");
const origSignature = Buffer.from(credential?.response.signature).toString(
"base64",
);
const origSignature = Buffer.from(response?.signature).toString("base64");
this.signature = origSignature
.replace(/\+/g, "-")
.replace(/\//g, "_")
@ -315,24 +316,18 @@ export async function createDidPeerJwt(
// ... and this import:
// import { p256 } from "@noble/curves/p256";
export async function verifyJwtP256(
credIdHex: string,
issuerDid: string,
authenticatorData: ArrayBuffer,
challenge: Uint8Array,
clientDataJsonBase64Url: Base64URLString,
signature: Base64URLString,
) {
const authDataFromBase = Buffer.from(authenticatorData);
const clientDataFromBase = Buffer.from(clientDataJsonBase64Url, "base64");
const sigBuffer = Buffer.from(signature, "base64");
const finalSigBuffer = unwrapEC2Signature(sigBuffer);
const publicKeyBytes = peerDidToPublicKeyBytes(issuerDid);
// Hash the client data
const hash = sha256(clientDataFromBase);
// Construct the preimage
const preimage = Buffer.concat([authDataFromBase, hash]);
// Use challenge in preimage construction
const preimage = Buffer.concat([authDataFromBase, Buffer.from(challenge)]);
const isValid = p256.verify(
finalSigBuffer,
@ -383,122 +378,37 @@ export async function verifyJwtSimplewebauthn(
// similar code is in endorser-ch util-crypto.ts verifyPeerSignature
export async function verifyJwtWebCrypto(
credId: Base64URLString,
issuerDid: string,
authenticatorData: ArrayBuffer,
challenge: Uint8Array,
clientDataJsonBase64Url: Base64URLString,
signature: Base64URLString,
) {
const authDataFromBase = Buffer.from(authenticatorData);
const clientDataFromBase = Buffer.from(clientDataJsonBase64Url, "base64");
const sigBuffer = Buffer.from(signature, "base64");
const finalSigBuffer = unwrapEC2Signature(sigBuffer);
// Hash the client data
const hash = sha256(clientDataFromBase);
// Use challenge in preimage construction
const preimage = Buffer.concat([authDataFromBase, Buffer.from(challenge)]);
// Construct the preimage
const preimage = Buffer.concat([authDataFromBase, hash]);
return verifyPeerSignature(preimage, issuerDid, finalSigBuffer);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function peerDidToDidDocument(did: string): Promise<DIDResolutionResult> {
if (!did.startsWith("did:peer:0z")) {
throw new Error(
"This only verifies a peer DID, method 0, encoded base58btc.",
);
}
// this is basically hard-coded from https://www.w3.org/TR/did-core/#example-various-verification-method-types
// (another reference is the @aviarytech/did-peer resolver)
/**
* Looks like JsonWebKey2020 isn't too difficult:
* - change context security/suites link to jws-2020/v1
* - change publicKeyMultibase to publicKeyJwk generated with cborToKeys
* - change type to JsonWebKey2020
*/
const id = did.split(":")[2];
const multibase = id.slice(1);
const encnumbasis = multibase.slice(1);
const didDocument = {
"@context": [
"https://www.w3.org/ns/did/v1",
"https://w3id.org/security/suites/secp256k1-2019/v1",
],
assertionMethod: [did + "#" + encnumbasis],
authentication: [did + "#" + encnumbasis],
capabilityDelegation: [did + "#" + encnumbasis],
capabilityInvocation: [did + "#" + encnumbasis],
id: did,
keyAgreement: undefined,
service: undefined,
verificationMethod: [
{
controller: did,
id: did + "#" + encnumbasis,
publicKeyMultibase: multibase,
type: "EcdsaSecp256k1VerificationKey2019",
},
],
};
return {
didDocument,
didDocumentMetadata: {},
didResolutionMetadata: { contentType: "application/did+ld+json" },
};
}
// convert COSE public key to PEM format
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function COSEtoPEM(cose: Buffer) {
// const alg = cose.get(3); // Algorithm
const x = cose[-2]; // x-coordinate
const y = cose[-3]; // y-coordinate
// Remove unused functions:
// - peerDidToDidDocument
// - COSEtoPEM
// - base64urlDecodeArrayBuffer
// - base64urlEncodeArrayBuffer
// - pemToCryptoKey
// Ensure the coordinates are in the correct format
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error because it complains about the type of x and y
const pubKeyBuffer = Buffer.concat([Buffer.from([0x04]), x, y]);
// Convert to PEM format
const pem = `-----BEGIN PUBLIC KEY-----
${pubKeyBuffer.toString("base64")}
-----END PUBLIC KEY-----`;
return pem;
}
// tried the base64url library but got an error using their Buffer
// Keep only the used functions:
export function base64urlDecodeString(input: string) {
return atob(input.replace(/-/g, "+").replace(/_/g, "/"));
}
// tried the base64url library but got an error using their Buffer
export function base64urlEncodeString(input: string) {
return btoa(input).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function base64urlDecodeArrayBuffer(input: string) {
input = input.replace(/-/g, "+").replace(/_/g, "/");
const pad = input.length % 4 === 0 ? "" : "====".slice(input.length % 4);
const str = atob(input + pad);
const bytes = new Uint8Array(str.length);
for (let i = 0; i < str.length; i++) {
bytes[i] = str.charCodeAt(i);
}
return bytes.buffer;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function base64urlEncodeArrayBuffer(buffer: ArrayBuffer) {
const str = String.fromCharCode(...new Uint8Array(buffer));
return base64urlEncodeString(str);
}
// from @simplewebauthn/browser
function arrayBufferToBase64URLString(buffer: ArrayBuffer) {
const bytes = new Uint8Array(buffer);
@ -523,28 +433,3 @@ function base64URLStringToArrayBuffer(base64URLString: string) {
}
return buffer;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function pemToCryptoKey(pem: string) {
const binaryDerString = atob(
pem
.split("\n")
.filter((x) => !x.includes("-----"))
.join(""),
);
const binaryDer = new Uint8Array(binaryDerString.length);
for (let i = 0; i < binaryDerString.length; i++) {
binaryDer[i] = binaryDerString.charCodeAt(i);
}
// console.log("binaryDer", binaryDer.buffer);
return await window.crypto.subtle.importKey(
"spki",
binaryDer.buffer,
{
name: "RSASSA-PKCS1-v1_5",
hash: "SHA-256",
},
true,
["verify"],
);
}

420
src/libs/endorserServer.ts

@ -26,29 +26,42 @@ import {
DEFAULT_IMAGE_API_SERVER,
NotificationIface,
APP_SERVER,
USE_DEXIE_DB,
} from "../constants/app";
import { Contact } from "../db/tables/contacts";
import { accessToken, deriveAddress, nextDerivationPath } from "../libs/crypto";
import { logConsoleAndDb, NonsensitiveDexie } from "../db/index";
import { NonsensitiveDexie } from "../db/index";
import { logConsoleAndDb } from "../db/databaseUtil";
import {
retrieveAccountMetadata,
retrieveFullyDecryptedAccount,
getPasskeyExpirationSeconds,
} from "../libs/util";
import { createEndorserJwtForKey, KeyMeta } from "../libs/crypto/vc";
import { createEndorserJwtForKey } from "../libs/crypto/vc";
import {
GiveActionClaim,
JoinActionClaim,
OfferClaim,
PlanActionClaim,
RegisterActionClaim,
TenureClaim,
} from "../interfaces/claims";
import {
GiveVerifiableCredential,
OfferVerifiableCredential,
RegisterVerifiableCredential,
GenericVerifiableCredential,
GenericCredWrapper,
PlanSummaryRecord,
GenericVerifiableCredential,
AxiosErrorResponse,
UserInfo,
CreateAndSubmitClaimResult,
} from "../interfaces";
ClaimObject,
VerifiableCredentialClaim,
QuantitativeValue,
KeyMetaWithPrivate,
KeyMetaMaybeWithPrivate,
} from "../interfaces/common";
import { PlanSummaryRecord } from "../interfaces/records";
import { logger } from "../utils/logger";
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
/**
* Standard context for schema.org data
@ -100,7 +113,10 @@ export const ENDORSER_CH_HANDLE_PREFIX = "https://endorser.ch/entity/";
export const BLANK_GENERIC_SERVER_RECORD: GenericCredWrapper<GenericVerifiableCredential> =
{
claim: { "@type": "" },
claim: {
"@context": SCHEMA_ORG_CONTEXT,
"@type": "",
},
handleId: "",
id: "",
issuedAt: "",
@ -180,37 +196,21 @@ export function isEmptyOrHiddenDid(did?: string): boolean {
* };
* testRecursivelyOnStrings(isHiddenDid, obj); // Returns: true
*/
function testRecursivelyOnStrings(
func: (arg0: unknown) => boolean,
const testRecursivelyOnStrings = (
input: unknown,
): boolean {
// Test direct string values
if (Object.prototype.toString.call(input) === "[object String]") {
return func(input);
}
// Recursively test objects and arrays
else if (input instanceof Object) {
if (!Array.isArray(input)) {
// Handle plain objects
for (const key in input) {
if (testRecursivelyOnStrings(func, input[key])) {
return true;
}
}
} else {
// Handle arrays
for (const value of input) {
if (testRecursivelyOnStrings(func, value)) {
return true;
}
}
test: (s: string) => boolean,
): boolean => {
if (typeof input === "string") {
return test(input);
} else if (Array.isArray(input)) {
return input.some((item) => testRecursivelyOnStrings(item, test));
} else if (input && typeof input === "object") {
return Object.values(input as Record<string, unknown>).some((value) =>
testRecursivelyOnStrings(value, test),
);
}
return false;
} else {
// Non-string, non-object values can't contain strings
return false;
}
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function containsHiddenDid(obj: any) {
@ -551,7 +551,11 @@ export async function setPlanInCache(
* @returns {string|undefined} User-friendly message or undefined if none found
*/
export function serverMessageForUser(error: unknown): string | undefined {
return error?.response?.data?.error?.message;
if (error && typeof error === "object" && "response" in error) {
const err = error as AxiosErrorResponse;
return err.response?.data?.error?.message;
}
return undefined;
}
/**
@ -573,20 +577,29 @@ export function errorStringForLog(error: unknown) {
// --- property '_value' closes the circle
}
let fullError = "" + error + " - JSON: " + stringifiedError;
const errorResponseText = JSON.stringify(error.response);
if (error && typeof error === "object" && "response" in error) {
const err = error as AxiosErrorResponse;
const errorResponseText = JSON.stringify(err.response);
// for some reason, error.response is not included in stringify result (eg. for 400 errors on invite redemptions)
if (!R.empty(errorResponseText) && !fullError.includes(errorResponseText)) {
// add error.response stuff
if (R.equals(error?.config, error?.response?.config)) {
if (
err.response?.config &&
err.config &&
R.equals(err.config, err.response.config)
) {
// but exclude "config" because it's already in there
const newErrorResponseText = JSON.stringify(
R.omit(["config"] as never[], error.response),
R.omit(["config"] as never[], err.response),
);
fullError += " - .response w/o same config JSON: " + newErrorResponseText;
fullError +=
" - .response w/o same config JSON: " + newErrorResponseText;
} else {
fullError += " - .response JSON: " + errorResponseText;
}
}
}
return fullError;
}
@ -642,7 +655,7 @@ export async function getNewOffersToUserProjects(
* @param lastClaimId supplied when editing a previous claim
*/
export function hydrateGive(
vcClaimOrig?: GiveVerifiableCredential,
vcClaimOrig?: GiveActionClaim,
fromDid?: string,
toDid?: string,
description?: string,
@ -650,14 +663,12 @@ export function hydrateGive(
unitCode?: string,
fulfillsProjectHandleId?: string,
fulfillsOfferHandleId?: string,
isTrade: boolean = false, // remove, because this app is all for gifting
isTrade: boolean = false,
imageUrl?: string,
providerPlanHandleId?: string,
lastClaimId?: string,
): GiveVerifiableCredential {
// Remember: replace values or erase if it's null
const vcClaim: GiveVerifiableCredential = vcClaimOrig
): GiveActionClaim {
const vcClaim: GiveActionClaim = vcClaimOrig
? R.clone(vcClaimOrig)
: {
"@context": SCHEMA_ORG_CONTEXT,
@ -665,55 +676,72 @@ export function hydrateGive(
};
if (lastClaimId) {
// this is an edit
vcClaim.lastClaimId = lastClaimId;
delete vcClaim.identifier;
}
vcClaim.agent = fromDid ? { identifier: fromDid } : undefined;
vcClaim.recipient = toDid ? { identifier: toDid } : undefined;
if (fromDid) {
vcClaim.agent = { identifier: fromDid };
}
if (toDid) {
vcClaim.recipient = { identifier: toDid };
}
vcClaim.description = description || undefined;
vcClaim.object =
amount && !isNaN(amount)
? { amountOfThisGood: amount, unitCode: unitCode || "HUR" }
: undefined;
// ensure fulfills is an array
if (amount && !isNaN(amount)) {
const quantitativeValue: QuantitativeValue = {
"@type": "QuantitativeValue",
amountOfThisGood: amount,
unitCode: unitCode || "HUR",
};
vcClaim.object = quantitativeValue;
}
// Initialize fulfills array if not present
if (!Array.isArray(vcClaim.fulfills)) {
vcClaim.fulfills = vcClaim.fulfills ? [vcClaim.fulfills] : [];
}
// ... and replace or add each element, ending with Trade or Donate
// I realize the following doesn't change any elements that are not PlanAction or Offer or Trade/Action.
// Filter and add fulfills elements
vcClaim.fulfills = vcClaim.fulfills.filter(
(elem) => elem["@type"] !== "PlanAction",
(elem: { "@type": string }) => elem["@type"] !== "PlanAction",
);
if (fulfillsProjectHandleId) {
vcClaim.fulfills.push({
"@type": "PlanAction",
identifier: fulfillsProjectHandleId,
});
}
vcClaim.fulfills = vcClaim.fulfills.filter(
(elem) => elem["@type"] !== "Offer",
(elem: { "@type": string }) => elem["@type"] !== "Offer",
);
if (fulfillsOfferHandleId) {
vcClaim.fulfills.push({
"@type": "Offer",
identifier: fulfillsOfferHandleId,
});
}
// do Trade/Donate last because current endorser.ch only looks at the first for plans & offers
vcClaim.fulfills = vcClaim.fulfills.filter(
(elem) =>
(elem: { "@type": string }) =>
elem["@type"] !== "DonateAction" && elem["@type"] !== "TradeAction",
);
vcClaim.fulfills.push({ "@type": isTrade ? "TradeAction" : "DonateAction" });
vcClaim.fulfills.push({
"@type": isTrade ? "TradeAction" : "DonateAction",
});
vcClaim.image = imageUrl || undefined;
vcClaim.provider = providerPlanHandleId
? { "@type": "PlanAction", identifier: providerPlanHandleId }
: undefined;
if (providerPlanHandleId) {
vcClaim.provider = {
"@type": "PlanAction",
identifier: providerPlanHandleId,
};
}
return vcClaim;
}
@ -774,7 +802,7 @@ export async function createAndSubmitGive(
export async function editAndSubmitGive(
axios: Axios,
apiServer: string,
fullClaim: GenericCredWrapper<GiveVerifiableCredential>,
fullClaim: GenericCredWrapper<GiveActionClaim>,
issuerDid: string,
fromDid?: string,
toDid?: string,
@ -815,7 +843,7 @@ export async function editAndSubmitGive(
* @param lastClaimId supplied when editing a previous claim
*/
export function hydrateOffer(
vcClaimOrig?: OfferVerifiableCredential,
vcClaimOrig?: OfferClaim,
fromDid?: string,
toDid?: string,
itemDescription?: string,
@ -825,10 +853,8 @@ export function hydrateOffer(
fulfillsProjectHandleId?: string,
validThrough?: string,
lastClaimId?: string,
): OfferVerifiableCredential {
// Remember: replace values or erase if it's null
const vcClaim: OfferVerifiableCredential = vcClaimOrig
): OfferClaim {
const vcClaim: OfferClaim = vcClaimOrig
? R.clone(vcClaimOrig)
: {
"@context": SCHEMA_ORG_CONTEXT,
@ -841,14 +867,20 @@ export function hydrateOffer(
delete vcClaim.identifier;
}
vcClaim.offeredBy = fromDid ? { identifier: fromDid } : undefined;
vcClaim.recipient = toDid ? { identifier: toDid } : undefined;
if (fromDid) {
vcClaim.offeredBy = { identifier: fromDid };
}
if (toDid) {
vcClaim.recipient = { identifier: toDid };
}
vcClaim.description = conditionDescription || undefined;
vcClaim.includesObject =
amount && !isNaN(amount)
? { amountOfThisGood: amount, unitCode: unitCode || "HUR" }
: undefined;
if (amount && !isNaN(amount)) {
vcClaim.includesObject = {
amountOfThisGood: amount,
unitCode: unitCode || "HUR",
};
}
if (itemDescription || fulfillsProjectHandleId) {
vcClaim.itemOffered = vcClaim.itemOffered || {};
@ -860,6 +892,7 @@ export function hydrateOffer(
};
}
}
vcClaim.validThrough = validThrough || undefined;
return vcClaim;
@ -899,7 +932,7 @@ export async function createAndSubmitOffer(
undefined,
);
return createAndSubmitClaim(
vcClaim as OfferVerifiableCredential,
vcClaim as OfferClaim,
issuerDid,
apiServer,
axios,
@ -909,7 +942,7 @@ export async function createAndSubmitOffer(
export async function editAndSubmitOffer(
axios: Axios,
apiServer: string,
fullClaim: GenericCredWrapper<OfferVerifiableCredential>,
fullClaim: GenericCredWrapper<OfferClaim>,
issuerDid: string,
itemDescription: string,
amount?: number,
@ -932,7 +965,7 @@ export async function editAndSubmitOffer(
fullClaim.id,
);
return createAndSubmitClaim(
vcClaim as OfferVerifiableCredential,
vcClaim as OfferClaim,
issuerDid,
apiServer,
axios,
@ -968,11 +1001,12 @@ export async function createAndSubmitClaim(
axios: Axios,
): Promise<CreateAndSubmitClaimResult> {
try {
const vcPayload = {
const vcPayload: { vc: VerifiableCredentialClaim } = {
vc: {
"@context": ["https://www.w3.org/2018/credentials/v1"],
"@context": "https://www.w3.org/2018/credentials/v1",
"@type": "VerifiableCredential",
type: ["VerifiableCredential"],
credentialSubject: vcClaim,
credentialSubject: vcClaim as unknown as ClaimObject,
},
};
@ -988,26 +1022,25 @@ export async function createAndSubmitClaim(
},
});
return { type: "success", response };
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (error: any) {
return { success: true, handleId: response.data?.handleId };
} catch (error: unknown) {
logger.error("Error submitting claim:", error);
const errorMessage: string =
serverMessageForUser(error) ||
error.message ||
(error && typeof error === "object" && "message" in error
? String(error.message)
: undefined) ||
"Got some error submitting the claim. Check your permissions, network, and error logs.";
return {
type: "error",
error: {
success: false,
error: errorMessage,
},
};
}
}
export async function generateEndorserJwtUrlForAccount(
account: KeyMeta,
account: KeyMetaMaybeWithPrivate,
isRegistered: boolean,
givenName: string,
profileImageUrl: string,
@ -1031,12 +1064,9 @@ export async function generateEndorserJwtUrlForAccount(
}
// Add the next key -- not recommended for the QR code for such a high resolution
if (isContact && account?.mnemonic && account?.derivationPath) {
const newDerivPath = nextDerivationPath(account.derivationPath as string);
const nextPublicHex = deriveAddress(
account.mnemonic as string,
newDerivPath,
)[2];
if (isContact && account.derivationPath && account.mnemonic) {
const newDerivPath = nextDerivationPath(account.derivationPath);
const nextPublicHex = deriveAddress(account.mnemonic, newDerivPath)[2];
const nextPublicEncKey = Buffer.from(nextPublicHex, "hex");
const nextPublicEncKeyHash = sha256(nextPublicEncKey);
const nextPublicEncKeyHashBase64 =
@ -1056,7 +1086,11 @@ export async function createEndorserJwtForDid(
expiresIn?: number,
) {
const account = await retrieveFullyDecryptedAccount(issuerDid);
return createEndorserJwtForKey(account as KeyMeta, payload, expiresIn);
return createEndorserJwtForKey(
account as KeyMetaWithPrivate,
payload,
expiresIn,
);
}
/**
@ -1104,21 +1138,21 @@ export const capitalizeAndInsertSpacesBeforeCaps = (text: string) => {
similar code is also contained in endorser-mobile
**/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const claimSummary = (
claim: GenericCredWrapper<GenericVerifiableCredential>,
claim:
| GenericVerifiableCredential
| GenericCredWrapper<GenericVerifiableCredential>,
) => {
if (!claim) {
// to differentiate from "something" above
return "something";
}
let specificClaim:
| GenericVerifiableCredential
| GenericCredWrapper<GenericVerifiableCredential> = claim;
if (claim.claim) {
// probably a Verified Credential
// eslint-disable-next-line @typescript-eslint/no-explicit-any
specificClaim = claim.claim;
let specificClaim: GenericVerifiableCredential;
if ("claim" in claim) {
// It's a GenericCredWrapper
specificClaim = claim.claim as GenericVerifiableCredential;
} else {
// It's already a GenericVerifiableCredential
specificClaim = claim;
}
if (Array.isArray(specificClaim)) {
if (specificClaim.length === 1) {
@ -1153,88 +1187,112 @@ export const claimSpecialDescription = (
identifiers: Array<string>,
contacts: Array<Contact>,
) => {
let claim = record.claim;
if (claim.claim) {
// it's probably a Verified Credential
claim = claim.claim;
let claim:
| GenericVerifiableCredential
| GenericCredWrapper<GenericVerifiableCredential> = record.claim;
if ("claim" in claim) {
// it's a nested GenericCredWrapper
claim = claim.claim as GenericVerifiableCredential;
}
const issuer = didInfo(record.issuer, activeDid, identifiers, contacts);
const type = claim["@type"] || "UnknownType";
if (type === "AgreeAction") {
return issuer + " agreed with " + claimSummary(claim.object);
return (
issuer +
" agreed with " +
claimSummary(claim.object as GenericVerifiableCredential)
);
} else if (isAccept(claim)) {
return issuer + " accepted " + claimSummary(claim.object);
return (
issuer +
" accepted " +
claimSummary(claim.object as GenericVerifiableCredential)
);
} else if (type === "GiveAction") {
// agent.did is for legacy data, before March 2023
const giver = claim.agent?.identifier || claim.agent?.did;
const giveClaim = claim as GiveActionClaim;
// @ts-expect-error because .did may be found in legacy data, before March 2023
const legacyGiverDid = giveClaim.agent?.did;
const giver = giveClaim.agent?.identifier || legacyGiverDid;
const giverInfo = didInfo(giver, activeDid, identifiers, contacts);
let gaveAmount = claim.object?.amountOfThisGood
? displayAmount(claim.object.unitCode, claim.object.amountOfThisGood)
let gaveAmount = giveClaim.object?.amountOfThisGood
? displayAmount(
giveClaim.object.unitCode as string,
giveClaim.object.amountOfThisGood as number,
)
: "";
if (claim.description) {
if (giveClaim.description) {
if (gaveAmount) {
gaveAmount = gaveAmount + ", and also: ";
}
gaveAmount = gaveAmount + claim.description;
gaveAmount = gaveAmount + giveClaim.description;
}
if (!gaveAmount) {
gaveAmount = "something not described";
}
// recipient.did is for legacy data, before March 2023
const gaveRecipientId = claim.recipient?.identifier || claim.recipient?.did;
// @ts-expect-error because .did may be found in legacy data, before March 2023
const legacyRecipDid = giveClaim.recipient?.did;
const gaveRecipientId = giveClaim.recipient?.identifier || legacyRecipDid;
const gaveRecipientInfo = gaveRecipientId
? " to " + didInfo(gaveRecipientId, activeDid, identifiers, contacts)
: "";
return giverInfo + " gave" + gaveRecipientInfo + ": " + gaveAmount;
} else if (type === "JoinAction") {
// agent.did is for legacy data, before March 2023
const agent = claim.agent?.identifier || claim.agent?.did;
const joinClaim = claim as JoinActionClaim;
// @ts-expect-error because .did may be found in legacy data, before March 2023
const legacyDid = joinClaim.agent?.did;
const agent = joinClaim.agent?.identifier || legacyDid;
const contactInfo = didInfo(agent, activeDid, identifiers, contacts);
let eventOrganizer =
claim.event && claim.event.organizer && claim.event.organizer.name;
joinClaim.event &&
joinClaim.event.organizer &&
joinClaim.event.organizer.name;
eventOrganizer = eventOrganizer || "";
let eventName = claim.event && claim.event.name;
let eventName = joinClaim.event && joinClaim.event.name;
eventName = eventName ? " " + eventName : "";
let fullEvent = eventOrganizer + eventName;
fullEvent = fullEvent ? " attended the " + fullEvent : "";
let eventDate = claim.event && claim.event.startTime;
let eventDate = joinClaim.event && joinClaim.event.startTime;
eventDate = eventDate ? " at " + eventDate : "";
return contactInfo + fullEvent + eventDate;
} else if (isOffer(claim)) {
const offerer = claim.offeredBy?.identifier;
const offerClaim = claim as OfferClaim;
const offerer = offerClaim.offeredBy?.identifier;
const contactInfo = didInfo(offerer, activeDid, identifiers, contacts);
let offering = "";
if (claim.includesObject) {
if (offerClaim.includesObject) {
offering +=
" " +
displayAmount(
claim.includesObject.unitCode,
claim.includesObject.amountOfThisGood,
offerClaim.includesObject.unitCode,
offerClaim.includesObject.amountOfThisGood,
);
}
if (claim.itemOffered?.description) {
offering += ", saying: " + claim.itemOffered?.description;
if (offerClaim.itemOffered?.description) {
offering += ", saying: " + offerClaim.itemOffered?.description;
}
// recipient.did is for legacy data, before March 2023
const offerRecipientId =
claim.recipient?.identifier || claim.recipient?.did;
// @ts-expect-error because .did may be found in legacy data, before March 2023
const legacyDid = offerClaim.recipient?.did;
const offerRecipientId = offerClaim.recipient?.identifier || legacyDid;
const offerRecipientInfo = offerRecipientId
? " to " + didInfo(offerRecipientId, activeDid, identifiers, contacts)
: "";
return contactInfo + " offered" + offering + offerRecipientInfo;
} else if (type === "PlanAction") {
const claimer = claim.agent?.identifier || record.issuer;
const planClaim = claim as PlanActionClaim;
const claimer = planClaim.agent?.identifier || record.issuer;
const claimerInfo = didInfo(claimer, activeDid, identifiers, contacts);
return claimerInfo + " announced a project: " + claim.name;
return claimerInfo + " announced a project: " + planClaim.name;
} else if (type === "Tenure") {
// party.did is for legacy data, before March 2023
const claimer = claim.party?.identifier || claim.party?.did;
const tenureClaim = claim as TenureClaim;
// @ts-expect-error because .did may be found in legacy data, before March 2023
const legacyDid = tenureClaim.party?.did;
const claimer = tenureClaim.party?.identifier || legacyDid;
const contactInfo = didInfo(claimer, activeDid, identifiers, contacts);
const polygon = claim.spatialUnit?.geo?.polygon || "";
const polygon = tenureClaim.spatialUnit?.geo?.polygon || "";
return (
contactInfo +
" possesses [" +
@ -1242,11 +1300,7 @@ export const claimSpecialDescription = (
"...]"
);
} else {
return (
issuer +
" declared " +
claimSummary(claim as GenericCredWrapper<GenericVerifiableCredential>)
);
return issuer + " declared " + claimSummary(claim);
}
};
@ -1278,7 +1332,7 @@ export async function createEndorserJwtVcFromClaim(
// Make a payload for the claim
const vcPayload = {
vc: {
"@context": ["https://www.w3.org/2018/credentials/v1"],
"@context": "https://www.w3.org/2018/credentials/v1",
type: ["VerifiableCredential"],
credentialSubject: claim,
},
@ -1286,32 +1340,42 @@ export async function createEndorserJwtVcFromClaim(
return createEndorserJwtForDid(issuerDid, vcPayload);
}
/**
* Create a JWT for a RegisterAction claim.
*
* @param activeDid - The DID of the user creating the invite
* @param contact - The contact to register, with a 'did' field (all optional for invites)
* @param identifier - The identifier for the invite, usually random
* @param expiresIn - The number of seconds until the invite expires
* @returns The JWT for the RegisterAction claim
*/
export async function createInviteJwt(
activeDid: string,
contact?: Contact,
inviteId?: string,
expiresIn?: number,
identifier?: string,
expiresIn?: number, // in seconds
): Promise<string> {
const vcClaim: RegisterVerifiableCredential = {
const vcClaim: RegisterActionClaim = {
"@context": SCHEMA_ORG_CONTEXT,
"@type": "RegisterAction",
agent: { identifier: activeDid },
object: SERVICE_ID,
identifier: identifier,
};
if (contact) {
if (contact?.did) {
vcClaim.participant = { identifier: contact.did };
}
if (inviteId) {
vcClaim.identifier = inviteId;
}
// Make a payload for the claim
const vcPayload = {
const vcPayload: { vc: VerifiableCredentialClaim } = {
vc: {
"@context": ["https://www.w3.org/2018/credentials/v1"],
"@context": "https://www.w3.org/2018/credentials/v1",
"@type": "VerifiableCredential",
type: ["VerifiableCredential"],
credentialSubject: vcClaim,
credentialSubject: vcClaim as unknown as ClaimObject,
},
};
// Create a signature using private key of identity
const vcJwt = await createEndorserJwtForDid(activeDid, vcPayload, expiresIn);
return vcJwt;
@ -1323,21 +1387,44 @@ export async function register(
axios: Axios,
contact: Contact,
): Promise<{ success?: boolean; error?: string }> {
try {
const vcJwt = await createInviteJwt(activeDid, contact);
const url = apiServer + "/api/v2/claim";
const resp = await axios.post(url, { jwtEncoded: vcJwt });
const resp = await axios.post<{
success?: {
handleId?: string;
embeddedRecordError?: string;
};
error?: string;
message?: string;
}>(url, { jwtEncoded: vcJwt });
if (resp.data?.success?.handleId) {
return { success: true };
} else if (resp.data?.success?.embeddedRecordError) {
let message =
"There was some problem with the registration and so it may not be complete.";
if (typeof resp.data.success.embeddedRecordError == "string") {
if (typeof resp.data.success.embeddedRecordError === "string") {
message += " " + resp.data.success.embeddedRecordError;
}
return { error: message };
} else {
logger.error(resp);
logger.error("Registration error:", JSON.stringify(resp.data));
return { error: "Got a server error when registering." };
}
} catch (error: unknown) {
if (error && typeof error === "object") {
const err = error as AxiosErrorResponse;
const errorMessage =
err.message ||
(err.response?.data &&
typeof err.response.data === "object" &&
"message" in err.response.data
? (err.response.data as { message: string }).message
: undefined);
logger.error("Registration error:", errorMessage || JSON.stringify(err));
return { error: errorMessage || "Got a server error when registering." };
}
return { error: "Got a server error when registering." };
}
}
@ -1363,8 +1450,15 @@ export async function setVisibilityUtil(
if (resp.status === 200) {
const success = resp.data.success;
if (success) {
const platformService = PlatformServiceFactory.getInstance();
await platformService.dbExec(
"UPDATE contacts SET seesMe = ? WHERE did = ?",
[visibility, contact.did],
);
if (USE_DEXIE_DB) {
db.contacts.update(contact.did, { seesMe: visibility });
}
}
return { success };
} else {
logger.error(

296
src/libs/util.ts

@ -5,29 +5,43 @@ import { Buffer } from "buffer";
import * as R from "ramda";
import { useClipboard } from "@vueuse/core";
import { DEFAULT_PUSH_SERVER, NotificationIface } from "../constants/app";
import {
DEFAULT_PUSH_SERVER,
NotificationIface,
USE_DEXIE_DB,
} from "../constants/app";
import {
accountsDBPromise,
retrieveSettingsForActiveAccount,
updateAccountSettings,
updateDefaultSettings,
} from "../db/index";
import { Account } from "../db/tables/accounts";
import { Account, AccountEncrypted } from "../db/tables/accounts";
import { Contact } from "../db/tables/contacts";
import * as databaseUtil from "../db/databaseUtil";
import { DEFAULT_PASSKEY_EXPIRATION_MINUTES } from "../db/tables/settings";
import { deriveAddress, generateSeed, newIdentifier } from "../libs/crypto";
import {
arrayBufferToBase64,
base64ToArrayBuffer,
deriveAddress,
generateSeed,
newIdentifier,
simpleDecrypt,
simpleEncrypt,
} from "../libs/crypto";
import * as serverUtil from "../libs/endorserServer";
import { containsHiddenDid } from "../libs/endorserServer";
import {
containsHiddenDid,
GenericCredWrapper,
GenericVerifiableCredential,
GiveSummaryRecord,
OfferVerifiableCredential,
} from "../libs/endorserServer";
import { KeyMeta } from "../libs/crypto/vc";
KeyMetaWithPrivate,
} from "../interfaces/common";
import { GiveSummaryRecord } from "../interfaces/records";
import { OfferClaim } from "../interfaces/claims";
import { createPeerDid } from "../libs/crypto/vc/didPeer";
import { registerCredential } from "../libs/crypto/vc/passkeyDidPeer";
import { logger } from "../utils/logger";
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
export interface GiverReceiverInputInfo {
did?: string;
@ -364,16 +378,19 @@ export function base64ToBlob(base64DataUrl: string, sliceSize = 512) {
* @param veriClaim is expected to have fields: claim and issuer
*/
export function offerGiverDid(
veriClaim: GenericCredWrapper<OfferVerifiableCredential>,
veriClaim: GenericCredWrapper<OfferClaim>,
): string | undefined {
let giver;
if (
veriClaim.claim.offeredBy?.identifier &&
!serverUtil.isHiddenDid(veriClaim.claim.offeredBy.identifier as string)
) {
giver = veriClaim.claim.offeredBy.identifier;
} else if (veriClaim.issuer && !serverUtil.isHiddenDid(veriClaim.issuer)) {
const innerClaim = veriClaim.claim as OfferClaim;
let giver: string | undefined = undefined;
giver = innerClaim.offeredBy?.identifier;
if (giver && !serverUtil.isHiddenDid(giver)) {
return giver;
}
giver = veriClaim.issuer;
if (giver && !serverUtil.isHiddenDid(giver)) {
return giver;
}
return giver;
}
@ -387,7 +404,7 @@ export const canFulfillOffer = (
) => {
return (
veriClaim.claimType === "Offer" &&
!!offerGiverDid(veriClaim as GenericCredWrapper<OfferVerifiableCredential>)
!!offerGiverDid(veriClaim as GenericCredWrapper<OfferClaim>)
);
};
@ -457,27 +474,67 @@ export function findAllVisibleToDids(
*
**/
export interface AccountKeyInfo extends Account, KeyMeta {}
export type AccountKeyInfo = Account & KeyMetaWithPrivate;
export const retrieveAccountCount = async (): Promise<number> => {
let result = 0;
const platformService = PlatformServiceFactory.getInstance();
const dbResult = await platformService.dbQuery(
`SELECT COUNT(*) FROM accounts`,
);
if (dbResult?.values?.[0]?.[0]) {
result = dbResult.values[0][0] as number;
}
if (USE_DEXIE_DB) {
// one of the few times we use accountsDBPromise directly; try to avoid more usage
const accountsDB = await accountsDBPromise;
return await accountsDB.accounts.count();
result = await accountsDB.accounts.count();
}
return result;
};
export const retrieveAccountDids = async (): Promise<string[]> => {
const platformService = PlatformServiceFactory.getInstance();
const dbAccounts = await platformService.dbQuery(`SELECT did FROM accounts`);
let allDids =
databaseUtil
.mapQueryResultToValues(dbAccounts)
?.map((row) => row[0] as string) || [];
if (USE_DEXIE_DB) {
// this is the old way
// one of the few times we use accountsDBPromise directly; try to avoid more usage
const accountsDB = await accountsDBPromise;
const allAccounts = await accountsDB.accounts.toArray();
const allDids = allAccounts.map((acc) => acc.did);
allDids = allAccounts.map((acc) => acc.did);
}
return allDids;
};
// This is provided and recommended when the full key is not necessary so that
// future work could separate this info from the sensitive key material.
/**
* This is provided and recommended when the full key is not necessary so that
* future work could separate this info from the sensitive key material.
*
* If you need the private key data, use retrieveFullyDecryptedAccount instead.
*/
export const retrieveAccountMetadata = async (
activeDid: string,
): Promise<AccountKeyInfo | undefined> => {
): Promise<Account | undefined> => {
let result: Account | undefined = undefined;
const platformService = PlatformServiceFactory.getInstance();
const dbAccount = await platformService.dbQuery(
`SELECT * FROM accounts WHERE did = ?`,
[activeDid],
);
const account = databaseUtil.mapQueryResultToValues(dbAccount)[0] as Account;
if (account) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { identity, mnemonic, ...metadata } = account;
result = metadata;
} else {
result = undefined;
}
if (USE_DEXIE_DB) {
// one of the few times we use accountsDBPromise directly; try to avoid more usage
const accountsDB = await accountsDBPromise;
const account = (await accountsDB.accounts
@ -487,59 +544,135 @@ export const retrieveAccountMetadata = async (
if (account) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { identity, mnemonic, ...metadata } = account;
return metadata;
result = metadata;
} else {
return undefined;
result = undefined;
}
}
return result;
};
export const retrieveAllAccountsMetadata = async (): Promise<Account[]> => {
// one of the few times we use accountsDBPromise directly; try to avoid more usage
const accountsDB = await accountsDBPromise;
const array = await accountsDB.accounts.toArray();
return array.map((account) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { identity, mnemonic, ...metadata } = account;
return metadata;
});
};
/**
* This contains sensitive data. If possible, use retrieveAccountMetadata instead.
*
* @param activeDid
* @returns account info with private key data decrypted
*/
export const retrieveFullyDecryptedAccount = async (
activeDid: string,
): Promise<AccountKeyInfo | undefined> => {
): Promise<Account | undefined> => {
let result: Account | undefined = undefined;
const platformService = PlatformServiceFactory.getInstance();
const dbSecrets = await platformService.dbQuery(
`SELECT secretBase64 from secret`,
);
if (
!dbSecrets ||
dbSecrets.values.length === 0 ||
dbSecrets.values[0].length === 0
) {
throw new Error(
"No secret found. We recommend you clear your data and start over.",
);
}
const secretBase64 = dbSecrets.values[0][0] as string;
const secret = base64ToArrayBuffer(secretBase64);
const dbAccount = await platformService.dbQuery(
`SELECT * FROM accounts WHERE did = ?`,
[activeDid],
);
if (
!dbAccount ||
dbAccount.values.length === 0 ||
dbAccount.values[0].length === 0
) {
throw new Error("Account not found.");
}
const fullAccountData = databaseUtil.mapQueryResultToValues(
dbAccount,
)[0] as AccountEncrypted;
const identityEncr = base64ToArrayBuffer(fullAccountData.identityEncrBase64);
const mnemonicEncr = base64ToArrayBuffer(fullAccountData.mnemonicEncrBase64);
fullAccountData.identity = await simpleDecrypt(identityEncr, secret);
fullAccountData.mnemonic = await simpleDecrypt(mnemonicEncr, secret);
result = fullAccountData;
if (USE_DEXIE_DB) {
// one of the few times we use accountsDBPromise directly; try to avoid more usage
const accountsDB = await accountsDBPromise;
const account = (await accountsDB.accounts
.where("did")
.equals(activeDid)
.first()) as Account;
return account;
result = account;
}
return result;
};
// let's try and eliminate this
export const retrieveAllFullyDecryptedAccounts = async (): Promise<
Array<AccountKeyInfo>
> => {
export const retrieveAllAccountsMetadata = async (): Promise<Account[]> => {
const platformService = PlatformServiceFactory.getInstance();
const dbAccounts = await platformService.dbQuery(`SELECT * FROM accounts`);
const accounts = databaseUtil.mapQueryResultToValues(dbAccounts) as Account[];
let result = accounts.map((account) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { identity, mnemonic, ...metadata } = account;
return metadata as Account;
});
if (USE_DEXIE_DB) {
// one of the few times we use accountsDBPromise directly; try to avoid more usage
const accountsDB = await accountsDBPromise;
const allAccounts = await accountsDB.accounts.toArray();
return allAccounts;
const array = await accountsDB.accounts.toArray();
result = array.map((account) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { identity, mnemonic, ...metadata } = account;
return metadata as Account;
});
}
return result;
};
/**
* Generates a new identity, saves it to the database, and sets it as the active identity.
* @return {Promise<string>} with the DID of the new identity
* Saves a new identity to both SQL and Dexie databases
*/
export const generateSaveAndActivateIdentity = async (): Promise<string> => {
const mnemonic = generateSeed();
// address is 0x... ETH address, without "did:eth:"
const [address, privateHex, publicHex, derivationPath] =
deriveAddress(mnemonic);
const newId = newIdentifier(address, publicHex, privateHex, derivationPath);
const identity = JSON.stringify(newId);
export async function saveNewIdentity(
identity: string,
mnemonic: string,
newId: { did: string; keys: Array<{ publicKeyHex: string }> },
derivationPath: string,
): Promise<void> {
try {
// add to the new sql db
const platformService = PlatformServiceFactory.getInstance();
const secrets = await platformService.dbQuery(
`SELECT secretBase64 FROM secret`,
);
if (!secrets?.values?.length || !secrets.values[0]?.length) {
throw new Error(
"No initial encryption supported. We recommend you clear your data and start over.",
);
}
const secretBase64 = secrets.values[0][0] as string;
const secret = base64ToArrayBuffer(secretBase64);
const encryptedIdentity = await simpleEncrypt(identity, secret);
const encryptedMnemonic = await simpleEncrypt(mnemonic, secret);
const encryptedIdentityBase64 = arrayBufferToBase64(encryptedIdentity);
const encryptedMnemonicBase64 = arrayBufferToBase64(encryptedMnemonic);
await platformService.dbExec(
`INSERT INTO accounts (dateCreated, derivationPath, did, identityEncrBase64, mnemonicEncrBase64, publicKeyHex)
VALUES (?, ?, ?, ?, ?, ?)`,
[
new Date().toISOString(),
derivationPath,
newId.did,
encryptedIdentityBase64,
encryptedMnemonicBase64,
newId.keys[0].publicKeyHex,
],
);
await databaseUtil.updateDefaultSettings({ activeDid: newId.did });
if (USE_DEXIE_DB) {
// one of the few times we use accountsDBPromise directly; try to avoid more usage
try {
const accountsDB = await accountsDBPromise;
await accountsDB.accounts.add({
dateCreated: new Date().toISOString(),
@ -549,13 +682,34 @@ export const generateSaveAndActivateIdentity = async (): Promise<string> => {
mnemonic: mnemonic,
publicKeyHex: newId.keys[0].publicKeyHex,
});
await updateDefaultSettings({ activeDid: newId.did });
}
} catch (error) {
console.error("Failed to update default settings:", error);
throw new Error("Failed to set default settings. Please try again or restart the app.");
logger.error("Failed to update default settings:", error);
throw new Error(
"Failed to set default settings. Please try again or restart the app.",
);
}
}
/**
* Generates a new identity, saves it to the database, and sets it as the active identity.
* @return {Promise<string>} with the DID of the new identity
*/
export const generateSaveAndActivateIdentity = async (): Promise<string> => {
const mnemonic = generateSeed();
// address is 0x... ETH address, without "did:eth:"
const [address, privateHex, publicHex, derivationPath] =
deriveAddress(mnemonic);
const newId = newIdentifier(address, publicHex, privateHex, derivationPath);
const identity = JSON.stringify(newId);
await saveNewIdentity(identity, mnemonic, newId, derivationPath);
await databaseUtil.updateAccountSettings(newId.did, { isRegistered: false });
if (USE_DEXIE_DB) {
await updateAccountSettings(newId.did, { isRegistered: false });
}
return newId.did;
};
@ -573,9 +727,19 @@ export const registerAndSavePasskey = async (
passkeyCredIdHex,
publicKeyHex: Buffer.from(publicKeyBytes).toString("hex"),
};
const insertStatement = databaseUtil.generateInsertStatement(
account,
"accounts",
);
await PlatformServiceFactory.getInstance().dbExec(
insertStatement.sql,
insertStatement.params,
);
if (USE_DEXIE_DB) {
// one of the few times we use accountsDBPromise directly; try to avoid more usage
const accountsDB = await accountsDBPromise;
await accountsDB.accounts.add(account);
}
return account;
};
@ -583,13 +747,22 @@ export const registerSaveAndActivatePasskey = async (
keyName: string,
): Promise<Account> => {
const account = await registerAndSavePasskey(keyName);
await databaseUtil.updateDefaultSettings({ activeDid: account.did });
await databaseUtil.updateAccountSettings(account.did, {
isRegistered: false,
});
if (USE_DEXIE_DB) {
await updateDefaultSettings({ activeDid: account.did });
await updateAccountSettings(account.did, { isRegistered: false });
}
return account;
};
export const getPasskeyExpirationSeconds = async (): Promise<number> => {
const settings = await retrieveSettingsForActiveAccount();
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
if (USE_DEXIE_DB) {
settings = await retrieveSettingsForActiveAccount();
}
return (
(settings?.passkeyExpirationMinutes ?? DEFAULT_PASSKEY_EXPIRATION_MINUTES) *
60
@ -605,7 +778,10 @@ export const sendTestThroughPushServer = async (
subscriptionJSON: PushSubscriptionJSON,
skipFilter: boolean,
): Promise<AxiosResponse> => {
const settings = await retrieveSettingsForActiveAccount();
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
if (USE_DEXIE_DB) {
settings = await retrieveSettingsForActiveAccount();
}
let pushUrl: string = DEFAULT_PUSH_SERVER as string;
if (settings?.webPushServer) {
pushUrl = settings.webPushServer;

2
src/main.capacitor.ts

@ -34,7 +34,7 @@ import router from "./router";
import { handleApiError } from "./services/api";
import { AxiosError } from "axios";
import { DeepLinkHandler } from "./services/deepLinks";
import { logConsoleAndDb } from "./db";
import { logConsoleAndDb } from "./db/databaseUtil";
import { logger } from "./utils/logger";
logger.log("[Capacitor] Starting initialization");

7
src/main.common.ts

@ -2,6 +2,7 @@ import { createPinia } from "pinia";
import { App as VueApp, ComponentPublicInstance, createApp } from "vue";
import App from "./App.vue";
import router from "./router";
// Use the browser version of axios for web builds
import axios from "axios";
import VueAxios from "vue-axios";
import Notifications from "notiwind";
@ -10,6 +11,12 @@ import { FontAwesomeIcon } from "./libs/fontawesome";
import Camera from "simple-vue-camera";
import { logger } from "./utils/logger";
const platform = process.env.VITE_PLATFORM;
const pwa_enabled = process.env.VITE_PWA_ENABLED === "true";
logger.error("Platform", { platform });
logger.error("PWA enabled", { pwa_enabled });
// Global Error Handler
function setupGlobalErrorHandler(app: VueApp) {
logger.log("[App Init] Setting up global error handler");

71
src/main.electron.ts

@ -1,4 +1,75 @@
import { initializeApp } from "./main.common";
import { logger } from "./utils/logger";
async function initializeSQLite() {
try {
// Wait for SQLite to be available in the main process
let retries = 0;
const maxRetries = 5;
const retryDelay = 1000; // 1 second
while (retries < maxRetries) {
try {
const isAvailable = await window.CapacitorSQLite.isAvailable();
if (isAvailable) {
logger.info(
"[Electron] SQLite plugin bridge initialized successfully",
);
return true;
}
} catch (error) {
logger.warn(
`[Electron] SQLite not available yet (attempt ${retries + 1}/${maxRetries}):`,
error,
);
}
retries++;
if (retries < maxRetries) {
await new Promise((resolve) => setTimeout(resolve, retryDelay));
}
}
throw new Error("SQLite plugin not available after maximum retries");
} catch (error) {
logger.error(
"[Electron] Failed to initialize SQLite plugin bridge:",
error,
);
throw error;
}
}
const platform = process.env.VITE_PLATFORM;
const pwa_enabled = process.env.VITE_PWA_ENABLED === "true";
logger.info("[Electron] Initializing app");
logger.info("[Electron] Platform:", { platform });
logger.info("[Electron] PWA enabled:", { pwa_enabled });
if (pwa_enabled) {
logger.warn("[Electron] PWA is enabled, but not supported in electron");
}
// Initialize app and SQLite
const app = initializeApp();
// Initialize SQLite first, then mount the app
initializeSQLite()
.then(() => {
logger.info("[Electron] SQLite initialized, mounting app...");
app.mount("#app");
})
.catch((error) => {
logger.error("[Electron] Failed to initialize app:", error);
// Show error to user
const errorDiv = document.createElement("div");
errorDiv.style.cssText =
"position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: #ffebee; color: #c62828; padding: 20px; border-radius: 4px; text-align: center; max-width: 80%;";
errorDiv.innerHTML = `
<h2>Failed to Initialize Database</h2>
<p>There was an error initializing the database. Please try restarting the application.</p>
<p>Error details: ${error.message}</p>
`;
document.body.appendChild(errorDiv);
});

215
src/main.ts

@ -1,215 +0,0 @@
import { createPinia } from "pinia";
import { App as VueApp, ComponentPublicInstance, createApp } from "vue";
import App from "./App.vue";
import "./registerServiceWorker";
import router from "./router";
import axios from "axios";
import VueAxios from "vue-axios";
import Notifications from "notiwind";
import "./assets/styles/tailwind.css";
import { library } from "@fortawesome/fontawesome-svg-core";
import {
faArrowDown,
faArrowLeft,
faArrowRight,
faArrowRotateBackward,
faArrowUpRightFromSquare,
faArrowUp,
faBan,
faBitcoinSign,
faBurst,
faCalendar,
faCamera,
faCameraRotate,
faCaretDown,
faChair,
faCheck,
faChevronDown,
faChevronLeft,
faChevronRight,
faChevronUp,
faCircle,
faCircleCheck,
faCircleInfo,
faCircleQuestion,
faCircleUser,
faClock,
faCoins,
faComment,
faCopy,
faDollar,
faEllipsis,
faEllipsisVertical,
faEnvelopeOpenText,
faEraser,
faEye,
faEyeSlash,
faFileContract,
faFileLines,
faFilter,
faFloppyDisk,
faFolderOpen,
faForward,
faGift,
faGlobe,
faHammer,
faHand,
faHandHoldingDollar,
faHandHoldingHeart,
faHouseChimney,
faImage,
faImagePortrait,
faLeftRight,
faLightbulb,
faLink,
faLocationDot,
faLongArrowAltLeft,
faLongArrowAltRight,
faMagnifyingGlass,
faMessage,
faMinus,
faPen,
faPersonCircleCheck,
faPersonCircleQuestion,
faPlus,
faQuestion,
faQrcode,
faRightFromBracket,
faRotate,
faShareNodes,
faSpinner,
faSquare,
faSquareCaretDown,
faSquareCaretUp,
faSquarePlus,
faTrashCan,
faTriangleExclamation,
faUser,
faUsers,
faXmark,
} from "@fortawesome/free-solid-svg-icons";
library.add(
faArrowDown,
faArrowLeft,
faArrowRight,
faArrowRotateBackward,
faArrowUpRightFromSquare,
faArrowUp,
faBan,
faBitcoinSign,
faBurst,
faCalendar,
faCamera,
faCameraRotate,
faCaretDown,
faChair,
faCheck,
faChevronDown,
faChevronLeft,
faChevronRight,
faChevronUp,
faCircle,
faCircleCheck,
faCircleInfo,
faCircleQuestion,
faCircleUser,
faClock,
faCoins,
faComment,
faCopy,
faDollar,
faEllipsis,
faEllipsisVertical,
faEnvelopeOpenText,
faEraser,
faEye,
faEyeSlash,
faFileContract,
faFileLines,
faFilter,
faFloppyDisk,
faFolderOpen,
faForward,
faGift,
faGlobe,
faHammer,
faHand,
faHandHoldingDollar,
faHandHoldingHeart,
faHouseChimney,
faImage,
faImagePortrait,
faLeftRight,
faLightbulb,
faLink,
faLocationDot,
faLongArrowAltLeft,
faLongArrowAltRight,
faMagnifyingGlass,
faMessage,
faMinus,
faPen,
faPersonCircleCheck,
faPersonCircleQuestion,
faPlus,
faQrcode,
faQuestion,
faRotate,
faRightFromBracket,
faShareNodes,
faSpinner,
faSquare,
faSquareCaretDown,
faSquareCaretUp,
faSquarePlus,
faTrashCan,
faTriangleExclamation,
faUser,
faUsers,
faXmark,
);
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import Camera from "simple-vue-camera";
import { logger } from "./utils/logger";
// Can trigger this with a 'throw' inside some top-level function, eg. on the HomeView
function setupGlobalErrorHandler(app: VueApp) {
// @ts-expect-error 'cause we cannot see why config is not defined
app.config.errorHandler = (
err: Error,
instance: ComponentPublicInstance | null,
info: string,
) => {
logger.error(
"Ouch! Global Error Handler.",
"Error:",
err,
"- Error toString:",
err.toString(),
"- Info:",
info,
"- Instance:",
instance,
);
// Want to show a nice notiwind notification but can't figure out how.
alert(
(err.message || "Something bad happened") +
" - Try reloading or restarting the app.",
);
};
}
const app = createApp(App)
.component("fa", FontAwesomeIcon)
.component("camera", Camera)
.use(createPinia())
.use(VueAxios, axios)
.use(router)
.use(Notifications);
setupGlobalErrorHandler(app);
app.mount("#app");

34
src/main.web.ts

@ -1,5 +1,37 @@
import { initBackend } from "absurd-sql/dist/indexeddb-main-thread";
import { initializeApp } from "./main.common";
import "./registerServiceWorker"; // Web PWA support
import { logger } from "./utils/logger";
const platform = process.env.VITE_PLATFORM;
const pwa_enabled = process.env.VITE_PWA_ENABLED === "true";
logger.error("[Web] PWA enabled", { pwa_enabled });
logger.error("[Web] Platform", { platform });
// Only import service worker for web builds
if (platform !== "electron" && pwa_enabled) {
import("./registerServiceWorker"); // Web PWA support
}
const app = initializeApp();
function sqlInit() {
// see https://github.com/jlongster/absurd-sql
const worker = new Worker(
new URL("./registerSQLWorker.js", import.meta.url),
{
type: "module",
},
);
// This is only required because Safari doesn't support nested
// workers. This installs a handler that will proxy creating web
// workers through the main thread
initBackend(worker);
}
if (platform === "web" || platform === "development") {
sqlInit();
} else {
logger.info("[Web] SQL not initialized for platform", { platform });
}
app.mount("#app");

6
src/registerSQLWorker.js

@ -0,0 +1,6 @@
import databaseService from "./services/AbsurdSqlDatabaseService";
async function run() {
await databaseService.initialize();
}
run();

20
src/registerServiceWorker.ts

@ -2,8 +2,18 @@
import { register } from "register-service-worker";
// Only register service worker if explicitly enabled and in production
// Check if we're in an Electron environment
const isElectron =
process.env.VITE_PLATFORM === "electron" ||
process.env.VITE_DISABLE_PWA === "true" ||
window.navigator.userAgent.toLowerCase().includes("electron");
// Only register service worker if:
// 1. Not in Electron
// 2. PWA is explicitly enabled
// 3. In production mode
if (
!isElectron &&
process.env.VITE_PWA_ENABLED === "true" &&
process.env.NODE_ENV === "production"
) {
@ -34,6 +44,12 @@ if (
});
} else {
console.log(
"Service worker registration skipped - not enabled or not in production",
`Service worker registration skipped - ${
isElectron
? "running in Electron"
: process.env.VITE_PWA_ENABLED !== "true"
? "PWA not enabled"
: "not in production mode"
}`,
);
}

25
src/router/index.ts

@ -2,35 +2,11 @@ import {
createRouter,
createWebHistory,
createMemoryHistory,
NavigationGuardNext,
RouteLocationNormalized,
RouteRecordRaw,
} from "vue-router";
import { accountsDBPromise } from "../db/index";
import { logger } from "../utils/logger";
/**
*
* @param to :RouteLocationNormalized
* @param from :RouteLocationNormalized
* @param next :NavigationGuardNext
*/
const enterOrStart = async (
to: RouteLocationNormalized,
from: RouteLocationNormalized,
next: NavigationGuardNext,
) => {
// one of the few times we use accountsDBPromise directly; try to avoid more usage
const accountsDB = await accountsDBPromise;
const num_accounts = await accountsDB.accounts.count();
if (num_accounts > 0) {
next();
} else {
next({ name: "start" });
}
};
const routes: Array<RouteRecordRaw> = [
{
path: "/account",
@ -216,7 +192,6 @@ const routes: Array<RouteRecordRaw> = [
path: "/projects",
name: "projects",
component: () => import("../views/ProjectsView.vue"),
beforeEnter: enterOrStart,
},
{
path: "/quick-action-bvc",

29
src/services/AbsurdSqlDatabaseService.d.ts

@ -0,0 +1,29 @@
import { DatabaseService } from "../interfaces/database";
declare module "@jlongster/sql.js" {
interface SQL {
Database: unknown;
FS: unknown;
register_for_idb: (fs: unknown) => void;
}
function initSqlJs(config: {
locateFile: (file: string) => string;
}): Promise<SQL>;
export default initSqlJs;
}
declare module "absurd-sql" {
export class SQLiteFS {
constructor(fs: unknown, backend: unknown);
}
}
declare module "absurd-sql/dist/indexeddb-backend" {
export default class IndexedDBBackend {
constructor();
}
}
declare const databaseService: DatabaseService;
export default databaseService;

243
src/services/AbsurdSqlDatabaseService.ts

@ -0,0 +1,243 @@
import initSqlJs from "@jlongster/sql.js";
import { SQLiteFS } from "absurd-sql";
import IndexedDBBackend from "absurd-sql/dist/indexeddb-backend";
import { runMigrations } from "../db-sql/migration";
import type { DatabaseService, QueryExecResult } from "../interfaces/database";
import { logger } from "@/utils/logger";
interface QueuedOperation {
type: "run" | "query" | "getOneRow" | "getAll";
sql: string;
params: unknown[];
resolve: (value: unknown) => void;
reject: (reason: unknown) => void;
}
interface AbsurdSqlDatabase {
exec: (sql: string, params?: unknown[]) => Promise<QueryExecResult[]>;
run: (
sql: string,
params?: unknown[],
) => Promise<{ changes: number; lastId?: number }>;
}
class AbsurdSqlDatabaseService implements DatabaseService {
private static instance: AbsurdSqlDatabaseService | null = null;
private db: AbsurdSqlDatabase | null;
private initialized: boolean;
private initializationPromise: Promise<void> | null = null;
private operationQueue: Array<QueuedOperation> = [];
private isProcessingQueue: boolean = false;
private constructor() {
this.db = null;
this.initialized = false;
}
static getInstance(): AbsurdSqlDatabaseService {
if (!AbsurdSqlDatabaseService.instance) {
AbsurdSqlDatabaseService.instance = new AbsurdSqlDatabaseService();
}
return AbsurdSqlDatabaseService.instance;
}
async initialize(): Promise<void> {
// If already initialized, return immediately
if (this.initialized) {
return;
}
// If initialization is in progress, wait for it
if (this.initializationPromise) {
return this.initializationPromise;
}
// Start initialization
this.initializationPromise = this._initialize();
try {
await this.initializationPromise;
} catch (error) {
logger.error(`AbsurdSqlDatabaseService initialize method failed:`, error);
this.initializationPromise = null; // Reset on failure
throw error;
}
}
private async _initialize(): Promise<void> {
if (this.initialized) {
return;
}
const SQL = await initSqlJs({
locateFile: (file: string) => {
return new URL(
`/node_modules/@jlongster/sql.js/dist/${file}`,
import.meta.url,
).href;
},
});
const sqlFS = new SQLiteFS(SQL.FS, new IndexedDBBackend());
SQL.register_for_idb(sqlFS);
SQL.FS.mkdir("/sql");
SQL.FS.mount(sqlFS, {}, "/sql");
const path = "/sql/timesafari.absurd-sql";
if (typeof SharedArrayBuffer === "undefined") {
const stream = SQL.FS.open(path, "a+");
await stream.node.contents.readIfFallback();
SQL.FS.close(stream);
}
this.db = new SQL.Database(path, { filename: true });
if (!this.db) {
throw new Error(
"The database initialization failed. We recommend you restart or reinstall.",
);
}
// An error is thrown without this pragma: "File has invalid page size. (the first block of a new file must be written first)"
await this.db.exec(`PRAGMA journal_mode=MEMORY;`);
const sqlExec = this.db.exec.bind(this.db);
// Run migrations
await runMigrations(sqlExec);
this.initialized = true;
// Start processing the queue after initialization
this.processQueue();
}
private async processQueue(): Promise<void> {
if (this.isProcessingQueue || !this.initialized || !this.db) {
return;
}
this.isProcessingQueue = true;
while (this.operationQueue.length > 0) {
const operation = this.operationQueue.shift();
if (!operation) continue;
try {
let queryResult: QueryExecResult[] = [];
let result: unknown;
switch (operation.type) {
case "run":
result = await this.db.run(operation.sql, operation.params);
break;
case "query":
result = await this.db.exec(operation.sql, operation.params);
break;
case "getOneRow":
queryResult = await this.db.exec(operation.sql, operation.params);
result = queryResult[0]?.values[0];
break;
case "getAll":
queryResult = await this.db.exec(operation.sql, operation.params);
result = queryResult[0]?.values || [];
break;
}
operation.resolve(result);
} catch (error) {
logger.error(
"Error while processing SQL queue:",
error,
" ... for sql:",
operation.sql,
" ... with params:",
operation.params,
);
operation.reject(error);
}
}
this.isProcessingQueue = false;
}
private async queueOperation<R>(
type: QueuedOperation["type"],
sql: string,
params: unknown[] = [],
): Promise<R> {
return new Promise<R>((resolve, reject) => {
const operation: QueuedOperation = {
type,
sql,
params,
resolve: (value: unknown) => resolve(value as R),
reject,
};
this.operationQueue.push(operation);
// If we're already initialized, start processing the queue
if (this.initialized && this.db) {
this.processQueue();
}
});
}
private async waitForInitialization(): Promise<void> {
// If we have an initialization promise, wait for it
if (this.initializationPromise) {
await this.initializationPromise;
return;
}
// If not initialized and no promise, start initialization
if (!this.initialized) {
await this.initialize();
return;
}
// If initialized but no db, something went wrong
if (!this.db) {
logger.error(
`Database not properly initialized after await waitForInitialization() - initialized flag is true but db is null`,
);
throw new Error(
`The database could not be initialized. We recommend you restart or reinstall.`,
);
}
}
// Used for inserts, updates, and deletes
async run(
sql: string,
params: unknown[] = [],
): Promise<{ changes: number; lastId?: number }> {
await this.waitForInitialization();
return this.queueOperation<{ changes: number; lastId?: number }>(
"run",
sql,
params,
);
}
// Note that the resulting array may be empty if there are no results from the query
async query(sql: string, params: unknown[] = []): Promise<QueryExecResult[]> {
await this.waitForInitialization();
return this.queueOperation<QueryExecResult[]>("query", sql, params);
}
async getOneRow(
sql: string,
params: unknown[] = [],
): Promise<unknown[] | undefined> {
await this.waitForInitialization();
return this.queueOperation<unknown[] | undefined>("getOneRow", sql, params);
}
async getAll(sql: string, params: unknown[] = []): Promise<unknown[][]> {
await this.waitForInitialization();
return this.queueOperation<unknown[][]>("getAll", sql, params);
}
}
// Create a singleton instance
const databaseService = AbsurdSqlDatabaseService.getInstance();
export default databaseService;

24
src/services/PlatformService.ts

@ -1,3 +1,5 @@
import { QueryExecResult } from "@/interfaces/database";
/**
* Represents the result of an image capture or selection operation.
* Contains both the image data as a Blob and the associated filename.
@ -98,4 +100,26 @@ export interface PlatformService {
* @returns Promise that resolves when the deep link has been handled
*/
handleDeepLink(url: string): Promise<void>;
/**
* Executes a SQL query on the database.
* @param sql - The SQL query to execute
* @param params - The parameters to pass to the query
* @returns Promise resolving to the query result
*/
dbQuery(
sql: string,
params?: unknown[],
): Promise<QueryExecResult | undefined>;
/**
* Executes a create/update/delete on the database.
* @param sql - The SQL statement to execute
* @param params - The parameters to pass to the statement
* @returns Promise resolving to the result of the statement
*/
dbExec(
sql: string,
params?: unknown[],
): Promise<{ changes: number; lastId?: number }>;
}

41
src/services/QRScanner/CapacitorQRScanner.ts

@ -4,7 +4,13 @@ import {
StartScanOptions,
LensFacing,
} from "@capacitor-mlkit/barcode-scanning";
import { QRScannerService, ScanListener, QRScannerOptions } from "./types";
import {
QRScannerService,
ScanListener,
QRScannerOptions,
CameraStateListener,
CameraState,
} from "./types";
import { logger } from "@/utils/logger";
export class CapacitorQRScanner implements QRScannerService {
@ -12,6 +18,9 @@ export class CapacitorQRScanner implements QRScannerService {
private isScanning = false;
private listenerHandles: Array<() => Promise<void>> = [];
private cleanupPromise: Promise<void> | null = null;
private cameraStateListeners: Set<CameraStateListener> = new Set();
private currentState: CameraState = "off";
private currentStateMessage?: string;
async checkPermissions(): Promise<boolean> {
try {
@ -79,8 +88,11 @@ export class CapacitorQRScanner implements QRScannerService {
}
try {
this.updateCameraState("initializing", "Starting camera...");
// Ensure we have permissions before starting
if (!(await this.checkPermissions())) {
this.updateCameraState("permission_denied", "Camera permission denied");
logger.debug("Requesting camera permissions");
const granted = await this.requestPermissions();
if (!granted) {
@ -90,11 +102,16 @@ export class CapacitorQRScanner implements QRScannerService {
// Check if scanning is supported
if (!(await this.isSupported())) {
this.updateCameraState(
"error",
"QR scanning not supported on this device",
);
throw new Error("QR scanning not supported on this device");
}
logger.info("Starting MLKit scanner");
this.isScanning = true;
this.updateCameraState("active", "Camera is active");
const scanOptions: StartScanOptions = {
formats: [BarcodeFormat.QrCode],
@ -126,6 +143,7 @@ export class CapacitorQRScanner implements QRScannerService {
stack: wrappedError.stack,
});
this.isScanning = false;
this.updateCameraState("error", wrappedError.message);
await this.cleanup();
this.scanListener?.onError?.(wrappedError);
throw wrappedError;
@ -140,6 +158,7 @@ export class CapacitorQRScanner implements QRScannerService {
try {
logger.debug("Stopping QR scanner");
this.updateCameraState("off", "Camera stopped");
await BarcodeScanner.stopScan();
logger.info("QR scanner stopped successfully");
} catch (error) {
@ -149,6 +168,7 @@ export class CapacitorQRScanner implements QRScannerService {
error: wrappedError.message,
stack: wrappedError.stack,
});
this.updateCameraState("error", wrappedError.message);
this.scanListener?.onError?.(wrappedError);
throw wrappedError;
} finally {
@ -207,4 +227,23 @@ export class CapacitorQRScanner implements QRScannerService {
// No-op for native scanner
callback(null);
}
addCameraStateListener(listener: CameraStateListener): void {
this.cameraStateListeners.add(listener);
// Immediately notify the new listener of current state
listener.onStateChange(this.currentState, this.currentStateMessage);
}
removeCameraStateListener(listener: CameraStateListener): void {
this.cameraStateListeners.delete(listener);
}
private updateCameraState(state: CameraState, message?: string): void {
this.currentState = state;
this.currentStateMessage = message;
// Notify all listeners of state change
for (const listener of this.cameraStateListeners) {
listener.onStateChange(state, message);
}
}
}

29
src/services/QRScanner/WebInlineQRScanner.ts

@ -30,14 +30,16 @@ export class WebInlineQRScanner implements QRScannerService {
private cameraStateListeners: Set<CameraStateListener> = new Set();
private currentState: CameraState = "off";
private currentStateMessage?: string;
private options: QRScannerOptions;
constructor(private options?: QRScannerOptions) {
constructor(options?: QRScannerOptions) {
// Generate a short random ID for this scanner instance
this.id = Math.random().toString(36).substring(2, 8).toUpperCase();
this.options = options ?? {};
logger.error(
`[WebInlineQRScanner:${this.id}] Initializing scanner with options:`,
{
...options,
...this.options,
buildId: BUILD_ID,
targetFps: this.TARGET_FPS,
},
@ -494,26 +496,34 @@ export class WebInlineQRScanner implements QRScannerService {
}
}
async startScan(): Promise<void> {
async startScan(options?: QRScannerOptions): Promise<void> {
if (this.isScanning) {
logger.error(`[WebInlineQRScanner:${this.id}] Scanner already running`);
return;
}
// Update options if provided
if (options) {
this.options = { ...this.options, ...options };
}
try {
this.isScanning = true;
this.scanAttempts = 0;
this.lastScanTime = Date.now();
this.updateCameraState("initializing", "Starting camera...");
logger.error(`[WebInlineQRScanner:${this.id}] Starting scan`);
logger.error(
`[WebInlineQRScanner:${this.id}] Starting scan with options:`,
this.options,
);
// Get camera stream
// Get camera stream with options
logger.error(
`[WebInlineQRScanner:${this.id}] Requesting camera stream...`,
);
this.stream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: "environment",
facingMode: this.options.camera === "front" ? "user" : "environment",
width: { ideal: 1280 },
height: { ideal: 720 },
},
@ -527,11 +537,18 @@ export class WebInlineQRScanner implements QRScannerService {
label: t.label,
readyState: t.readyState,
})),
options: this.options,
});
// Set up video element
if (this.video) {
this.video.srcObject = this.stream;
// Only show preview if showPreview is true
if (this.options.showPreview) {
this.video.style.display = "block";
} else {
this.video.style.display = "none";
}
await this.video.play();
logger.error(
`[WebInlineQRScanner:${this.id}] Video element started playing`,

116
src/services/database/ConnectionPool.ts

@ -0,0 +1,116 @@
import { logger } from "../../utils/logger";
import { SQLiteDBConnection } from "@capacitor-community/sqlite";
interface ConnectionState {
connection: SQLiteDBConnection;
lastUsed: number;
inUse: boolean;
}
export class DatabaseConnectionPool {
private static instance: DatabaseConnectionPool | null = null;
private connections: Map<string, ConnectionState> = new Map();
private readonly MAX_CONNECTIONS = 1; // We only need one connection for SQLite
private readonly MAX_IDLE_TIME = 5 * 60 * 1000; // 5 minutes
private readonly CLEANUP_INTERVAL = 60 * 1000; // 1 minute
private cleanupInterval: NodeJS.Timeout | null = null;
private constructor() {
// Start cleanup interval
this.cleanupInterval = setInterval(() => this.cleanup(), this.CLEANUP_INTERVAL);
}
public static getInstance(): DatabaseConnectionPool {
if (!DatabaseConnectionPool.instance) {
DatabaseConnectionPool.instance = new DatabaseConnectionPool();
}
return DatabaseConnectionPool.instance;
}
public async getConnection(
dbName: string,
createConnection: () => Promise<SQLiteDBConnection>
): Promise<SQLiteDBConnection> {
// Check if we have an existing connection
const existing = this.connections.get(dbName);
if (existing && !existing.inUse) {
existing.inUse = true;
existing.lastUsed = Date.now();
logger.debug(`[ConnectionPool] Reusing existing connection for ${dbName}`);
return existing.connection;
}
// If we have too many connections, wait for one to be released
if (this.connections.size >= this.MAX_CONNECTIONS) {
logger.debug(`[ConnectionPool] Waiting for connection to be released...`);
await this.waitForConnection();
}
// Create new connection
try {
const connection = await createConnection();
this.connections.set(dbName, {
connection,
lastUsed: Date.now(),
inUse: true
});
logger.debug(`[ConnectionPool] Created new connection for ${dbName}`);
return connection;
} catch (error) {
logger.error(`[ConnectionPool] Failed to create connection for ${dbName}:`, error);
throw error;
}
}
public async releaseConnection(dbName: string): Promise<void> {
const connection = this.connections.get(dbName);
if (connection) {
connection.inUse = false;
connection.lastUsed = Date.now();
logger.debug(`[ConnectionPool] Released connection for ${dbName}`);
}
}
private async waitForConnection(): Promise<void> {
return new Promise((resolve) => {
const checkInterval = setInterval(() => {
if (this.connections.size < this.MAX_CONNECTIONS) {
clearInterval(checkInterval);
resolve();
}
}, 100);
});
}
private async cleanup(): Promise<void> {
const now = Date.now();
for (const [dbName, state] of this.connections.entries()) {
if (!state.inUse && now - state.lastUsed > this.MAX_IDLE_TIME) {
try {
await state.connection.close();
this.connections.delete(dbName);
logger.debug(`[ConnectionPool] Cleaned up idle connection for ${dbName}`);
} catch (error) {
logger.warn(`[ConnectionPool] Error closing idle connection for ${dbName}:`, error);
}
}
}
}
public async closeAll(): Promise<void> {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval);
this.cleanupInterval = null;
}
for (const [dbName, state] of this.connections.entries()) {
try {
await state.connection.close();
logger.debug(`[ConnectionPool] Closed connection for ${dbName}`);
} catch (error) {
logger.warn(`[ConnectionPool] Error closing connection for ${dbName}:`, error);
}
}
this.connections.clear();
}
}

19
src/services/deepLinks.ts

@ -52,7 +52,7 @@ import {
routeSchema,
DeepLinkRoute,
} from "../interfaces/deepLinks";
import { logConsoleAndDb } from "../db";
import { logConsoleAndDb } from "../db/databaseUtil";
import type { DeepLinkError } from "../interfaces/deepLinks";
/**
@ -119,6 +119,15 @@ export class DeepLinkHandler {
const [path, queryString] = parts[1].split("?");
const [routePath, param] = path.split("/");
// Validate route exists before proceeding
if (!this.ROUTE_MAP[routePath]) {
throw {
code: "INVALID_ROUTE",
message: `Invalid route path: ${routePath}`,
details: { routePath },
};
}
const query: Record<string, string> = {};
if (queryString) {
new URLSearchParams(queryString).forEach((value, key) => {
@ -128,11 +137,9 @@ export class DeepLinkHandler {
const params: Record<string, string> = {};
if (param) {
if (this.ROUTE_MAP[routePath].paramKey) {
params[this.ROUTE_MAP[routePath].paramKey] = param;
} else {
params["id"] = param;
}
// Now we know routePath exists in ROUTE_MAP
const routeConfig = this.ROUTE_MAP[routePath];
params[routeConfig.paramKey ?? "id"] = param;
}
return { path: routePath, params, query };
}

67
src/services/migrationService.ts

@ -0,0 +1,67 @@
import { logger } from "@/utils/logger";
import { QueryExecResult } from "../interfaces/database";
interface Migration {
name: string;
sql: string;
}
export class MigrationService {
private static instance: MigrationService;
private migrations: Migration[] = [];
private constructor() {}
static getInstance(): MigrationService {
if (!MigrationService.instance) {
MigrationService.instance = new MigrationService();
}
return MigrationService.instance;
}
async registerMigration(migration: Migration): Promise<void> {
this.migrations.push(migration);
}
async runMigrations(
sqlExec: (
sql: string,
params?: unknown[],
) => Promise<Array<QueryExecResult>>,
): Promise<void> {
// Create migrations table if it doesn't exist
await sqlExec(`
CREATE TABLE IF NOT EXISTS migrations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
`);
// Get list of executed migrations
const result: QueryExecResult[] = await sqlExec(
"SELECT name FROM migrations;",
);
let executedMigrations: Set<unknown> = new Set();
// Even with that query, the QueryExecResult may be [] (which doesn't make sense to me).
if (result.length > 0) {
const singleResult = result[0];
executedMigrations = new Set(
singleResult.values.map((row: unknown[]) => row[0]),
);
}
// Run pending migrations in order
for (const migration of this.migrations) {
if (!executedMigrations.has(migration.name)) {
await sqlExec(migration.sql);
await sqlExec("INSERT INTO migrations (name) VALUES (?)", [
migration.name,
]);
logger.log(`Migration ${migration.name} executed successfully`);
}
}
}
}
export default MigrationService.getInstance();

230
src/services/platforms/CapacitorPlatformService.ts

@ -6,7 +6,20 @@ import {
import { Filesystem, Directory, Encoding } from "@capacitor/filesystem";
import { Camera, CameraResultType, CameraSource } from "@capacitor/camera";
import { Share } from "@capacitor/share";
import {
SQLiteConnection,
SQLiteDBConnection,
CapacitorSQLite,
Changes,
} from "@capacitor-community/sqlite";
import { logger } from "../../utils/logger";
import { QueryExecResult, SqlValue } from "@/interfaces/database";
import { DEFAULT_ENDORSER_API_SERVER } from "@/constants/app";
interface Migration {
name: string;
sql: string;
}
/**
* Platform service implementation for Capacitor (mobile) platform.
@ -14,8 +27,168 @@ import { logger } from "../../utils/logger";
* - File system operations
* - Camera and image picker
* - Platform-specific features
* - SQLite database operations
*/
export class CapacitorPlatformService implements PlatformService {
private sqlite: SQLiteConnection;
private db: SQLiteDBConnection | null = null;
private dbName = "timesafari.db";
private initialized = false;
constructor() {
this.sqlite = new SQLiteConnection(CapacitorSQLite);
}
private async initializeDatabase(): Promise<void> {
if (this.initialized) {
return;
}
try {
// Create/Open database
this.db = await this.sqlite.createConnection(
this.dbName,
false,
"no-encryption",
1,
false,
);
await this.db.open();
// Set journal mode to WAL for better performance
await this.db.execute("PRAGMA journal_mode=WAL;");
// Run migrations
await this.runMigrations();
this.initialized = true;
logger.log("SQLite database initialized successfully");
} catch (error) {
logger.error("Error initializing SQLite database:", error);
throw new Error("Failed to initialize database");
}
}
private async runMigrations(): Promise<void> {
if (!this.db) {
throw new Error("Database not initialized");
}
// Create migrations table if it doesn't exist
await this.db.execute(`
CREATE TABLE IF NOT EXISTS migrations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
`);
// Get list of executed migrations
const result = await this.db.query("SELECT name FROM migrations;");
const executedMigrations = new Set(
result.values?.map((row) => row[0]) || [],
);
// Run pending migrations in order
const migrations: Migration[] = [
{
name: "001_initial",
sql: `
CREATE TABLE IF NOT EXISTS accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
dateCreated TEXT NOT NULL,
derivationPath TEXT,
did TEXT NOT NULL,
identityEncrBase64 TEXT,
mnemonicEncrBase64 TEXT,
passkeyCredIdHex TEXT,
publicKeyHex TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_accounts_did ON accounts(did);
CREATE TABLE IF NOT EXISTS secret (
id INTEGER PRIMARY KEY AUTOINCREMENT,
secretBase64 TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS settings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
accountDid TEXT,
activeDid TEXT,
apiServer TEXT,
filterFeedByNearby BOOLEAN,
filterFeedByVisible BOOLEAN,
finishedOnboarding BOOLEAN,
firstName TEXT,
hideRegisterPromptOnNewContact BOOLEAN,
isRegistered BOOLEAN,
lastName TEXT,
lastAckedOfferToUserJwtId TEXT,
lastAckedOfferToUserProjectsJwtId TEXT,
lastNotifiedClaimId TEXT,
lastViewedClaimId TEXT,
notifyingNewActivityTime TEXT,
notifyingReminderMessage TEXT,
notifyingReminderTime TEXT,
partnerApiServer TEXT,
passkeyExpirationMinutes INTEGER,
profileImageUrl TEXT,
searchBoxes TEXT,
showContactGivesInline BOOLEAN,
showGeneralAdvanced BOOLEAN,
showShortcutBvc BOOLEAN,
vapid TEXT,
warnIfProdServer BOOLEAN,
warnIfTestServer BOOLEAN,
webPushServer TEXT
);
CREATE INDEX IF NOT EXISTS idx_settings_accountDid ON settings(accountDid);
INSERT INTO settings (id, apiServer) VALUES (1, '${DEFAULT_ENDORSER_API_SERVER}');
CREATE TABLE IF NOT EXISTS contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
did TEXT NOT NULL,
name TEXT,
contactMethods TEXT,
nextPubKeyHashB64 TEXT,
notes TEXT,
profileImageUrl TEXT,
publicKeyBase64 TEXT,
seesMe BOOLEAN,
registered BOOLEAN
);
CREATE INDEX IF NOT EXISTS idx_contacts_did ON contacts(did);
CREATE INDEX IF NOT EXISTS idx_contacts_name ON contacts(name);
CREATE TABLE IF NOT EXISTS logs (
date TEXT PRIMARY KEY,
message TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS temp (
id TEXT PRIMARY KEY,
blobB64 TEXT
);
`,
},
];
for (const migration of migrations) {
if (!executedMigrations.has(migration.name)) {
await this.db.execute(migration.sql);
await this.db.run("INSERT INTO migrations (name) VALUES (?)", [
migration.name,
]);
logger.log(`Migration ${migration.name} executed successfully`);
}
}
}
/**
* Gets the capabilities of the Capacitor platform
* @returns Platform capabilities object
@ -185,6 +358,9 @@ export class CapacitorPlatformService implements PlatformService {
*/
async writeFile(fileName: string, content: string): Promise<void> {
try {
// Check storage permissions before proceeding
await this.checkStoragePermissions();
const logData = {
targetFileName: fileName,
contentLength: content.length,
@ -326,6 +502,9 @@ export class CapacitorPlatformService implements PlatformService {
logger.log("[CapacitorPlatformService]", JSON.stringify(logData, null, 2));
try {
// Check storage permissions before proceeding
await this.checkStoragePermissions();
const { uri } = await Filesystem.writeFile({
path: fileName,
data: content,
@ -476,4 +655,55 @@ export class CapacitorPlatformService implements PlatformService {
// This is just a placeholder for the interface
return Promise.resolve();
}
/**
* @see PlatformService.dbQuery
*/
async dbQuery(sql: string, params?: unknown[]): Promise<QueryExecResult> {
await this.initializeDatabase();
if (!this.db) {
throw new Error("Database not initialized");
}
try {
const result = await this.db.query(sql, params || []);
const values = result.values || [];
return {
columns: [], // SQLite plugin doesn't provide column names in query result
values: values as SqlValue[][],
};
} catch (error) {
logger.error("Error executing query:", error);
throw new Error(
`Database query failed: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
/**
* @see PlatformService.dbExec
*/
async dbExec(
sql: string,
params?: unknown[],
): Promise<{ changes: number; lastId?: number }> {
await this.initializeDatabase();
if (!this.db) {
throw new Error("Database not initialized");
}
try {
const result = await this.db.run(sql, params || []);
const changes = result.changes as Changes;
return {
changes: changes?.changes || 0,
lastId: changes?.lastId,
};
} catch (error) {
logger.error("Error executing statement:", error);
throw new Error(
`Database execution failed: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
}

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save