docs & feat: update project plan to E2E encrypted server storage & initialize monorepo client/server codebases

This commit is contained in:
2026-05-27 21:22:02 +02:00
parent d4b3cc2d74
commit db8b454a9e
43 changed files with 10646 additions and 206 deletions
+71 -37
View File
@@ -6,14 +6,14 @@
## Component Architecture
Since this is a client-side only PWA, the entire architecture runs in the user's browser sandbox. The structure is separated into UI Components, Services (business logic), and Storage.
The application uses an offline-first PWA architecture synced with a remote database. End-to-end (E2E) encryption is managed entirely on the client, ensuring the server only receives encrypted payloads.
```
┌────────────────────────────────────────────────────────┐
│ User Interface │
│ ┌──────────────┐ ┌────────────────┐ ┌──────────────┐ │
│ │ Stammdaten │ │ Logbook Entry │ │ Settings/ │ │
│ │ (Forms, Crew)│ │ (Forms, List) │ │ Language │ │
│ │ Stammdaten │ │ Logbook Entry │ │ Auth & Logs │ │
│ │ (Forms, Crew)│ │ (Forms, List) │ │ (Passkey) │ │
│ └──────┬───────┘ └───────┬────────┘ └──────┬───────┘ │
└─────────┼─────────────────┼─────────────────┼──────────┘
│ │ │
@@ -22,67 +22,101 @@ Since this is a client-side only PWA, the entire architecture runs in the user's
│ ┌────────────────┐ ┌────────────────┐ ┌────────────┐ │
│ │ Geolocation │ │ Weather Service│ │ Export │ │
│ │ Service (GPS) │ │ (OpenWeather) │ │ Service │ │
│ └───────────────┘ └───────────────┘ └───────────┘ │
└─────────┼────────────────────────────────────────────
│ │ │
┌─────────▼───────────────────▼───────────────▼──────────┐
Data Infrastructure
│ └───────────────┘ └───────────────┘ └───────────┘ │
│ ┌────────────────┐ ┌────────────────┐ ┌────────────┐ │
│ │ WebAuthn Client│ │ E2E Cryptography│ │ Sync │ │
│ │ (Passkey Auth) │ │ (Web Crypto) │ │ Service │ │
└────────┬───────┘ └───────┬────────┘ └────┬───────┘
└───────────┼─────────────────┼───────────────┼──────────┘
│ │ │
┌───────────▼─────────────────▼───────────────▼──────────┐
│ Local Data Infrastructure │
│ ┌──────────────────────────────────────────────────┐ │
│ │ IndexedDB / Dexie.js (Data Persistence) │ │
│ │ IndexedDB / Dexie.js (Data Persistence Cache) │ │
│ └──────────────────────────────────────────────────┘ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ Service Worker (Asset Cache & Offline) │ │
│ └──────────────────────────┬───────────────────────┘ │
└─────────────────────────────┼──────────────────────────┘
│ HTTPS (Encrypted Payloads & WebAuthn JSON)
┌────────────────────────────────────────────────────────┐
│ Backend Infrastructure │
│ ┌──────────────────────────────────────────────────┐ │
│ │ Node.js Express API (WebAuthn Validation) │ │
│ └──────────────────────────┬───────────────────────┘ │
│ ┌──────────────────────────▼───────────────────────┐ │
│ │ PostgreSQL Database (Encrypted Payloads) │ │
│ └──────────────────────────────────────────────────┘ │
└────────────────────────────────────────────────────────┘
```
### 1. UI Layer
- **Responsive Layout Shell**: Single page app with a bottom navigation bar for mobile feel and sidebar for tablet/desktop. Responsive and adaptive depending on device size.
- **Form Views**:
- **Responsive Layout Shell**: Single page app with bottom navigation bar for mobile feel and sidebar for tablet/desktop. Responsive and adaptive depending on device size.
- **Form & Management Views**:
- **Auth Onboarding Panel**: Handles Passkey registration/login and generates or inputs the 12-word recovery key.
- **Logbook Dashboard**: Overview panel listing available user logbooks, option to create a new logbook, and active logbook selection.
- **Stammdaten Form**: Single tabbed view separating Boat Profile, Crew profiles, and the Deviation Table.
- **Logbook List**: Chronological display of journal entries with details and summaries.
- **Logbook Entry Form**: Interactive form with sub-sections for Nautical logs, Weather inputs, Sails, Course, and Consumption controls.
- **Adaptive UI Handler**: Standard CSS variables and OS-detection class selectors (`.platform-ios`, `.platform-android`) to render inputs and dialogs matching Cupertino or Material styles.
### 2. Services Layer
- **E2E Cryptography Service**: Uses standard Web Crypto API. Handles AES-GCM encryption/decryption of logbook payloads. Manages key derivation via PBKDF2/HKDF using WebAuthn PRF inputs or a 12-word recovery phrase.
- **WebAuthn Authentication Service**: Connects to the browser's credentials API (`navigator.credentials`) and `@simplewebauthn/browser`. Communicates registration and authentication challenges to the server.
- **Synchronization Service**: Tracks offline data mutations in a local transaction log. Resolves push/pull updates with the server API when online using conflict resolution algorithms (client-wins/last-write-wins).
- **GPS Service**: Interface to browser Geolocation API (`navigator.geolocation`). Provides DMS (Degrees, Minutes, Seconds) coordinate formatting.
- **Weather Service**: Performs asynchronous REST requests to OpenWeatherMap API using coordinates. Handles offline fallback gracefully.
- **Export Service**: Generates a CSV file using standard RFC 4180 parameters, creates a dynamic Blob URL, and triggers browser download or invokes `navigator.share` (Web Share API) for native email/message share.
- **Export Service**: Client-side decrypts entries, generates a CSV file using standard RFC 4180 parameters, creates a dynamic Blob URL, and triggers browser download or invokes `navigator.share` (Web Share API) for native email/message share.
- **Translation Service**: standard `i18next` engine. Automatically detects system locale on first start (`navigator.language`), falls back to English, and persists user selection in LocalStorage.
### 3. Data Infrastructure
- **IndexedDB Storage Scheme (Dexie.js)**:
- Table `yacht`: Single record containing vessel specs.
- Table `crew`: Skipper + Crew members.
- Table `deviation`: 37 records mapping `heading` (MgK 0-360) to `deviation` (Abl).
- Table `entries`: Logbook records containing dates, coordinates, courses, weather, sails, and daily consumption.
### 3. Local Data Infrastructure
- **IndexedDB Caching (Dexie.js)**:
- Table `yacht`: Yacht records, schema: `id, logbookId, encryptedData, updatedAt`.
- Table `crew`: Crew profiles, schema: `id, logbookId, encryptedData, updatedAt`.
- Table `deviation`: Compass deviations, schema: `id, logbookId, encryptedData, updatedAt`.
- Table `entries`: Logbook records, schema: `id, logbookId, encryptedData, updatedAt`.
- Table `logbooks`: Logbook metadata, schema: `id, encryptedTitle, updatedAt, isSynced`.
- Table `syncQueue`: Sync status tracking local pending mutations.
- **Offline Shell**: Service Worker configured using Workbox via `vite-plugin-pwa`. Caches CSS, JS, HTML, fonts, and icons for immediate load.
### 4. Backend Infrastructure
- **Node.js Server (TypeScript & Express)**:
- API Routes: `/api/auth/register-options`, `/api/auth/register-verify`, `/api/auth/login-options`, `/api/auth/login-verify`, `/api/logbooks`, `/api/sync`.
- Uses `@simplewebauthn/server` for validating Passkey cryptography.
- **PostgreSQL Database**:
- `User`: id, username, createdAt.
- `Credential`: id, userId, credentialId, publicKey, counter, transports.
- `Logbook`: id, userId, encryptedTitle, createdAt, updatedAt.
- `Payloads` (Yacht, Crew, Deviation, Entries): E2E encrypted string blobs stored by logbookId.
## Data Flow
### 1. Fetching GPS & Weather
1. User clicks "Auto-Fill GPS/Weather" on a new log entry.
2. Geolocation Service queries `navigator.geolocation.getCurrentPosition()`.
3. Coordinates are returned and set in form state.
4. If internet is available, Weather Service requests OpenWeatherMap using the coordinates.
5. API response (pressure, wind strength, direction, weather icons) is parsed and merged into the form state.
6. User reviews the pre-filled fields and saves the entry.
### 1. WebAuthn Registration and Key Derivation
1. User registers passwordlessly using their device biometric authenticator (Passkey).
2. During registration, the WebAuthn PRF extension is invoked to derive a unique symmetric key input from the hardware credential.
3. If PRF is unsupported, or as a recovery fallback, the client generates a 12-word BIP39 recovery phrase and derives a master key via PBKDF2.
4. The client generates a random 256-bit User Master Key.
5. The User Master Key is E2E-encrypted with the PRF-derived key and (separately) with the recovery-derived key.
6. The encrypted User Master Key payloads are sent to the server and stored.
7. During subsequent logins, the authenticator is used to verify identity and regenerate the PRF key. The client requests the encrypted User Master Key from the server, decrypts it locally, and stores it in memory.
### 2. Saving to Database & Local Cache
1. Form state triggers `dexie` write operation: `db.entries.add(formData)`.
2. IndexedDB saves the record locally.
3. The UI queries IndexedDB reactively using `useLiveQuery` from `dexie-react-hooks`, updating lists instantly.
4. No network requests are made, ensuring zero lag.
### 2. Encryption and Synchronization
1. User makes edits to a logbook entry locally.
2. The client fetches the User Master Key from memory, encrypts the data payload using AES-GCM (generating a IV and authentication tag), and writes it to the local IndexedDB.
3. A local mutation event is created in the `syncQueue` table.
4. The Sync Service attempts to POST the encrypted payload (`{ logbookId, payloadId, encryptedData, iv, tag, updatedAt }`) to the backend `/api/sync` endpoint.
5. The backend validates the user's session and commits the encrypted payload directly to PostgreSQL.
6. If the user is offline, the syncQueue retains the event and retries once network connectivity is restored (`navigator.onLine`).
## Suggested Build Order
1. **Setup & PWA Shell**: Initialize Vite React TS, configure `vite-plugin-pwa` with service worker, and setup simple landing shell.
2. **Database Layer**: Implement Dexie.js database schemas, collections, and mock data.
3. **Master Data View (Stammdaten)**: Implement boat profile form, crew cards, and the Deviation grid.
4. **Logbook Entry Forms**: Build the main log entry form, course inputs, and consumption controller.
5. **GPS & Weather Integrations**: Implement device Geolocation fetching and OpenWeatherMap query helpers.
6. **Data Export & Language Switcher**: Add CSV generation/sharing and `react-i18next` localization.
7. **Adaptive UI Polish**: Apply iOS/Android CSS themes and polish responsiveness.
1. **Setup & Foundations**: Initialize client Vite PWA, Express TS backend server, Prisma schema and PostgreSQL database docker/connection.
2. **Auth & Crypto Layer**: Implement Passkey registration and assertion using WebAuthn. Build Web Crypto API utilities for PRF/recovery key E2E master key decryption.
3. **Multi-Logbook & Sync**: Implement multi-logbook dashboards, switching logic, IndexedDB local cache tables, and sync queue protocols.
4. **Forms UI & Client Encryption**: Implement Yacht, Crew profiles, and Deviation grid editors that write and read encrypted data.
5. **Logbook Entries & Integrations**: Build entry forms, Geolocation GPS fetcher, and OpenWeatherMap lookup service.
6. **Decryption Export & Styling**: Implement client-side decryption CSV builder, sync indicator bars, and platform CSS adaptations.
---
*Architecture research for: Kapteins Daagbox PWA*
Regular → Executable
+14 -8
View File
@@ -21,9 +21,12 @@
- **OpenWeatherMap Integration**: Automatically query and pre-fill wind direction/strength, pressure, and weather state based on geographical coordinates.
- **GPS Coordinates Capture**: Fetch current latitude/longitude via device GPS and pre-fill coordinates into log entries.
### 4. Data Management & Privacy
- **Local Database (IndexedDB)**: Direct database queries and local storage in browser sandbox.
- **CSV Data Export**: Generate and download formatted CSV logbooks directly, or trigger local email/message sharing.
### 4. Data Management, Auth & Cryptography
- **Passkey Accounts (WebAuthn)**: Passwordless user registration and login using device authenticators (biometrics, secure keys).
- **Client-Side E2E Cryptography**: Transparent client-side AES-GCM-256 encryption. WebAuthn PRF and BIP39 recovery word helpers for zero-knowledge key derivation.
- **Multi-Logbook Manager**: Dashboard interface allowing skippers to create and switch between multiple ship logbooks under one account.
- **Offline-First Synchronization**: Sync local changes (IndexedDB cache) to remote PostgreSQL via transaction logs and delta packet exchanges, offering conflict resolution markers.
- **CSV Data Export**: Generate and download unencrypted CSV logbooks compiled on-the-fly client-side (after decrypting entries), or trigger local email/message sharing.
- **Offline Assets & Service Worker**: Cache all HTML, JS, CSS, and assets so the application runs completely disconnected.
## Feature Scoping: Table Stakes vs Differentiators
@@ -34,8 +37,11 @@
| Crew Registry | Stammdaten | Table Stake | Low | Up to 6 profiles, standard fields. |
| Logbook Form | Logbuch | Table Stake | Medium | Complex form containing wind, course, and sails. |
| Deviation Table | Stammdaten | Table Stake | Low | Grid mapping MgK to Abl. |
| CSV Export | Data | Table Stake | Medium | Client-side CSV generation and download trigger. |
| Local Storage | Data | Table Stake | Medium | IndexedDB schema setup and migration. |
| CSV Export | Data | Table Stake | Medium | Client-side decryption and CSV download trigger. |
| Passkey Auth | Auth | Table Stake | Medium | WebAuthn biometrics setup (SimpleWebAuthn). |
| E2E Cryptography | Crypto | Table Stake | High | Web Crypto API, PRF derivation & recovery fallback. |
| Sync Manager | Data | Table Stake | High | Local queue processing, background pushes, conflict management. |
| Multi-Logbook UI | UI | Table Stake | Medium | Dashboard to create, delete, and switch logbooks. |
| Offline PWA | System | Table Stake | Medium | Service Worker configuration. |
| GPS Fetching | Assistance | Differentiator | Low | HTML5 Geolocation API integration. |
| OpenWeather API | Assistance | Differentiator | Medium | Needs API key, coordinates, and fallback for offline. |
@@ -43,9 +49,9 @@
## Anti-Features (Do Not Build)
- **Cloud DB Sync**: Violates local-only privacy constraint.
- **Central User Login / Registration**: No remote accounts; the app is immediately active upon loading.
- **Remote Sharing Server**: Logbook files must be exported directly from the device (CSV download or local email handler).
- **Cleartext Server-Side Storage / Sync**: The server must never store unencrypted vessel, crew, deviation, or journal entry data.
- **Classic Username / Password Login**: Passwords introduce security risks and weak encryption bases. Enforce biometric/hardware Passkeys (WebAuthn) instead.
- **Server-Side Data Analytics**: The backend has zero visibility into user logs, avoiding tracking.
## Dependencies & Risk Analysis
Regular → Executable
+24 -1
View File
@@ -47,6 +47,29 @@
- Implement an auto-save mechanism that writes the active form draft to IndexedDB (or LocalStorage) every 10 seconds.
- On launching the logbook entry form, check if a draft exists and offer to restore it.
### 6. Passkey Authenticator Compatibility & WebAuthn Limitations
- **Problem**: Biometric hardware/WebAuthn APIs might be restricted on legacy operating systems, specific Android skins, or in private/incognito browsing windows.
- **Warning Signs**: Browser throws authentication errors or `navigator.credentials` returns undefined.
- **Prevention Strategy**:
- Check `PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()` on onboarding.
- Inform the user of browser/device capability limitations and recommend updating their system.
- Fall back cleanly to hardware USB security keys if biometrics fail.
### 7. Permanent Data Loss due to E2E Encryption Key Loss
- **Problem**: In a zero-knowledge architecture, the server does not store plaintext passwords or master keys. If the user registers a Passkey, loses their device, and loses their 12-word recovery phrase, the server cannot recover their logbooks.
- **Warning Signs**: Skipper logs out or switches devices and cannot decrypt downloaded database chunks.
- **Prevention Strategy**:
- Enforce a mandatory recovery phrase validation step (e.g. asking the user to re-enter words 3, 7, and 11) during sign-up.
- Display clear warnings in the settings dashboard about the zero-knowledge nature of the server.
### 8. Concurrent Sync Conflicts from Offline Edits
- **Problem**: Skipper modifies a logbook entry or crew member on device A (phone) and device B (tablet) while both are offline at sea. Upon re-establishing internet, conflicting updates are pushed to the server.
- **Warning Signs**: Data edits are silently overwritten or entries become duplicated/corrupted.
- **Prevention Strategy**:
- Use atomic delta packages containing object timestamps.
- Apply Last-Write-Wins (LWW) strategy on standard field updates based on local timestamps.
- For journal entry splits, append logs chronologically instead of overwriting, and flag conflict states to the user for manual merge.
---
*Pitfalls research for: Kapteins Daagbox PWA*
*Researched: 2026-05-26*
*Researched: 2026-05-26 (Updated 2026-05-27)*
Regular → Executable
+23 -13
View File
@@ -13,9 +13,12 @@ We recommend a **React + TypeScript + Vite** stack wrapped with **vite-plugin-pw
| Technology | Version | Purpose | Why Recommended |
|------------|---------|---------|-----------------|
| **React** | 18.x / 19.x | UI Library | Component-driven architecture allows building a modular, reactive UI that easily handles state transitions for logbook forms. |
| **TypeScript** | 5.x | Language | Enforces strict type safety across logbook entries and crew models, preventing runtime errors. |
| **Vite** | 5.x | Build Tool | Extremely fast bundler and dev server; offers direct support for PWAs via plugins. |
| **TailwindCSS** / **Vanilla CSS** | 3.x / 4.x | Styling | Allows responsive, adaptive styling to match Android/iOS aesthetics and handles mobile viewport constraints. |
| **TypeScript** | 5.x | Language | Enforces strict type safety across client and server. |
| **Vite** | 5.x | Build Tool | Fast client packager and Service Worker compiler. |
| **Node.js (Express)** | 20.x | Backend Server | Lightweight API backend to handle WebAuthn challenges and database storage. |
| **PostgreSQL** | 16.x | Relational DB | Robust storage of credentials and E2E-encrypted JSON payloads. |
| **Prisma** | 5.x | ORM | Type-safe SQL database client interface. |
| **TailwindCSS** / **Vanilla CSS** | 3.x / 4.x | Styling | Responsive styling matching iOS/Android. |
### Supporting Libraries
@@ -23,7 +26,10 @@ We recommend a **React + TypeScript + Vite** stack wrapped with **vite-plugin-pw
|---------|---------|---------|-------------|
| **Dexie.js** | 4.x | IndexedDB Wrapper | Required for robust, structured offline-first storage of ship data and log entries. |
| **vite-plugin-pwa** | 0.20.x | PWA / Service Worker | Handles automatic service worker registration, offline caching of assets, and install prompts. |
| **react-i18next** | 14.x | Multilingual (l18n) | Seamless translation management for German and English with automatic language detection. |
| **react-i18next** | 14.x | Multilingual (l18n) | Seamless translation management for German and English. |
| **@simplewebauthn/server** | 9.x / 10.x | Passkey Verification | Validates WebAuthn registration/login assertions on the server. |
| **@simplewebauthn/browser** | 9.x / 10.x | Passkey Client helper | Connects WebAuthn client requests to browser credentials API. |
| **bip39** | 3.x | Recovery phrases | Generates 12-word mnemonic phrases for E2E encryption fallbacks. |
| **lucide-react** | 0.300.x | SVG Icons | Light, modern icon library for weather states, navigation, and logbook actions. |
### Development Tools
@@ -36,14 +42,18 @@ We recommend a **React + TypeScript + Vite** stack wrapped with **vite-plugin-pw
## Installation
```bash
# Core & UI
# Client Core & UI
npm install react react-dom lucide-react
# Storage, PWA & Localization
npm install dexie dexie-react-hooks react-i18next i18next i18next-browser-languagedetector
# Client Storage, PWA, Localization & Cryptography
npm install dexie dexie-react-hooks react-i18next i18next i18next-browser-languagedetector @simplewebauthn/browser bip39
# Dev Dependencies
# Client Dev Dependencies
npm install -D typescript @types/react @types/react-dom vite @vitejs/plugin-react vite-plugin-pwa
# Backend Core, ORM & Auth
npm install express dotenv cors @simplewebauthn/server @prisma/client
npm install -D tsx @types/express @types/node @types/cors prisma
```
## Alternatives Considered
@@ -57,18 +67,18 @@ npm install -D typescript @types/react @types/react-dom vite @vitejs/plugin-reac
| Avoid | Why | Use Instead |
|-------|-----|-------------|
| **Firebase / Supabase** | Requires online connection for core operations; violates "local-only" strict privacy constraint. | Dexie.js + Local IndexedDB |
| **Plain Firebase / Supabase DB Sync** | Default syncing exposes raw unencrypted database schemas to the cloud provider, violating zero-knowledge privacy. | Custom Node/Express server + E2E encrypted payloads database |
| **Bootstrap** | Heavy, outdated styling that doesn't adapt well to modern native mobile looks. | TailwindCSS / CSS variables |
## Stack Patterns by Variant
**If strict local privacy is required:**
- Use IndexedDB (via Dexie.js) for storage.
- Because IndexedDB runs entirely in the user's browser sandbox and has no cloud sync, guaranteeing absolute data ownership.
**If strict user privacy with multi-device access is required:**
- Use Client-Side E2E Encryption (AES-GCM-256) combined with Local-first IndexedDB (via Dexie.js) synced to a zero-knowledge PostgreSQL server.
- Because client-side encryption ensures the server operator only holds encrypted payloads, retaining absolute user data privacy.
**If poor connectivity is expected:**
- Configure Workbox Service Worker in "CacheFirst" or "StaleWhileRevalidate" mode.
- Because it ensures the application shell loads immediately even with 0% network connection.
- Because it ensures the application shell loads immediately even with 0% network connection, queueing synchronization packets until the device is online.
## Version Compatibility
Regular → Executable
+50 -52
View File
@@ -7,90 +7,86 @@
## Executive Summary
Kapteins Daagbox is an offline-first PWA that serves as a digital ship's logbook for private yachts. It places a primary emphasis on complete data privacy by storing all yacht, crew, and journal entries entirely local to the user's browser database (IndexedDB).
Kapteins Daagbox is an offline-first PWA synced with a zero-knowledge backend server, serving as a secure digital ship's logbook for private yachts. It guarantees data privacy via client-side End-to-End Encryption (E2E), ensuring the server only stores encrypted payloads.
The recommended approach uses **Vite + React + TypeScript + Dexie.js + TailwindCSS**, which guarantees a lightweight bundle that loads quickly on low-bandwidth mobile connections at sea. The app incorporates browser Geolocation APIs for automatic GPS coordinate capture and integrates with OpenWeatherMap for sea/weather pre-filling.
The recommended stack features a **React + TS + Vite** frontend, a **Node.js Express + Prisma + PostgreSQL** backend, **Dexie.js** for local caching, and **WebAuthn** for passwordless Passkey login. E2E key derivation uses biometric/hardware PRF input or a 12-word recovery phrase.
Key risks include data loss due to OS storage reclamation policies (particularly on iOS Safari) and API timeouts when connections fail. These are mitigated by instructing the user to install the app as a PWA on their Home Screen, enabling persistent storage APIs, and using local draft autosaving along with regular CSV backups.
Key risks include loss of client-side encryption keys (causing unrecoverable server data), browser compatibility with WebAuthn, and concurrent offline synchronization conflicts. These are mitigated by a mandatory recovery phrase verification on registration, using standard security key fallbacks, and applying Last-Write-Wins timestamps to sync packets.
## Key Findings
### Recommended Stack
We recommend React with Vite and TypeScript for fast rendering and development. [STACK.md](STACK.md) details the tools and configurations.
We recommend a React with Vite client paired with a Node.js + Express backend using Prisma and PostgreSQL. [STACK.md](STACK.md) details the configurations.
**Core technologies:**
- **React + TS + Vite**: Builds a fast, responsive mobile app compiled to lightweight static assets.
- **Dexie.js (IndexedDB)**: An asynchronous, robust client-side database with reactive binding for UI state management.
- **vite-plugin-pwa (Workbox)**: Configures offline asset caching, service worker hooks, and updates.
- **react-i18next**: Handles German/English localizations and browser language auto-detection.
- **React + TS + Vite / Node.js Express**: Full-stack TypeScript environment.
- **PostgreSQL & Prisma**: Backend storage for user credentials and encrypted payloads.
- **Dexie.js (IndexedDB)**: Client-side local transaction cache.
- **WebAuthn (@simplewebauthn)**: Passkey integration for passwordless logins.
- **Web Crypto API**: High-performance, browser-native client encryption.
### Expected Features
Detailed scoping is tracked in [FEATURES.md](FEATURES.md).
**Must have (table stakes):**
- **Vessel Profile & Crew Registry**: Stammdaten forms capturing yacht specifications and up to 6 crew records.
- **Steuertafel (Deviation table)**: Grid aligning compass headings with magnetic deviation.
- **Logbook Forms**: Rich fields capturing journey details, course, wind, sails, sea state, and daily fuel/water checks.
- **Local Database & Offline Capability**: Persistent client-side storage and offline asset availability.
- **CSV Data Export**: Generating and downloading logs in standard CSV format.
- **Passkey Auth & E2E Encryption**: Biometric user onboarding and client-side AES-GCM data encryption.
- **Multi-Logbook Manager**: Dashboard UI to manage and switch between multiple ship logbooks.
- **Stammdaten Forms**: Yacht profile, skipper/crew profiles, and Deviation grids.
- **Sync Protocol**: Local-first caching synced securely to PostgreSQL payloads.
- **CSV Data Export**: Decrypted on-the-fly client-side CSV downloads.
**Should have (differentiators):**
- **GPS Pre-filling**: Instant fetch of coordinates via browser Geolocation.
- **Weather API Integration**: Prefill coordinates' weather and wind parameters via OpenWeatherMap.
- **Adaptive OS UI**: CSS themes styled to blend with Android Material or iOS Cupertino designs.
- **GPS & Weather Integration**: Browser Geolocation API and OpenWeatherMap lookup with offline fallbacks.
- **Adaptive OS UI**: Platforms adaptive Cupertino (iOS) and Material (Android) themes.
### Architecture Approach
Detailed in [ARCHITECTURE.md](ARCHITECTURE.md).
**Major components:**
1. **IndexedDB (Dexie)**: Structured database tables for yacht metadata, crew, compass deviations, and logbook entries.
2. **App Shell UI**: A single-page layout with responsive page navigation, form views, and a storage status check.
3. **Application Services**: Isolated logic handlers for GPS acquisition, OpenWeather API requests, translation bundles, and CSV builders.
4. **Service Worker Cache**: Local static asset container ensuring immediate PWA load times.
- **Zero-Knowledge Backend**: Handles Passkey verification and stores E2E encrypted string blocks without access to user keys.
- **IndexedDB Caching Layer**: Local cache database holding encrypted versions of active logbooks and syncQueue.
- **E2E Cryptographic Service**: Web Crypto utilities implementing PRF-derived keys and BIP39 fallback phrases.
- **Offline PWA Shell**: Service worker caching front-end assets for offline launch.
### Critical Pitfalls
Mitigation steps are outlined in [PITFALLS.md](PITFALLS.md).
1. **iOS Safari Storage Purge**: Safely bypassed by adding instructions for PWA installation (preventing Safari's 7-day inactivity purge) and requesting persistent storage.
2. **Offline Weather API Timeouts**: Resolved by checking connection status and setting a strict 5-second timeout on requests.
3. **GPS Fetch Delays**: Mitigated by setting high-accuracy timeouts, validating precision, and offering full manual entry.
4. **SW Caching Stale Updates**: Handled by adding update prompts instead of automatic service worker overrides.
1. **E2E Key Recovery Loss**: Force recovery phrase validation during sign-up to prevent permanent data loss.
2. **WebAuthn Compatibility**: Check authenticator status and fallback to hardware security keys.
3. **Offline Sync Conflicts**: Utilize transaction logs, last-write-wins rules, and append-only entries with merge warnings.
4. **Offline Weather/GPS Timeouts**: Set 5-second weather fetch timeouts and 10-second GPS lock limits.
## Implications for Roadmap
Based on research and dependencies, we suggest a 4-phase rollout:
Based on research and dependencies, we suggest a revised 4-phase rollout:
### Phase 1: Foundation & Data Infrastructure
- **Rationale**: Setting up the development bundle, service worker, and local database first ensures all subsequent screens can read/write data in real-time.
- **Delivers**: PWA shell, Dexie DB database models, and English/German language configuration.
- **Addresses**: DATA-01 (Local storage), DATA-02 (Offline), GEN-02 (Multilingual).
- **Avoids**: Service worker stale caching updates (set up correctly at the beginning).
### Phase 1: Foundation, Auth & E2E Crypto
- **Rationale**: Creating the client PWA and Express backend repositories first allows building the core security boundary (Passkeys and Web Crypto key derivation) before handling user data.
- **Delivers**: Node backend, Prisma schema, WebAuthn options endpoints, and Web Crypto PRF/recovery helpers.
- **Addresses**: AUTH-01 (Passkeys), CRYPTO-01/02/03 (E2E encryption), UI-02/03 (Languages).
### Phase 2: Vessel & Crew Management (Stammdaten)
- **Rationale**: Master data must be created before a skipper can log a journey.
- **Delivers**: Vessel specifications form, Crew lists management, and the Compass Deviation Grid.
- **Addresses**: MASTER-01 (Vessel/Crew data), Steuertafel.
- **Uses**: Dexie tables for yacht, crew, and deviation.
### Phase 2: Sync Protocol & Multi-Logbooks
- **Rationale**: Developing the caching database, sync protocol, and multi-logbook views next ensures all subsequent UI features sync automatically in the background.
- **Delivers**: Multi-logbook dashboards, Local IndexedDB cache tables, and synchronization transaction queue API.
- **Addresses**: AUTH-02/03 (Multi-logbooks), SYS-02 (Local-first sync).
### Phase 3: Logbook Entries & Integration
- **Rationale**: Core logbook entries require the vessel profile and deviation calculations defined in Phase 2.
- **Delivers**: Log list, log entry form with weather/sea/sail selectors, GPS position pre-fill, and OpenWeather API hook.
- **Addresses**: LOG-01 (Forms), LOG-02 (Weather), LOG-03 (GPS).
- **Avoids**: GPS fetch delays and offline API hangs (using timeouts and fallbacks).
### Phase 3: Master Data & Log entries
- **Rationale**: The UI forms can now read/write securely from the E2E-encrypted sync layer built in Phase 2.
- **Delivers**: Yacht forms, Crew lists, deviation grids, and journal entry records synced to the database.
- **Addresses**: VESSEL-01/02/03 (Boat/crew profiles), DEV-01/02 (Deviation grid), LOG-01/02/03/04/05 (Journal logs), INT-01/02/03 (GPS & Weather).
### Phase 4: Data Export & UI Polish
- **Rationale**: Finalizing data portability and polishing visual alignment.
- **Delivers**: CSV export, local mail/share handlers, storage persistence checks, and iOS/Android adaptive themes.
- **Addresses**: DATA-03 (CSV Export), GEN-01 (Mobile-first adaptive UI).
- **Avoids**: iOS storage purges (by implementing persistent storage requests and PWA install warnings).
### Phase 4: CSV Export & UI Polish
- **Rationale**: Compiling exports and polishing OS-native layouts completes the user cycle.
- **Delivers**: Client-side decryption CSV builder, sync progress indicators, and Material/Cupertino styles.
- **Addresses**: SYS-03/04 (CSV Share/Export), UI-01 (Adaptive UI layout).
### Phase Ordering Rationale
The suggested order establishes database schemas first, followed by static profiles, dynamic transaction forms, and finally export utilities. This minimizes developer friction by ensuring database queries can be fully tested in mock views before building the complex logbook interface.
The suggested order establishes the backend server and cryptographic vault first. Next, it handles multi-logbook syncing so that when the master forms and log entries are coded in Phase 3, they plug immediately into a working, encrypted offline sync pipeline.
### Research Flags
@@ -101,22 +97,24 @@ The suggested order establishes database schemas first, followed by static profi
| Area | Confidence | Notes |
|------|------------|-------|
| Stack | HIGH | Vite React TS is standard for offline PWAs. Dexie is well-maintained and reliable. |
| Features | HIGH | Extracted directly from official PDF example logbook layout. |
| Architecture | HIGH | Standard client-side-only architecture without server dependencies. |
| Pitfalls | HIGH | Service worker caching and iOS storage limits are thoroughly documented in developer circles. |
| Stack | HIGH | Express, Prisma, Postgres, and Dexie are highly reliable. SimpleWebAuthn makes Passkey integration straightforward. |
| Features | HIGH | Expanded requirements map directly to nautical guidelines while preserving user ownership. |
| Architecture | HIGH | Hybrid client-side E2E zero-knowledge design has been proven by services like Proton. |
| Pitfalls | HIGH | Identified key recovery and offline sync conflict risks early with mitigation strategies. |
**Overall confidence:** HIGH
### Gaps to Address
- **OpenWeatherMap API Key**: The app requires an API key. We will implement a setting allowing users to provide their own OpenWeatherMap API key (saved in LocalStorage) so that the app remains open-source, client-side, and avoids developer key exposure.
- **OpenWeatherMap API Key**: Stored client-side in LocalStorage to avoid server exposure or leakage of developer keys.
- **Database Hosting**: Will require configuring a PostgreSQL instance (e.g. Docker container locally or cloud host for production).
## Sources
- [Vite PWA Docs](https://vite-pwa-org.netlify.app/)
- [Dexie.js Documentation](https://dexie.org/)
- [Apple WebKit Storage Guidelines](https://webkit.org/blog/10218/full-third-party-cookie-blocking-and-more/)
- [WebAuthn Specification & SimpleWebAuthn Docs](https://webauthn.guide/)
- [Web Crypto API Reference (W3C)](https://www.w3.org/TR/WebCryptoAPI/)
---
*Research completed: 2026-05-26*