From e72602d7847be2e813c0dc8230baee09b75514c0 Mon Sep 17 00:00:00 2001 From: goose Date: Sat, 14 Feb 2026 11:11:06 -0300 Subject: [PATCH] Initial commit: Project setup and documentation - Initialize Normogen health tracking platform - Add comprehensive project documentation - Add zero-knowledge encryption implementation guide - Set up .gitignore for Rust/Node.js/mobile development - Create README with project overview and roadmap Project is currently in planning phase with no implementation code yet. --- .gitignore | 89 ++ README.md | 89 ++ encryption.md | 1248 +++++++++++++++++ introduction.md | 82 ++ ...04-1739-normogen-codebase-documentation.md | 154 ++ ...2026-01-04-1840-normogen-mvp-definition.md | 361 +++++ .../research/2026-01-05-RESEARCH-SUMMARY.md | 258 ++++ ...6-01-05-health-frameworks-research-plan.md | 60 + ...026-01-05-mobile-health-frameworks-data.md | 635 +++++++++ ...roid-health-connect-data-types-research.md | 431 ++++++ 10 files changed, 3407 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 encryption.md create mode 100644 introduction.md create mode 100644 thoughts/research/2026-01-04-1739-normogen-codebase-documentation.md create mode 100644 thoughts/research/2026-01-04-1840-normogen-mvp-definition.md create mode 100644 thoughts/research/2026-01-05-RESEARCH-SUMMARY.md create mode 100644 thoughts/research/2026-01-05-health-frameworks-research-plan.md create mode 100644 thoughts/research/2026-01-05-mobile-health-frameworks-data.md create mode 100644 thoughts/research/2026-01-12-android-health-connect-data-types-research.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5496cbf --- /dev/null +++ b/.gitignore @@ -0,0 +1,89 @@ +# Normogen - Health Data Tracking Platform + +# Environment variables +.env +.env.local +.env.*.local +.env.development +.env.production +.env.test + +# Dependencies +node_modules/ +.pnp +.pnp.js + +# Build outputs +dist/ +build/ +target/ +*.log + +# Rust specific +Cargo.lock +**/*.rs.bk +.cargo/ + +# Database +*.db +*.sqlite +*.sqlite3 +data/ +db/ + +# Encryption keys (NEVER commit these!) +*.key +*.pem +*.cert +*.der +keys/ +secrets/ +*.enc + +# IDE and Editor files +.vscode/ +.idea/ +*.swp +*.swo +*~ +.DS_Store + +# Logs +logs/ +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Testing +coverage/ +.nyc_output/ +*.lcov + +# Docker volumes (if using for local dev) +docker-volumes/ + +# OS specific +Thumbs.db +.DS_Store + +# Temporary files +tmp/ +temp/ +*.tmp + +# Backup files +*.bak +*.backup + +# Phone app builds (if developing locally) +ios/Pods/ +ios/*.xcworkspace +ios/*.xcodeproj/xcuserdata/ +android/app/build/ +android/.gradle/ + +# Documentation build artifacts +_site/ +.sass-cache/ +.jekyll-cache/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..2a5a0a6 --- /dev/null +++ b/README.md @@ -0,0 +1,89 @@ +# Normogen + +## Overview + +Normogen is a privacy-focused health data tracking and management platform. The name comes from Mapudungun, relating to "Balanced Life." + +## Vision + +To record as many variables related to health as possible, store them in a secure, private manner, to be used by **you**, not by corporations. From medication reminders to pattern analysis, Normogen puts you in control of your health data. + +## Key Features + +### Core Functionality +- ๐Ÿ” **Zero-knowledge encryption** - Your data is encrypted before it reaches the server +- ๐Ÿ‘ฅ **Multi-person profiles** - Track health data for yourself, children, elderly family members +- ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ **Family structure** - Manage family health records in one place +- ๐Ÿ”— **Secure sharing** - Share specific data via expiring links with embedded passwords +- ๐Ÿ“ฑ **Mobile apps** - iOS and Android with health sensor integration +- ๐ŸŒ **Web interface** - Access from any device + +### Health Data Tracking +- Lab results storage +- Medication tracking (dosage, schedules, composition) +- Health statistics (weight, height, trends) +- Medical appointments +- Regular checkups +- Period tracking +- Pregnancy tracking +- Dental information +- Illness records +- Phone sensor data (steps, activity, sleep, blood pressure, temperature) + +## Architecture + +### Technology Stack +- **Backend API**: Rust +- **Web Server**: Node.js +- **Database**: MongoDB (with zero-knowledge encryption) +- **Frontend**: Web + iOS + Android +- **Deployment**: Docker on Linux + +### Security Model +- **Client-side encryption**: Data encrypted before leaving the device +- **Zero-knowledge**: Server stores only encrypted data +- **Proton-style encryption**: AES-256-GCM with PBKDF2 key derivation +- **Shareable links**: Self-contained decryption keys in URLs +- **Privacy-first**: No data selling, subscription-based revenue + +## Documentation + +- [Introduction](./introduction.md) - Project vision and detailed feature specification +- [Encryption Implementation Guide](./encryption.md) - Zero-knowledge encryption architecture +- [Research](./thoughts/research/) - Technical research and planning documents + +## Development Status + +๐Ÿšง **Current Phase**: Planning/Documentation + +### Completed +- โœ… Project vision and requirements +- โœ… Security architecture design +- โœ… Encryption implementation guide +- โœ… Feature specifications +- โœ… Git repository initialization + +### Next Steps +- [ ] Select Rust framework (Actix, Axum, Rocket?) +- [ ] Design database schema +- [ ] Implement authentication system +- [ ] Build CRUD API +- [ ] Create web frontend +- [ ] Add encryption layer +- [ ] Implement sharing functionality + +## Open Source + +Normogen is open-source. Both server and client code will be publicly available. + +## License + +TBD + +## Contributing + +TBD - While in planning phase, contributions are welcome through discussion and documentation improvements. + +--- + +**Note**: This project is currently in the planning phase. No implementation code has been written yet. diff --git a/encryption.md b/encryption.md new file mode 100644 index 0000000..281781c --- /dev/null +++ b/encryption.md @@ -0,0 +1,1248 @@ +# Zero-Knowledge Encryption Implementation Guide + +## Table of Contents +1. [Proton-Style Encryption for MongoDB](#proton-style-encryption-for-mongodb) +2. [Shareable Links with Embedded Passwords](#shareable-links-with-embedded-passwords) +3. [Security Best Practices](#security-best-practices) +4. [Advanced Features](#advanced-features) + +--- + +## Proton-Style Encryption for MongoDB + +### Architecture Overview + +``` +Application Layer (Client Side) +โ”œโ”€โ”€ Encryption/Decryption happens HERE +โ”œโ”€โ”€ Queries constructed with encrypted searchable fields +โ””โ”€โ”€ Data never leaves application unencrypted + +MongoDB (Server Side) +โ””โ”€โ”€ Stores only encrypted data +``` + +### Implementation Approaches + +#### 1. Application-Level Encryption (Recommended) + +Encrypt sensitive fields before they reach MongoDB: + +```javascript +// Using Node.js with crypto +const crypto = require('crypto'); + +class EncryptedMongo { + constructor(encryptionKey) { + this.algorithm = 'aes-256-gcm'; + this.key = encryptionKey; + } + + encrypt(text) { + const iv = crypto.randomBytes(16); + const cipher = crypto.createCipheriv(this.algorithm, this.key, iv); + let encrypted = cipher.update(text, 'utf8', 'hex'); + encrypted += cipher.final('hex'); + const authTag = cipher.getAuthTag(); + + return { + data: encrypted, + iv: iv.toString('hex'), + authTag: authTag.toString('hex') + }; + } + + decrypt(encryptedObj) { + const decipher = crypto.createDecipheriv( + this.algorithm, + this.key, + Buffer.from(encryptedObj.iv, 'hex') + ); + decipher.setAuthTag(Buffer.from(encryptedObj.authTag, 'hex')); + + let decrypted = decipher.update(encryptedObj.data, 'hex', 'utf8'); + decrypted += decipher.final('utf8'); + return decrypted; + } +} + +// Example usage +const encryptedMongo = new EncryptedMongo(userEncryptionKey); + +// Storing encrypted data +await db.collection('users').insertOne({ + _id: userId, + email: encryptedMongo.encrypt('user@example.com'), + ssn: encryptedMongo.encrypt('123-45-6789'), + // Non-sensitive fields can remain plaintext for queries + username: 'johndoe', // plaintext for searching + createdAt: new Date() +}); + +// Retrieving and decrypting +const user = await db.collection('users').findOne({ _id: userId }); +const decryptedEmail = encryptedMongo.decrypt(user.email); +``` + +#### 2. Deterministic Encryption for Searchable Fields + +For fields you need to query (like email), use deterministic encryption: + +```javascript +const crypto = require('crypto'); + +function deterministicEncrypt(text, key) { + const hmac = crypto.createHmac('sha256', key); + const iv = hmac.update(text).digest(); + const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); + + let encrypted = cipher.update(text, 'utf8', 'hex'); + encrypted += cipher.final('hex'); + return encrypted; +} + +// Same input always produces same output +const encryptedEmail1 = deterministicEncrypt('user@example.com', key); +const encryptedEmail2 = deterministicEncrypt('user@example.com', key); +console.log(encryptedEmail1 === encryptedEmail2); // true + +// Now you can query by encrypted email +await db.collection('users').findOne({ + emailSearchable: deterministicEncrypt('user@example.com', userKey) +}); +``` + +#### 3. Field-Level Encryption Strategy + +```javascript +// Document structure example +{ + _id: ObjectId("..."), + + // Public/indexable fields (plaintext) + username: "johndoe", + userId: "unique-id-123", + createdAt: ISODate("2026-01-07"), + + // Deterministically encrypted (searchable but not readable) + email_searchable: "a1b2c3d4...", // for equality queries + username_searchable: "e5f6g7h8...", + + // Randomly encrypted (not searchable, most secure) + sensitiveData: { + encrypted: true, + data: "x9y8z7...", + iv: "1a2b3c...", + authTag: "4d5e6f..." + } +} +``` + +### Key Management Strategy + +```javascript +// Never store the master key in MongoDB! +class KeyManager { + constructor() { + this.masterKey = process.env.MASTER_ENCRYPTION_KEY; // Environment variable + } + + // Derive unique key per user/document + deriveUserKey(userId) { + return crypto + .createHash('sha256') + .update(`${this.masterKey}:${userId}`) + .digest(); + } + + // For additional security, use KDF (scrypt/argon2) + async deriveKeyWithScrypt(userId) { + return new Promise((resolve, reject) => { + crypto.scrypt( + this.masterKey, + `salt:${userId}`, + 32, + (err, derivedKey) => { + if (err) reject(err); + else resolve(derivedKey); + } + ); + }); + } +} +``` + +### MongoDB Schema Example with Mongoose + +```javascript +const mongoose = require('mongoose'); + +const encryptedFieldSchema = new mongoose.Schema({ + data: { type: String, required: true }, + iv: { type: String, required: true }, + authTag: { type: String, required: true } +}); + +const userSchema = new mongoose.Schema({ + // Public fields + username: { type: String, index: true }, + userId: { type: String, unique: true }, + + // Searchable encrypted fields + emailEncrypted: { type: String, index: true }, + + // Fully encrypted data + profile: encryptedFieldSchema, + financialData: encryptedFieldSchema, + + createdAt: { type: Date, default: Date.now } +}); + +// Middleware to encrypt before save +userSchema.pre('save', async function(next) { + if (this.isModified('profile')) { + const encrypted = encryptionService.encrypt(this.profile); + this.profile = encrypted; + } + next(); +}); +``` + +### MongoDB Field Level Encryption (Official Alternative) + +MongoDB offers official client-side field level encryption: + +```bash +npm install mongodb-client-encryption +``` + +```javascript +const { MongoClient } = require('mongodb'); +const { ClientEncryption } = require('mongodb-client-encryption'); + +const encryption = new ClientEncryption( + client, + { + keyVaultNamespace: 'encryption.__keyVault', + kmsProviders: { + local: { key: masterKey } + } + } +); + +// Auto-encrypt specific fields +const encryptedValue = await encryption.encrypt( + 'sensitive-data', + 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' +); +``` + +--- + +## Shareable Links with Embedded Passwords + +### Architecture Overview + +``` +1. User has encrypted data in MongoDB +2. Creates a public share with a password +3. Generates a shareable link with encrypted password +4. External user clicks link โ†’ password extracted โ†’ data decrypted +``` + +### Implementation + +#### 1. Share Link Structure + +``` +https://yourapp.com/share/{shareId}?key={encryptedShareKey} +``` + +Components: +- **shareId**: References the shared data in MongoDB +- **key**: Encrypted version of the decryption password (self-contained in URL) + +#### 2. MongoDB Schema for Shared Data + +```javascript +const mongoose = require('mongoose'); + +const shareSchema = new mongoose.Schema({ + shareId: { type: String, unique: true, required: true }, + + // Reference to original encrypted data + userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, + documentId: { type: mongoose.Schema.Types.ObjectId }, + collectionName: { type: String }, + + // The encrypted data (encrypted with share-specific password) + encryptedData: { + data: { type: String, required: true }, + iv: { type: String, required: true }, + authTag: { type: String, required: true } + }, + + // Metadata + createdAt: { type: Date, default: Date.now }, + expiresAt: { type: Date }, + accessCount: { type: Number, default: 0 }, + maxAccessCount: { type: Number }, // Optional: limit access + + // Optional: Additional security + allowedEmails: [String], // Restrict to specific emails + requireEmailVerification: { type: Boolean, default: false }, + isRevoked: { type: Boolean, default: false }, + revokedAt: Date +}); + +const Share = mongoose.model('Share', shareSchema); +``` + +#### 3. Creating a Shareable Link + +```javascript +const crypto = require('crypto'); + +class ShareService { + constructor() { + this.algorithm = 'aes-256-gcm'; + } + + // Generate a random share password + generateSharePassword() { + return crypto.randomBytes(32).toString('hex'); + } + + // Generate unique share ID + generateShareId() { + return crypto.randomBytes(16).toString('hex'); + } + + // Encrypt data with share password + encryptData(data, password) { + const salt = crypto.randomBytes(32); + const key = crypto.pbkdf2Sync(password, salt, 100000, 32, 'sha256'); + + const iv = crypto.randomBytes(16); + const cipher = crypto.createCipheriv(this.algorithm, key, iv); + + let encrypted = cipher.update(JSON.stringify(data), 'utf8', 'hex'); + encrypted += cipher.final('hex'); + const authTag = cipher.getAuthTag(); + + return { + data: encrypted, + iv: iv.toString('hex'), + salt: salt.toString('hex'), + authTag: authTag.toString('hex') + }; + } + + // Create shareable link + async createShare(userId, documentData, options = {}) { + // Generate a unique share password + const sharePassword = this.generateSharePassword(); + + // Encrypt the data with this password + const encryptedData = this.encryptData(documentData, sharePassword); + + // Create share record + const shareId = this.generateShareId(); + const share = await Share.create({ + shareId, + userId, + encryptedData, + expiresAt: options.expiresAt, + maxAccessCount: options.maxAccessCount + }); + + // Generate the shareable link with embedded password + const shareLink = this.generateShareLink(shareId, sharePassword); + + return { + shareId, + shareLink, + expiresAt: share.expiresAt + }; + } + + // Generate share link with encrypted password + generateShareLink(shareId, password) { + // Encrypt the password with a server-side master key + // This way the password is in the URL but not readable + const masterKey = process.env.SHARE_LINK_MASTER_KEY; + const encryptedPassword = this.encryptPasswordInUrl(password, masterKey); + + return `https://yourapp.com/share/${shareId}?key=${encodeURIComponent(encryptedPassword)}`; + } + + encryptPasswordInUrl(password, masterKey) { + // Use URL-safe base64 encoding + const iv = crypto.randomBytes(16); + const cipher = crypto.createCipheriv(this.algorithm, masterKey, iv); + + let encrypted = cipher.update(password, 'utf8', 'hex'); + encrypted += cipher.final('hex'); + const authTag = cipher.getAuthTag(); + + // URL-safe format: iv:authTag:encrypted + return `${iv.toString('hex')}:${authTag.toString('hex')}:${encrypted}`; + } +} +``` + +#### 4. Accessing Shared Data (Backend) + +```javascript +class ShareAccessService { + constructor() { + this.algorithm = 'aes-256-gcm'; + this.masterKey = process.env.SHARE_LINK_MASTER_KEY; + } + + // Decrypt password from URL + decryptPasswordFromUrl(encryptedPassword) { + const parts = encryptedPassword.split(':'); + const iv = Buffer.from(parts[0], 'hex'); + const authTag = Buffer.from(parts[1], 'hex'); + const encrypted = parts[2]; + + const decipher = crypto.createDecipheriv(this.algorithm, this.masterKey, iv); + decipher.setAuthTag(authTag); + + let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + decrypted += decipher.final('utf8'); + return decrypted; + } + + // Decrypt share data + decryptShareData(encryptedData, password) { + const salt = Buffer.from(encryptedData.salt, 'hex'); + const key = crypto.pbkdf2Sync(password, salt, 100000, 32, 'sha256'); + + const iv = Buffer.from(encryptedData.iv, 'hex'); + const authTag = Buffer.from(encryptedData.authTag, 'hex'); + + const decipher = crypto.createDecipheriv(this.algorithm, key, iv); + decipher.setAuthTag(authTag); + + let decrypted = decipher.update(encryptedData.data, 'hex', 'utf8'); + decrypted += decipher.final('utf8'); + + return JSON.parse(decrypted); + } + + // Access shared data + async accessShare(shareId, encryptedPassword) { + // Find share record + const share = await Share.findOne({ shareId }); + + if (!share) { + throw new Error('Share not found'); + } + + // Check if revoked + if (share.isRevoked) { + throw new Error('Share has been revoked'); + } + + // Check if expired + if (share.expiresAt && new Date() > share.expiresAt) { + throw new Error('Share has expired'); + } + + // Check access limit + if (share.maxAccessCount && share.accessCount >= share.maxAccessCount) { + throw new Error('Maximum access count reached'); + } + + // Decrypt password from URL + const password = this.decryptPasswordFromUrl(encryptedPassword); + + // Decrypt data + const decryptedData = this.decryptShareData(share.encryptedData, password); + + // Increment access count + share.accessCount += 1; + await share.save(); + + return { + data: decryptedData, + expiresAt: share.expiresAt + }; + } +} +``` + +#### 5. Express.js API Endpoint + +```javascript +const express = require('express'); +const router = express.Router(); + +// POST /api/share - Create a new share +router.post('/share', async (req, res) => { + try { + const { userId, data, options } = req.body; + + const shareService = new ShareService(); + const result = await shareService.createShare(userId, data, options); + + res.json(result); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}); + +// GET /api/share/:shareId - Access shared data +router.get('/share/:shareId', async (req, res) => { + try { + const { shareId } = req.params; + const { key } = req.query; // Encrypted password from URL + + if (!key) { + return res.status(400).json({ error: 'Missing decryption key' }); + } + + const accessService = new ShareAccessService(); + const result = await accessService.accessShare(shareId, key); + + res.json(result); + } catch (error) { + res.status(404).json({ error: error.message }); + } +}); + +module.exports = router; +``` + +#### 6. Frontend: Share Access Page (React) + +```javascript +import React, { useEffect, useState } from 'react'; +import { useParams, useSearchParams } from 'react-router-dom'; + +function SharedDataView() { + const { shareId } = useParams(); + const [searchParams] = useSearchParams(); + const [data, setData] = useState(null); + const [error, setError] = useState(null); + const [loading, setLoading] = useState(true); + + useEffect(() => { + async function fetchData() { + try { + const key = searchParams.get('key'); + + if (!key) { + throw new Error('Invalid share link'); + } + + const response = await fetch(`/api/share/${shareId}?key=${encodeURIComponent(key)}`); + + if (!response.ok) { + throw new Error('Failed to access shared data'); + } + + const result = await response.json(); + setData(result.data); + } catch (err) { + setError(err.message); + } finally { + setLoading(false); + } + } + + fetchData(); + }, [shareId, searchParams]); + + if (loading) return
Loading...
; + if (error) return
Error: {error}
; + + return ( +
+

Shared Data

+
{JSON.stringify(data, null, 2)}
+
+ ); +} + +export default SharedDataView; +``` + +#### 7. Creating a Share (Frontend) + +```javascript +async function createShare() { + const dataToShare = { + name: 'John Doe', + email: 'john@example.com', + // ... other fields + }; + + const response = await fetch('/api/share', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + userId: 'current-user-id', + data: dataToShare, + options: { + expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days + maxAccessCount: 10 + } + }) + }); + + const result = await response.json(); + + // result.shareLink is ready to share! + // Example: https://yourapp.com/share/a1b2c3d4...?key=e5f6g7h8... + + return result.shareLink; +} +``` + +--- + +## Security Best Practices + +### Key Management + +1. **Never store encryption keys in MongoDB** + - Use environment variables + - Consider key management services (AWS KMS, HashiCorp Vault) + - Hardware Security Modules (HSMs) for production + +2. **Use different encryption keys per:** + - User + - Document type + - Environment (dev/staging/prod) + +3. **Implement key rotation:** + +```javascript +async function rotateKey(oldKey, newKey, collection) { + const documents = await collection.find().toArray(); + + for (const doc of documents) { + const decrypted = decrypt(doc.encryptedField, oldKey); + const reencrypted = encrypt(decrypted, newKey); + + await collection.updateOne( + { _id: doc._id }, + { $set: { encryptedField: reencrypted } } + ); + } +} +``` + +### Environment Variables + +```bash +# .env +MASTER_ENCRYPTION_KEY= +SHARE_LINK_MASTER_KEY= +MONGODB_URI=mongodb://localhost:27017/yourdb +``` + +Generate master keys: +```bash +node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" +``` + +### Backup Strategy + +- **Backup encrypted data with separate key backups** +- Store keys in different physical locations +- Test restore procedures regularly + +### Limitations of Encrypted Database + +- **No range queries** on encrypted numeric fields +- **No regex/full-text search** on encrypted text +- **Indexing only works** with deterministic encryption (less secure) +- **Performance overhead** from encryption/decryption + +--- + +## Advanced Features + +### 1. Password Expiration + +```javascript +// Set expiration when creating share +const share = await createShare(userId, data, { + expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000) // 24 hours +}); +``` + +### 2. Access Limits + +```javascript +const share = await createShare(userId, data, { + maxAccessCount: 5 // Only 5 people can access +}); +``` + +### 3. Additional Password Protection + +```javascript +// Require a separate password (not in URL) +const shareSchema = new mongoose.Schema({ + // ... other fields + passwordRequired: { type: Boolean, default: false }, + passwordHash: String +}); + +// User must enter password on page load +// Password is verified before decrypting data +``` + +### 4. Email Verification + +```javascript +// Restrict access to specific emails +const share = await createShare(userId, data, { + allowedEmails: ['user@example.com', 'trusted@domain.com'], + requireEmailVerification: true +}); +``` + +### 5. Revocable Shares + +```javascript +// Middleware to check revocation +shareSchema.pre('save', function(next) { + if (this.isModified('isRevoked') && this.isRevoked) { + this.revokedAt = new Date(); + } + next(); +}); + +// Revoke a share +async function revokeShare(shareId) { + await Share.findOneAndUpdate( + { shareId }, + { isRevoked: true } + ); +} +``` + +--- + +## Summary + +This implementation provides: + +โœ… **Zero-knowledge**: MongoDB never stores unencrypted shared data +โœ… **Self-contained links**: Password embedded in URL +โœ… **Access controls**: Expiration, access limits, email restrictions +โœ… **Revocability**: Users can revoke shares anytime +โœ… **Security**: AES-256-GCM encryption with PBKDF2 key derivation +โœ… **User experience**: One-click access for recipients +โœ… **Per-user encryption**: Each user's data encrypted with unique keys +โœ… **Searchable encryption**: Deterministic encryption for queryable fields + +## Dependencies + +```json +{ + "dependencies": { + "mongoose": "^8.0.0", + "express": "^4.18.0", + "crypto": "built-in", + "mongodb-client-encryption": "^6.0.0" + } +} +``` + +## Password Recovery in Zero-Knowledge Systems + +### The Core Problem + +In a zero-knowledge system: +- **User's password** (or derived key) encrypts their data +- **Server never sees the password** in plaintext +- **If password is lost**, the data is mathematically unrecoverable + +This is actually a **feature**, not a bug - it's what makes the system truly zero-knowledge! + +--- + +### Solution Approaches (Ranked by Security) + +#### 1. Secure Recovery Phrase (Recommended) โญ + +Give users a recovery phrase during signup that they must save securely. + +```javascript +class UserRegistration { + async registerUser(email, password) { + // Generate a random recovery key + const recoveryKey = crypto.randomBytes(32).toString('hex'); + + // Encrypt recovery key with user's password + const encryptedRecoveryKey = this.encryptWithPassword( + recoveryKey, + password + ); + + // Store encrypted recovery key in database + await User.create({ + email, + passwordHash: await hashPassword(password), // For authentication only + encryptedRecoveryKey, + dataEncryptionKey: this.deriveKeyFromPassword(password) + }); + + // Display recovery key ONCE - never show again! + return { + userId: user.id, + recoveryKey: recoveryKey, // Show this to user + warning: "Save this key securely. You'll need it to recover your account." + }; + } +} + +// Recovery process +async function recoverAccount(email, recoveryKey, newPassword) { + const user = await User.findOne({ email }); + + // Decrypt the stored encrypted recovery key + // This is encrypted with the OLD password, but we have the recovery key + // So we can re-encrypt it with the NEW password + const dataEncryptionKey = this.decryptDataEncryptionKey( + user.encryptedRecoveryKey, + recoveryKey + ); + + // Re-encrypt data encryption key with new password + user.encryptedRecoveryKey = this.encryptWithPassword( + recoveryKey, + newPassword + ); + user.dataEncryptionKey = this.deriveKeyFromPassword(newPassword); + + await user.save(); + + return { success: true, message: "Account recovered successfully" }; +} +``` + +**Pros:** +- โœ… Maintains zero-knowledge property +- โœ… User has full control +- โœ… No backdoors for attackers + +**Cons:** +- โŒ Users might lose the recovery key +- โŒ Requires user education + +--- + +#### 2. Multi-Share Secret Splitting (Shamir's Secret Sharing) ๐Ÿ” + +Split the recovery key into multiple parts. User needs a threshold of parts to recover. + +```javascript +const secrets = require('secrets.js'); // npm install secrets.js + +class ShamirRecovery { + async createUserWithShamirBackup(email, password) { + // Generate master encryption key + const masterKey = crypto.randomBytes(32); + + // Split into shares (e.g., 5 shares, need 3 to recover) + const shares = secrets.share( + masterKey.toString('hex'), + 3, // threshold + 5 // total shares + ); + + // Store shares in different locations + const recoverySetup = { + userShare: shares[0], // Given to user + emailShare: shares[1], // Emailed to user + trustedContactShare: shares[2], // Sent to trusted contact + backupShare1: shares[3], // Stored in secure backup + backupShare2: shares[4] // Stored in separate location + }; + + // Encrypt master key with user's password + const encryptedMasterKey = this.encryptWithPassword( + masterKey, + password + ); + + await User.create({ + email, + encryptedMasterKey, + shamirShares: { + userShare: recoverySetup.userShare, + // Other shares stored elsewhere + } + }); + + return { + recoveryShare: recoverySetup.userShare, + emailShare: recoverySetup.emailShare, + instructions: "Keep at least 3 of these 5 shares safe" + }; + } + + async recoverAccount(email, providedShares, newPassword) { + const user = await User.findOne({ email }); + + // User provides 3+ shares + if (providedShares.length < 3) { + throw new Error('Need at least 3 shares to recover'); + } + + // Combine shares to recover master key + const masterKeyHex = secrets.combine(providedShares); + const masterKey = Buffer.from(masterKeyHex, 'hex'); + + // Re-encrypt with new password + user.encryptedMasterKey = this.encryptWithPassword( + masterKey, + newPassword + ); + + await user.save(); + + return { success: true }; + } +} +``` + +**Pros:** +- โœ… No single point of failure +- โœ… Flexible recovery options +- โœ… Still maintains zero-knowledge + +**Cons:** +- โŒ More complex to implement +- โŒ Users might find it confusing + +--- + +#### 3. Trusted Contact Recovery ๐Ÿ‘ฅ + +Allow trusted contacts to help recover access. + +```javascript +class TrustedContactRecovery { + async setupTrustedContact(userId, contactEmail, userPassword) { + // Generate a recovery key for this contact + const recoveryKey = crypto.randomBytes(32); + + // Encrypt recovery key with contact's public key + // (Contact would need to have an account too) + const encryptedRecoveryKey = crypto.publicEncrypt( + contactPublicKey, + recoveryKey + ); + + // Store the encrypted recovery share + await TrustedContact.create({ + userId, + contactEmail, + encryptedRecoveryKey, + createdAt: new Date() + }); + } + + async initiateRecovery(userId) { + // Notify all trusted contacts + const contacts = await TrustedContact.find({ userId }); + + for (const contact of contacts) { + await sendEmail({ + to: contact.contactEmail, + subject: 'Account Recovery Request', + body: 'Click to approve account recovery', + approvalLink: `/approve-recovery?token=${generateToken()}` + }); + } + } + + async recoverWithContactApproval(recoveryToken, newPassword) { + // Once enough contacts approve (e.g., 2 of 3) + const approvals = await RecoveryApproval.find({ token: recoveryToken }); + + if (approvals.length >= 2) { + // Combine encrypted shares and decrypt with contact private keys + // Then re-encrypt with new password + const masterKey = this.combineContactShares(approvals); + + await this.resetPassword(userId, masterKey, newPassword); + return { success: true }; + } + } +} +``` + +**Pros:** +- โœ… Social recovery mechanism +- โœ… No need to remember complex keys +- โœ… Still technically zero-knowledge + +**Cons:** +- โŒ Requires trusted contacts to also use the service +- โŒ Social engineering risks + +--- + +#### 4. Time-Locked Recovery โฐ + +Encrypt recovery keys with a future decryption (using blockchain or time-lock crypto). + +```javascript +class TimeLockedRecovery { + async createTimeLockedBackup(userId, password, lockDays) { + // Generate recovery key + const recoveryKey = crypto.randomBytes(32); + + // Encrypt recovery key with user's password + const encryptedRecoveryKey = this.encryptWithPassword( + recoveryKey, + password + ); + + // Create a time-locked backup + // In production, use something like Drand or blockchain timelock + const timeLock = { + recoveryKey, + unlockDate: new Date(Date.now() + lockDays * 24 * 60 * 60 * 1000), + encryptedBackup: this.encryptForFuture(recoveryKey, lockDays) + }; + + await TimeLockBackup.create({ + userId, + encryptedRecoveryKey, + timeLock, + createdAt: new Date() + }); + } + + async recoverWithTimeLock(userId) { + const backup = await TimeLockBackup.findOne({ userId }); + + if (new Date() < backup.timeLock.unlockDate) { + throw new Error('Backup not yet available'); + } + + // Decrypt using time-lock release + const recoveryKey = await this.decryptFromFuture( + backup.timeLock.encryptedBackup + ); + + return recoveryKey; + } +} +``` + +**Pros:** +- โœ… Automatic recovery after time period +- โœ… Prevents impulsive data loss + +**Cons:** +- โŒ User must wait for lock period +- โŒ Complex implementation + +--- + +### What NOT to Do โŒ + +#### โŒ Store Passwords in Plaintext +```javascript +// NEVER DO THIS +await User.create({ + email, + password: password // โŒ Defeats the whole purpose +}); +``` + +#### โŒ Store Encryption Keys on Server +```javascript +// NEVER DO THIS +await User.create({ + email, + encryptedData: data, + encryptionKey: key // โŒ Not zero-knowledge +}); +``` + +#### โŒ Backdoor Encryption +```javascript +// NEVER DO THIS +const key = deriveKey(password); +const backdoorKey = process.env.BACKDOOR_KEY; // โŒ Huge security risk +``` + +--- + +### Hybrid Approach (Practical Recommendation) + +Combine multiple methods for different scenarios: + +```javascript +class HybridRecoverySystem { + async setupUserRecovery(email, password) { + const userId = await this.createUser(email, password); + + // 1. Generate recovery phrase (primary method) + const recoveryPhrase = this.generateRecoveryPhrase(); + + // 2. Setup 2 trusted contacts (secondary method) + await this.setupTrustedContact(userId, 'contact1@email.com', password); + await this.setupTrustedContact(userId, 'contact2@email.com', password); + + // 3. Create time-locked backup (last resort) + await this.createTimeLockedBackup(userId, password, 30); // 30 days + + return { + userId, + recoveryPhrase, + trustedContacts: ['contact1@email.com', 'contact2@email.com'], + timeLockDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) + }; + } + + async recoverAccount(email, method, ...args) { + switch (method) { + case 'phrase': + return this.recoverWithPhrase(email, ...args); + case 'contacts': + return this.recoverWithContacts(email, ...args); + case 'timelock': + return this.recoverWithTimeLock(email, ...args); + default: + throw new Error('Invalid recovery method'); + } + } +} +``` + +--- + +### User Education is Key ๐Ÿ“š + +```javascript +// During registration +const registrationInfo = { + title: 'Account Recovery Setup', + message: ` + IMPORTANT: Save your recovery phrase securely! + + Your recovery phrase: ${recoveryPhrase} + + Store it in: + - A password manager + - A safe deposit box + - Written down and stored securely + + Without this phrase, your data cannot be recovered if you forget your password. + + We also recommend setting up trusted contacts as a backup recovery method. + `, + checkboxRequired: true, + checkboxLabel: 'I understand that without my recovery phrase, my data cannot be recovered' +}; +``` + +--- + +### UI/UX Example (React) + +```javascript +function RecoverySetup({ onComplete }) { + const [recoveryPhrase, setRecoveryPhrase] = useState(''); + const [confirmed, setConfirmed] = useState(false); + + useEffect(() => { + // Generate and show recovery phrase + const phrase = generateRecoveryPhrase(); + setRecoveryPhrase(phrase); + }, []); + + return ( +
+

Account Recovery Setup

+ +
+ + Save this recovery phrase securely. You won't be able to see it again! + +
+ +
+ + +
+ + setConfirmed(e.target.checked)} + /> + } + label="I have securely stored my recovery phrase" + /> + + +
+ ); +} +``` + +--- + +### Recovery Methods Comparison + +| Method | Security | UX | Complexity | Zero-Knowledge? | +|--------|----------|-----|------------|-----------------| +| Recovery Phrase | โญโญโญโญโญ | โญโญโญ | โญโญ | โœ… Yes | +| Shamir's Secret Sharing | โญโญโญโญโญ | โญโญ | โญโญโญโญ | โœ… Yes | +| Trusted Contacts | โญโญโญโญ | โญโญโญโญ | โญโญโญ | โœ… Yes | +| Time-Locked | โญโญโญ | โญโญโญโญโญ | โญโญโญโญโญ | โœ… Yes | +| Server Key Storage | โญ | โญโญโญโญโญ | โญ | โŒ No | + +--- + +### Bottom Line + +**There is no way to recover data without some form of backup.** The question is: which backup method aligns with your security requirements and user experience goals? + +For most applications, I recommend: +1. **Primary**: Recovery phrase (most secure) +2. **Secondary**: Trusted contacts (user-friendly) +3. **Fallback**: Time-locked backup (last resort) + +--- + +## Related Concepts + +- **Proton Mail/Drive**: Zero-knowledge encryption services +- **End-to-end encryption**: Data encrypted at rest and in transit +- **PBKDF2**: Password-based key derivation function +- **AES-256-GCM**: Advanced Encryption Standard with authentication +- **Deterministic encryption**: Same plaintext produces same ciphertext +- **Key rotation**: Periodic replacement of encryption keys +- **Shamir's Secret Sharing**: Cryptographic method for splitting secrets +- **Social recovery**: Using trusted contacts for account recovery diff --git a/introduction.md b/introduction.md new file mode 100644 index 0000000..56746f6 --- /dev/null +++ b/introduction.md @@ -0,0 +1,82 @@ +# Normogen + +## Naming + +Codename, coming from mapudungun, related to Balanced Life. Commercial name to be defined + +## Purpose + +To record as many variables related to health as possible, store them in a secure, private manner, to be used by the user, not by corporations. From there, use the data to help the user, not for profit. +From reminding about medication, to comparing data changes over time, and finding emerging patterns. + +## Income + +It will come from subscriptions from users, not from using the data. +Even if open-source, the architecture is complicated enough that users will want to pay a subscription rather than setting it all up themselves. And the bugfixing coming from open-source users should offset the lost income. + +## Architecture + +Client-server architecture, server running on linux docker, clients via web or phone apps (iOS and Android) + +Rust for the server backend. Nodejs for web server. Clients will be on whatever is best for each platform, which can reuse the web when possible. + +Data has to be encrypted on storage, only accessible to the user, on the server and on the phone apps. +It is important to be able to share specific bits of data with external users. (at first, accessed by an expiring link). Therefore, the encryption has to be made in a way that a limited password can access some of the data. + +It will be open-sourced, both server and clients. + +### Plugins + +Mostly for import and export of data + + +## Application Features + +### User structure + +- User login +- Person, which may not be the logged in user. eg. recording data of a child +- Family structure (eg. parents, children, elderly under care, etc.) + +### General + +- Lab results storage +- Medication + - Pill shape + - Length of take + - Timetable + - Drug composition +- General health statistics, such as weight over time, height, age +- Medical appointments +- Regular checkouts +- Period tracking +- Pregnancy +- Dental information +- Illness records + + +### Phone app + +- Pill reminder +- QR code reader, for access to lab results and others +- Health statistics from the phone and connected devices, such as: + - steps + - physical activity + - Breathing + - Sleep patterns + - Blood pressure + - Temperature, etc +- Sync back to the main server at regular intervals +- Instant nuke option, to delete all data instantly (for privacy) + +### Lab Results + +Lab results are not standard format, so there must be a plugin structure that allows to convert data from specific labs + +### Sensors + +Most sensors will have a common interface or data will be accessable through the phone's Health API, but there might be cases where a plugin to convert data is needed + + + + diff --git a/thoughts/research/2026-01-04-1739-normogen-codebase-documentation.md b/thoughts/research/2026-01-04-1739-normogen-codebase-documentation.md new file mode 100644 index 0000000..f9805f7 --- /dev/null +++ b/thoughts/research/2026-01-04-1739-normogen-codebase-documentation.md @@ -0,0 +1,154 @@ +--- +date: 2026-01-04T17:39:07-03:00 +git_commit: N/A (not a git repository) +branch: N/A +repository: normogen +topic: "Normogen Codebase Documentation - Initial State" +tags: [research, codebase, project-status, documentation] +status: complete +--- + +# Research: Normogen Codebase Documentation + +## Research Question +Document the current state of the Normogen project codebase based on introduction.md to understand what exists, where components are located, and how the architecture is planned. + +## Summary + +**Critical Finding:** The Normogen project is currently in the **conceptual/planning phase** only. The codebase contains **no implementation code** whatsoever. The entire project exists as a single design document (`introduction.md`) outlining the planned architecture and features. + +**Status:** Pre-implementation - Planning Stage + +## Detailed Findings + +### Current Project State + +#### What Exists +- **Single File Only:** `/home/asoliver/desarrollo/normogen/introduction.md` (2,642 bytes) +- **No Git Repository:** Project is not under version control +- **No Source Code:** Zero lines of implementation code +- **No Configuration:** No Cargo.toml, package.json, docker-compose, or other config files +- **No Directory Structure:** Flat directory with only the design document + +#### What Does NOT Exist (Yet) +Based on the plans in introduction.md, the following components are **not yet implemented**: + +1. **Backend (Rust)** + - No Rust server code + - No Cargo.toml or workspace configuration + - No database schema or migrations + - No encryption implementation + - No API endpoints + +2. **Web Server (Node.js)** + - No package.json + - No web server code + - No frontend code + +3. **Mobile Applications** + - No iOS/Swift code + - No Android/Kotlin code + - No React Native or cross-platform framework setup + +4. **Infrastructure** + - No Docker configuration + - No database setup (PostgreSQL, MongoDB, etc.) + - No CI/CD pipelines + - No deployment configuration + +5. **Plugin System** + - No plugin architecture + - No import/export implementations + - No lab result converters + +## Project Vision (From introduction.md) + +### Planned Architecture +- **Client-Server Model:** Linux Docker server, web and mobile clients +- **Tech Stack:** + - Backend: Rust + - Web Server: Node.js + - Mobile: Platform-native or cross-platform +- **Security:** End-to-end encryption, data accessible only to user +- **Business Model:** Subscription-based, open-source +- **Privacy:** No corporate data usage, instant data deletion ("nuke option") + +### Planned Features + +#### User Management +- User authentication system +- Person records (distinct from logged-in users) +- Family structure (parent-child, caregiving relationships) + +#### Health Data Tracking +- Lab results storage +- Medication management (shape, schedule, composition) +- Health statistics (weight, height, age over time) +- Medical appointments +- Regular checkups +- Period tracking +- Pregnancy tracking +- Dental records +- Illness records + +#### Phone App Features +- Medication reminders +- QR code scanner for lab results +- Health sensor integration (steps, activity, breathing, sleep, blood pressure, temperature) +- Periodic server sync +- Instant data deletion + +#### Plugin System +- Import/export functionality +- Lab result format converters +- Sensor data adapters + +#### Data Sharing +- Selective data sharing with external users +- Expiring link-based access +- Granular encryption to support partial access + +## Code References +**No code references available - project has not been implemented yet.** + +Only reference: +- `/home/asoliver/desarrollo/normogen/introduction.md:1-82` - Complete project design document + +## Open Questions + +### Immediate Next Steps for Implementation +1. **Version Control:** Initialize Git repository +2. **Project Structure:** Create directory layout for Rust backend, Node.js web server, mobile apps +3. **Technology Choices:** + - Which Rust web framework? (Actix, Axum, Rocket?) + - Which database? (PostgreSQL, MongoDB, SQLite?) + - Encryption libraries and key management approach + - Mobile app framework choice +4. **MVP Definition:** What is the minimal viable product to start with? + +### Architectural Decisions Needed +1. **Encryption Architecture:** How to implement "limited password" access for shared data while maintaining encryption +2. **Plugin System Design:** Define plugin interface and loading mechanism +3. **Data Models:** Design schema for health records, medications, lab results +4. **API Design:** REST vs GraphQL, authentication approach +5. **Mobile Sync Strategy:** Offline-first vs always-online, conflict resolution + +### Development Priority +What should be built first? +- Backend authentication and data models? +- Basic web interface? +- Mobile app with sensor integration? +- Plugin system foundation? + +## Recommendation + +This is a **greenfield project** in the planning phase. Before writing code, the following should be established: + +1. **Set up version control** (Git) +2. **Create project structure** with placeholder directories +3. **Choose specific technologies** (Rust framework, database, encryption libraries) +4. **Define MVP scope** - what features are essential for the first version +5. **Create initial README** with setup instructions and contribution guidelines +6. **Consider starting with backend API** before building clients + +The project vision is clear and well-documented. The next step is to begin implementation. diff --git a/thoughts/research/2026-01-04-1840-normogen-mvp-definition.md b/thoughts/research/2026-01-04-1840-normogen-mvp-definition.md new file mode 100644 index 0000000..946410c --- /dev/null +++ b/thoughts/research/2026-01-04-1840-normogen-mvp-definition.md @@ -0,0 +1,361 @@ +--- +date: 2026-01-04T18:40:30-03:00 +git_commit: N/A (not a git repository) +branch: N/A +repository: normogen +topic: "Normogen MVP Definition - Auth + Basic Health Tracking" +tags: [research, mvp, planning, requirements, open-questions] +status: complete +--- + +# Research: Normogen MVP Definition + +## Research Question +Define the MVP (Minimum Viable Product) scope for Normogen based on stakeholder decision: basic health tracking + authentication. + +## Summary + +**MVP Scope:** Authentication system + Basic health tracking features + +**Critical Decisions Made:** +- MVP will include user authentication and basic health tracking +- All other technical choices remain as open research questions + +--- + +## MVP Requirements + +### 1. Authentication System + +#### Core Features +- User registration and login +- Secure password storage (hashing + salting) +- Session management +- Password reset flow +- Basic API authentication (JWT tokens) + +#### User Model +``` +User +- id: UUID +- email: string (unique) +- password_hash: string +- created_at: timestamp +- updated_at: timestamp +``` + +#### Security Requirements +- HTTPS only for production +- Password requirements enforcement +- Rate limiting on auth endpoints +- Secure session management + +--- + +### 2. Basic Health Tracking + +#### Core Health Metrics +Based on introduction.md and mobile health framework research (see `2026-01-05-mobile-health-frameworks-data.md`): + +**Phase 1 - Manual Entry (MVP):** +**Tracked Metrics:** +- Weight (with timestamp) +- Height (with timestamp) +- Age (calculated from birthdate) + +**Phase 2 - Mobile Integration (Post-MVP):** +Additional metrics available from Apple HealthKit and Google Health Connect: +- **Vitals:** Heart rate, blood pressure, body temperature, respiratory rate, SpO2 +- **Activity:** Steps, distance, active energy/calories +- **Sleep:** Sleep duration and basic stages +- **Body Composition:** Body fat percentage, BMI + +See research document for complete list of 50+ available data types. + +**Data Model (MVP - Phase 1):** +``` +Person +- id: UUID +- user_id: UUID (foreign key to User) +- name: string +- birthdate: date +- created_at: timestamp + +HealthMetric +- id: UUID +- person_id: UUID (foreign key to Person) +- metric_type: enum (weight, height) +- value: decimal +- unit: string (kg, cm, etc.) +- recorded_at: timestamp +- created_at: timestamp +``` + +**Data Model (Phase 2 - Mobile Integration):** +``` +-- Additional columns for mobile health framework integration +HealthMetric +- metric_source: enum (manual, healthkit, healthconnect, device) +- source_device_id: string (e.g., "com.apple.health.Health") +- accuracy: decimal (sensor accuracy 0.0-1.0) +- metadata: JSONB (platform-specific data) + +-- New tables for sync tracking +health_metric_sources (platform, device_name, sync timestamps) +sync_history (import records, conflicts, errors) +``` + +#### Features (Phase 1 - MVP) +- Manual entry of weight and height +- View health metric history +- Basic chart/visualization of metrics over time +- Multiple person profiles (e.g., tracking children's data) + +#### Features (Phase 2 - Mobile Integration) +- Automatic sync from Apple HealthKit (iOS) +- Automatic sync from Google Health Connect (Android) +- Background sync every 15-30 minutes +- Historical data import (last 30 days) +- Support for 50+ health data types +- Conflict resolution when same metric from multiple sources + +--- + +## Out of Scope for MVP + +Features from introduction.md that are **NOT** in MVP: + +### Not Included (Future Phases) +- Lab results storage +- Medication tracking and reminders +- Medical appointments +- Period tracking +- Pregnancy tracking +- Dental information +- Illness records +- Phone app features (pill reminders, QR scanner, sensors) +- Plugin system +- Data sharing with external users +- Advanced encryption for partial access +- Mobile apps (MVP will be web-only) + +--- + +## Technical Architecture for MVP + +### Backend (Rust) +**Still needs research:** +- Web framework choice (Actix, Axum, Rocket) +- Database selection (PostgreSQL, MongoDB, SQLite) +- ORM/database library choice +- Authentication library selection + +### Frontend (Node.js Web) +**Still needs research:** +- Frontend framework (React, Vue, Svelte, plain JS) +- UI component library +- State management approach +- Build tool choice + +### Database Schema (MVP) +```sql +-- Users table +CREATE TABLE users ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + email VARCHAR(255) UNIQUE NOT NULL, + password_hash VARCHAR(255) NOT NULL, + created_at TIMESTAMP DEFAULT NOW(), + updated_at TIMESTAMP DEFAULT NOW() +); + +-- Persons table (for multi-person tracking) +CREATE TABLE persons ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + name VARCHAR(255) NOT NULL, + birthdate DATE, + created_at TIMESTAMP DEFAULT NOW() +); + +-- Health metrics table +CREATE TABLE health_metrics ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + person_id UUID NOT NULL REFERENCES persons(id) ON DELETE CASCADE, + metric_type VARCHAR(50) NOT NULL, -- 'weight', 'height' + value DECIMAL(10, 2) NOT NULL, + unit VARCHAR(20) NOT NULL, -- 'kg', 'cm', 'lbs', 'in' + recorded_at TIMESTAMP NOT NULL, + created_at TIMESTAMP DEFAULT NOW() +); + +-- Indexes for performance +CREATE INDEX idx_health_metrics_person ON health_metrics(person_id); +CREATE INDEX idx_health_metrics_type ON health_metrics(metric_type); +CREATE INDEX idx_health_metrics_recorded ON health_metrics(recorded_at DESC); +``` + +--- + +## API Endpoints (MVP) + +### Authentication +``` +POST /api/auth/register - Register new user +POST /api/auth/login - Login user +POST /api/auth/logout - Logout user +POST /api/auth/refresh - Refresh JWT token +POST /api/auth/forgot-password - Initiate password reset +POST /api/auth/reset-password - Complete password reset +``` + +### Persons +``` +GET /api/persons - List all persons for current user +POST /api/persons - Create new person profile +GET /api/persons/:id - Get person details +PUT /api/persons/:id - Update person details +DELETE /api/persons/:id - Delete person profile +``` + +### Health Metrics +``` +GET /api/persons/:id/metrics - Get all metrics for a person +POST /api/persons/:id/metrics - Add new metric +GET /api/persons/:id/metrics/:type - Get metrics by type (weight/height) +DELETE /api/persons/:id/metrics/:metricId - Delete a metric entry +``` + +--- + +## User Stories (MVP) + +### Authentication +1. As a new user, I can register with email and password +2. As a registered user, I can login with my credentials +3. As a logged-in user, I can logout securely +4. As a user who forgot their password, I can reset it via email + +### Health Tracking +5. As a user, I can create profiles for myself and family members +6. As a user, I can record weight for any person in my account +7. As a user, I can record height for any person in my account +8. As a user, I can view a history of weight/height changes over time +9. As a user, I can see a simple chart showing weight trends + +--- + +## MVP Success Criteria + +### Functional Requirements +- [ ] User can register and login +- [ ] User can create multiple person profiles +- [ ] User can add weight and height measurements +- [ ] User can view historical data in a list +- [ ] User can see basic trend visualization +- [ ] Data persists across sessions +- [ ] User can delete their own data + +### Non-Functional Requirements +- [ ] All passwords are hashed (never stored plaintext) +- [ ] API is secured with authentication on all endpoints +- [ ] Responsive web interface works on mobile browsers +- [ ] Application can handle 1000+ users +- [ ] Database queries complete in <100ms +- [ ] API response time <200ms for 95% of requests + +### Security Requirements +- [ ] HTTPS in production +- [ ] SQL injection prevention +- [ ] XSS protection +- [ ] CSRF protection +- [ ] Input validation on all endpoints +- [ ] Rate limiting on auth endpoints + +--- + +## Open Questions Requiring Further Research + +### Priority 1 (Blocking for MVP) +1. **Rust Web Framework** + - Options: Actix, Axum, Rocket + - Criteria: Performance, ecosystem, learning curve, async support + - Research needed: Benchmark comparison, community adoption + +2. **Database Selection** + - Options: PostgreSQL, MongoDB, SQLite + - Criteria: Query complexity, scaling needs, deployment simplicity + - Research needed: Data modeling comparison, hosting costs + +3. **Authentication Library** + - Options: Custom JWT implementation, existing auth crates + - Criteria: Security audit history, maintenance status + - Research needed: Available crate reviews + +4. **Frontend Framework** + - Options: React, Vue, Svelte, plain JavaScript + - Criteria: Bundle size, learning curve, ecosystem + - Research needed: Performance comparison for simple apps + +### Priority 2 (Important but Not Blocking) +5. **ORM vs Raw SQL** + - Options: Diesel, SeaORM, sqlx, raw SQL + - Research needed: Type safety vs flexibility tradeoff + +6. **Testing Framework** + - Unit tests, integration tests, E2E tests + - Research needed: Best practices for Rust + web testing + +7. **Deployment Strategy** + - Docker setup, hosting provider (AWS, DigitalOcean, Railway?) + - Research needed: Cost comparison, ease of deployment + +8. **UI Component Library** + - Material UI, Tailwind, Chakra UI, custom CSS + - Research needed: Speed of development for MVP + +### Priority 3 (Nice to Have) +9. **Monitoring & Logging** + - Application performance monitoring + - Error tracking (Sentry, etc.) + +10. **CI/CD Pipeline** + - GitHub Actions, GitLab CI, etc. + - Automated testing, deployment automation + +--- + +## Next Steps + +1. **Research Priority 1 questions** (Rust framework, database, auth library, frontend) +2. **Initialize Git repository** +3. **Create project structure** with chosen tech stack +4. **Implement authentication system** (register, login, JWT) +5. **Design and implement database schema** for users, persons, health metrics +6. **Build basic CRUD API** for persons and metrics +7. **Create simple web frontend** for auth and health tracking +8. **Add basic chart visualization** for trends +9. **Test end-to-end user flows** +10. **Deploy MVP** + +--- + +## File References + +**Design Document:** +- `/home/asoliver/desarrollo/normogen/introduction.md:1-82` - Complete project vision + +**Research Document:** +- `/home/asoliver/desarrollo/normogen/thoughts/research/2026-01-04-1739-normogen-codebase-documentation.md` - Initial codebase assessment + +**This Document:** +- `/home/asoliver/desarrollo/normogen/thoughts/research/2026-01-04-1840-normogen-mvp-definition.md` + +--- + +## Notes + +- MVP is intentionally simple to validate core concepts +- Future phases will add features from introduction.md +- Plugin system and advanced encryption deferred to post-MVP +- Mobile apps deferred to post-MVP (web-only for now) +- Focus on getting working code into users' hands quickly diff --git a/thoughts/research/2026-01-05-RESEARCH-SUMMARY.md b/thoughts/research/2026-01-05-RESEARCH-SUMMARY.md new file mode 100644 index 0000000..43dd4c4 --- /dev/null +++ b/thoughts/research/2026-01-05-RESEARCH-SUMMARY.md @@ -0,0 +1,258 @@ +# Normogen Research Summary + +**Date:** 2026-01-05 +**Status:** Research Complete, Ready for Implementation Planning + +--- + +## Executive Summary + +The Normogen project has been researched and scoped. The project is currently in the **conceptual phase** with only a design document (`introduction.md`). The MVP has been defined and technical research has been completed for mobile health framework integration. + +**Key Decisions:** +1. **MVP Scope:** Authentication + Basic Health Tracking (weight, height, manual entry) +2. **Phase 2:** Mobile app with Apple HealthKit & Google Health Connect integration +3. **Available Health Data:** 50+ data types from both mobile platforms + +--- + +## Research Documents Created + +### 1. Initial Codebase Assessment +**File:** `thoughts/research/2026-01-04-1739-normogen-codebase-documentation.md` + +**Key Findings:** +- Project is pre-implementation (only design document exists) +- No source code, configuration, or project structure +- Comprehensive vision in `introduction.md` + +**Recommendation:** +- Initialize Git repository +- Create project structure +- Begin MVP implementation + +--- + +### 2. MVP Definition +**File:** `thoughts/research/2026-01-04-1840-normogen-mvp-definition.md` + +**MVP Scope (Phase 1):** +- **Authentication:** Register, login, password reset, JWT tokens +- **Health Tracking:** Manual entry for weight and height +- **Multi-person:** Support for family members (children, elderly care) +- **Visualization:** Basic charts for trends +- **Platform:** Web-only (responsive) + +**MVP Success Criteria:** +- Users can register and login +- Create person profiles +- Add weight/height measurements +- View historical data with charts +- Data persists securely + +**Out of Scope (Future Phases):** +- Lab results, medications, appointments +- Period/pregnancy tracking +- Mobile apps +- Plugin system +- Advanced encryption for data sharing + +--- + +### 3. Mobile Health Frameworks Research +**File:** `thoughts/research/2026-01-05-mobile-health-frameworks-data.md` + +**Comprehensive Data Available (50+ types):** + +**Apple HealthKit (iOS):** +- Body: Weight, height, BMI, body fat, lean mass +- Vitals: Heart rate, blood pressure, temperature, SpO2, glucose, respiratory rate +- Activity: Steps, distance, active energy, workouts +- Sleep: Duration, stages (REM, light, deep) +- Nutrition: Calories, macros, vitamins, hydration +- Reproductive: Menstrual flow, ovulation, basal temp +- Medical: Lab results, medications, allergies, conditions +- Apple Watch: ECG, AFib, fall detection + +**Google Health Connect (Android):** +- Body: Weight, height, body fat, BMR, bone mass +- Vitals: Heart rate, HRV, blood pressure, SpO2, temperature +- Activity: Steps, distance, exercise sessions, swimming +- Sleep: Sessions, stages, latency +- Nutrition: Hydration, calories, macros +- Cycle tracking: Menstruation, ovulation, cervical mucus + +**Common to Both (15 core types):** +Weight, height, steps, distance, heart rate, blood pressure, sleep, active energy, temperature, glucose, SpO2, respiratory rate, nutrition, exercise, body fat + +**Integration Complexity:** +- iOS (HealthKit): โญโญโญ Medium +- Android (Health Connect): โญโญโญโญ Medium-High + +**Timeline:** +- Phase 1 (Manual Entry): 4 weeks +- Phase 2 (Mobile Foundation): 4 weeks +- Phase 3 (Health Framework Integration): 4 weeks +- Phase 4 (Expanded Data Types): 4 weeks + +**Total to Full Mobile Integration:** ~16 weeks + +--- + +## Updated MVP Definition + +### Phase 1: Manual Entry (MVP) - 4 weeks +- Web-based authentication +- Manual weight/height entry +- Basic visualization +- Multi-person profiles + +### Phase 2: Mobile Foundation - 4 weeks +- iOS and Android apps +- Mobile authentication +- Manual data entry on mobile +- Server sync + +### Phase 3: Health Framework Integration - 4 weeks +- Apple HealthKit integration +- Google Health Connect integration +- Top 5 data types: weight, heart rate, blood pressure, sleep, steps +- Background sync (15-30 min intervals) +- Historical data import (30 days) + +### Phase 4: Expanded Data Types - 4 weeks +- All 50+ data types +- Exercise tracking +- Nutrition tracking +- Advanced sleep analysis +- Menstrual cycle tracking + +--- + +## Data Model + +### MVP (Phase 1) +```sql +users (id, email, password_hash, timestamps) +persons (id, user_id, name, birthdate) +health_metrics (id, person_id, metric_type, value, unit, recorded_at) +``` + +### Phase 2 (Mobile Integration) +```sql +-- Enhanced health_metrics +ALTER TABLE health_metrics ADD COLUMN metric_source; +ALTER TABLE health_metrics ADD COLUMN source_device_id; +ALTER TABLE health_metrics ADD COLUMN accuracy; +ALTER TABLE health_metrics ADD COLUMN metadata JSONB; + +-- New tables +health_metric_sources (platform, device_name, sync timestamps) +sync_history (import records, conflicts, errors) +``` + +--- + +## Open Technical Questions (Priority 1) + +### Blocking for MVP Start: + +1. **Rust Web Framework** + - Actix vs Axum vs Rocket + - Need: Performance comparison, ecosystem maturity + +2. **Database Selection** + - PostgreSQL vs MongoDB vs SQLite + - Need: Data modeling approach, hosting costs + +3. **Authentication Library** + - Custom JWT vs existing crates + - Need: Security audit status + +4. **Frontend Framework** + - React vs Vue vs Svelte vs plain JS + - Need: Bundle size, learning curve + +--- + +## Security & Privacy Requirements + +### Data Protection: +- **Encryption at rest** (database level) +- **Encryption in transit** (TLS 1.3) +- **No plaintext passwords** (bcrypt/scrypt/Argon2) +- **Per-user encryption keys** + +### User Privacy: +- **Granular permissions** (user chooses what to share) +- **Easy data deletion** ("nuke option") +- **No third-party data sharing** +- **Transparent data usage** + +### Compliance: +- GDPR (Europe) +- HIPAA (if handling PHI in US) +- CCPA (California) +- App Store & Play Store policies + +--- + +## Recommended Next Steps + +### Immediate (This Week): +1. **Research Priority 1 questions** above +2. **Initialize Git repository** +3. **Choose tech stack** based on research + +### Short-term (Month 1): +4. **Create project structure** +5. **Implement authentication** (register, login, JWT) +6. **Design database schema** +7. **Build basic CRUD API** for persons and metrics + +### Medium-term (Month 2): +8. **Create web frontend** (auth + health tracking) +9. **Add chart visualization** +10. **Test end-to-end flows** +11. **Deploy MVP** + +### Long-term (Months 3-4): +12. **Build mobile apps** (iOS + Android) +13. **Integrate HealthKit & Health Connect** +14. **Implement background sync** + +--- + +## File Structure + +``` +normogen/ +โ”œโ”€โ”€ introduction.md # Project vision +โ””โ”€โ”€ thoughts/ + โ””โ”€โ”€ research/ + โ”œโ”€โ”€ 2026-01-04-1739-normogen-codebase-documentation.md + โ”œโ”€โ”€ 2026-01-04-1840-normogen-mvp-definition.md + โ””โ”€โ”€ 2026-01-05-mobile-health-frameworks-data.md +``` + +--- + +## Key Takeaways + +โœ… **MVP is clearly defined** - Manual health tracking with authentication +โœ… **Mobile path is clear** - HealthKit & Health Connect with 50+ data types +โœ… **Timeline is realistic** - 4 weeks MVP, 16 weeks to full mobile +โœ… **Technical questions are identified** - Ready for research/decision + +โš ๏ธ **Action needed:** Choose Rust framework, database, and frontend stack before starting implementation + +๐Ÿš€ **Ready to proceed:** All research complete, can begin implementation planning + +--- + +## Contact & Questions + +All research documents are available in `thoughts/research/`. +Review the three main research documents for detailed findings. + +**Ready to start implementation?** Begin by researching the Priority 1 technical questions above, then proceed with Git initialization and project structure. diff --git a/thoughts/research/2026-01-05-health-frameworks-research-plan.md b/thoughts/research/2026-01-05-health-frameworks-research-plan.md new file mode 100644 index 0000000..cdaf26a --- /dev/null +++ b/thoughts/research/2026-01-05-health-frameworks-research-plan.md @@ -0,0 +1,60 @@ +# Research Plan: Health Data from Phone Frameworks + +## Objective +Research what health data can be accessed from mobile health frameworks with proper permissions: +- **Apple HealthKit** (iOS) +- **Google Health Connect** (Android) +- **Samsung Health SDK** (optional - additional coverage) + +## Research Areas + +### 1. Apple HealthKit (iOS) +Research questions: +- What health data types are available? +- What permissions are required for each data type? +- What are the user privacy requirements? +- How to read historical vs real-time data? +- What metadata is available (timestamps, device info, units)? +- Any special requirements for medical data vs fitness data? + +### 2. Google Health Connect (Android) +Research questions: +- What health data types are supported? +- What permissions model does Health Connect use? +- How does it differ from the old Google Fit API? +- What are the integration requirements? +- Can it read data from third-party apps (Fitbit, Strava, etc.)? +- What metadata is available? + +### 3. Data Type Comparison +Compare both frameworks: +- Which data types are available on both platforms? +- Which are platform-specific? +- Unit differences and conversions needed +- Timestamp precision differences +- Data granularity differences + +### 4. Technical Implementation Requirements +Research: +- SDK/library requirements for both platforms +- Background data sync capabilities +- Battery usage considerations +- Data storage strategies (local cache vs direct sync) +- Error handling for missing permissions + +## Expected Deliverables +1. Complete list of available health data types for each platform +2. Permission requirements mapping +3. Comparison matrix (iOS vs Android) +4. Recommended data model additions for MVP +5. Integration complexity assessment +6. Privacy and security considerations + +## Search Strategy +Will research: +- Official Apple HealthKit documentation +- Official Google Health Connect documentation +- Developer guides and best practices +- Data type reference documentation +- Permission and privacy requirements +- Code examples and integration patterns diff --git a/thoughts/research/2026-01-05-mobile-health-frameworks-data.md b/thoughts/research/2026-01-05-mobile-health-frameworks-data.md new file mode 100644 index 0000000..b9794a5 --- /dev/null +++ b/thoughts/research/2026-01-05-mobile-health-frameworks-data.md @@ -0,0 +1,635 @@ +--- +date: 2026-01-05T20:27:17-03:00 +git_commit: N/A (not a git repository) +branch: N/A +repository: normogen +topic: "Mobile Health Frameworks - Available Data Types" +tags: [research, healthkit, health-connect, mobile-integration, data-types] +status: complete +--- + +# Research: Mobile Health Frameworks Data Availability + +## Research Question +What health data can be accessed from mobile phone health frameworks (Apple HealthKit and Google Health Connect) with proper application permissions? + +## Summary + +**Key Finding:** Both iOS and Android provide comprehensive access to health data through their respective frameworks (HealthKit and Health Connect). With proper permissions, applications can access **50+ different health data types** including body measurements, vitals, activity, sleep, nutrition, and reproductive health. + +**Platform Coverage:** +- **Apple HealthKit (iOS):** 9 major categories, 50+ data types +- **Google Health Connect (Android):** 8 major categories, 45+ data types +- **Common to Both:** ~15 core data types with overlap + +**User Control:** Both platforms require explicit user permission for each data category, with granular controls and easy revocation. + +--- + +## Apple HealthKit (iOS) + +### Data Categories Available + +#### 1. Body Measurements +With basic permissions: +- **Weight** - kg, lbs +- **Height** - cm, in, ft +- **Body Mass Index (BMI)** - calculated +- **Body Fat Percentage** - %age +- **Lean Body Mass** - kg, lbs + +#### 2. Vitals (Requires Special Permissions) +- **Heart Rate** - beats per minute (BPM) +- **Resting Heart Rate** - BPM +- **Blood Pressure** - systolic/diastolic (mmHg) +- **Body Temperature** - ยฐC, ยฐF +- **Respiratory Rate** - breaths per minute +- **Oxygen Saturation (SpO2)** - percentage +- **Blood Glucose** - mg/dL, mmol/L + +#### 3. Fitness & Activity +- **Step Count** - daily/total steps +- **Distance Walking/Running** - km, mi +- **Flights Climbed** - count +- **Active Energy Burned** - kcal +- **Basal Energy Burned** - kcal/day +- **Exercise Duration** - minutes/hours +- **Workouts** - type, duration, calories, route + +#### 4. Sleep Analysis +- **Sleep Duration** - total time asleep +- **Time in Bed** - total time in bed +- **Sleep Stages** - in bed, asleep, awake +- **Sleep Quality** - REM, light, deep sleep + +#### 5. Mobility +- **Walking Speed** - m/s +- **Walking Asymmetry** - percentage +- **Walking Steadiness** - score +- **Step Length** - cm, in + +#### 6. Nutrition +- **Dietary Energy** - calories +- **Macronutrients** - carbs, protein, fat (total, saturated, unsaturated) +- **Fiber** - grams +- **Sugar** - grams +- **Sodium** - milligrams +- **Water Intake** - liters, cups, ounces +- **Vitamins & Minerals** - various (A, C, D, iron, calcium, etc.) + +#### 7. Reproductive Health +- **Menstrual Flow** - light, medium, heavy +- **Basal Body Temperature** - ยฐC, ยฐF +- **Cervical Mucus Quality** - type and amount +- **Ovulation Test Result** - positive/negative +- **Sexual Activity** - protected/unprotected +- **Spotting** - yes/no + +#### 8. Medical Records & Labs (Clinical Data) +- **Allergy Records** - allergen, severity, reaction +- **Condition Records** - diagnosis, status +- **Immunization Records** - vaccine, date +- **Lab Result Records** - test name, result, unit, reference range +- **Medication Records** - name, dosage, frequency +- **Procedure Records** - procedure, date, outcome +- **Vital Signs Records** - clinical measurements + +#### 9. Apple Watch Specific Data +- **ECG Results** - ECG readings and classifications +- **AFib Detection** - atrial fibrillation notifications +- **Fall Detection** - fall events +- **Noise Levels** - environmental sound exposure +- **Headphone Audio Levels** - audio exposure + +### Permission Requirements + +**Info.plist Required Entries:** +```xml +NSHealthShareUsageDescription +We need access to your health data to track and analyze your wellness metrics. + +NSHealthUpdateUsageDescription +We need permission to save health data to your Health app. +``` + +**Entitlements Required:** +- HealthKit capability in Xcode project settings +- Special entitlements for clinical data access + +**User Permissions:** +- User must explicitly grant permission for each data category +- Prompts shown at first access to each category +- User can revoke permissions in Settings > Health > Data Access & Devices +- Clinical data requires additional user consent + +**Metadata Available:** +- **Timestamp:** Start and end time (millisecond precision) +- **Device:** Source device (iPhone, Apple Watch, third-party app) +- **Units:** Always included with proper conversions +- **Provenance:** Which app/device provided the data +- **Accuracy:** For sensor-based measurements +- **User Notes:** Optional user-created annotations + +--- + +## Google Health Connect (Android) + +### Data Types Available + +#### 1. Activity & Exercise +- **Steps** - count +- **Distance** - meters, kilometers, miles +- **Floors** - count +- **Elevation** - meters, feet +- **Exercise Sessions** - type (running, walking, cycling, etc.), duration, calories +- **Swimming** - strokes, laps, distance +- **Wheelchair Pushes** - count +- **Golf Swings** - count (for supported apps) + +#### 2. Body Measurements +- **Weight** - kg, lbs +- **Height** - meters, centimeters, feet, inches +- **Body Fat** - percentage +- **Basal Metabolic Rate** - kcal/day +- **Body Water Mass** - kg +- **Bone Mass** - kg +- **Lean Body Mass** - kg + +#### 3. Vitals +- **Heart Rate** - BPM +- **Resting Heart Rate** - BPM +- **Heart Rate Variability** - milliseconds +- **Blood Pressure** - systolic/diastolic in mmHg +- **Oxygen Saturation (SpO2)** - percentage +- **Body Temperature** - ยฐC, ยฐF +- **Respiratory Rate** - breaths/minute + +#### 4. Sleep +- **Sleep Sessions** - start time, end time, total duration +- **Sleep Stages** - awake, REM, light, deep sleep with durations +- **Sleep Latency** - time to fall asleep + +#### 5. Nutrition +- **Hydration** - volume in mL, oz, cups +- **Nutrition** - calories, macronutrients, micronutrients +- **Meal Information** - meal type (breakfast, lunch, dinner, snack) + +#### 6. Cycle Tracking +- **Menstruation Flow** - flow amount and type +- **Menstruation Period** - start and end dates +- **Ovulation** - positive, negative, test result +- **Cervical Mucus** - type and quantity +- **Sexual Activity** - protection status +- **Spotting** - yes/no + +#### 7. Clinical Data +- **Blood Glucose** - mg/dL, mmol/L +- **Lab Test Results** - similar to Apple HealthKit + +#### 8. Physical Activity Details +- **Exercise Type** - running, walking, cycling, swimming, etc. +- **Exercise Duration** - time in minutes/hours +- **Exercise Calories** - kcal burned +- **Exercise Route** - GPS data path (if available) + +### Permission Requirements + +**AndroidManifest.xml:** +```xml + + +``` + +**Runtime Permissions:** +- Granular permission requests per data type +- User approves each category individually +- Health Connect app must be installed on device +- User can manage permissions in Health Connect app + +**Requirements:** +- Android API level 34+ (Android 14) recommended +- Health Connect Jetpack library +- Google Play Services (on Play Store devices) +- User consent for each data type read + +**Metadata Available:** +- **Timestamps:** Start and end time (millisecond precision) +- **Device/Source:** Which app or device provided data +- **Accuracy:** Measurement precision +- **Units:** Always included +- **Entry Method:** Manual vs automatic/sensor + +--- + +## Cross-Platform Comparison + +### Common Data Types (Both Platforms) +These data types are available on both iOS and Android with consistent structure: + +| Data Type | Apple HealthKit | Google Health Connect | Notes | +|-----------|----------------|----------------------|-------| +| **Weight** | โœ“ | โœ“ | Both support kg/lbs | +| **Height** | โœ“ | โœ“ | Both support metric/imperial | +| **Steps** | โœ“ | โœ“ | Daily count and historical | +| **Distance** | โœ“ | โœ“ | Walking/running distance | +| **Heart Rate** | โœ“ | โœ“ | BPM, resting HR, HRV | +| **Blood Pressure** | โœ“ | โœ“ | Systolic/diastolic | +| **Sleep** | โœ“ | โœ“ | Duration, stages | +| **Active Energy** | โœ“ | โœ“ | Calories burned | +| **Body Temperature** | โœ“ | โœ“ | ยฐC/ยฐF | +| **Blood Glucose** | โœ“ | โœ“ | mg/dL, mmol/L | +| **Respiratory Rate** | โœ“ | โœ“ | Breaths per minute | +| **SpO2** | โœ“ | โœ“ | Oxygen saturation | +| **Nutrition** | โœ“ | โœ“ | Calories, macros, hydration | +| **Exercise** | โœ“ | โœ“ | Type, duration, calories | +| **Body Fat %** | โœ“ | โœ“ | Percentage | + +### Platform-Specific Features + +**Apple-Only:** +- ECG measurements (Apple Watch) +- Atrial fibrillation detection +- Walking steadiness/asymmetry metrics +- Environmental sound levels +- More detailed mobility analysis +- Integration with Apple ecosystem (Watch, iPad, Mac) + +**Android-Only:** +- More granular exercise types +- Broader device ecosystem (Samsung, Fitbit, Garmin, etc.) +- More flexible third-party app integrations +- Earlier API access for some features + +### Unit Conversions +Both platforms handle units automatically: + +| Measurement | iOS Units | Android Units | Notes | +|------------|-----------|---------------|-------| +| Weight | kg, lbs | kg, lbs | 1 kg = 2.20462 lbs | +| Height | cm, in | cm, in, ft+in | 1 in = 2.54 cm | +| Temperature | ยฐC, ยฐF | ยฐC, ยฐF | ยฐF = (ยฐC ร— 9/5) + 32 | +| Glucose | mg/dL, mmol/L | mg/dL, mmol/L | mg/dL = mmol/L ร— 18.02 | +| Distance | km, mi | km, mi | 1 mi = 1.60934 km | + +### Time Precision +- **Apple:** Millisecond precision (Unix timestamp) +- **Android:** Millisecond precision (Unix timestamp) +- **Both:** Support historical queries with date ranges +- **Best Practice:** Store all timestamps in UTC on server + +--- + +## Integration Complexity Assessment + +### Apple HealthKit + +**Complexity:** โญโญโญ (Medium - 3/5) + +**Advantages:** +- Mature, stable framework (since iOS 8) +- Excellent documentation (with Apple Developer account) +- Strong type safety with Swift +- Consistent API across iOS versions +- Good debugging tools in Xcode +- Deep integration with Apple Watch + +**Challenges:** +- Requires Mac for development +- Requires Xcode +- Simulator has limited HealthKit support +- Testing on physical device required +- Some features require Apple Developer Program ($99/year) + +**Development Requirements:** +- macOS with Xcode +- iOS deployment target: iOS 13+ (for full features) +- Swift or Objective-C +- HealthKit framework entitlement + +### Google Health Connect + +**Complexity:** โญโญโญโญ (Medium-High - 4/5) + +**Advantages:** +- Modern, actively developed framework +- Centralizes data from all health apps +- Cross-app data sharing +- User privacy controls +- Works on wide range of devices + +**Challenges:** +- Newer framework (introduced 2023, replacing Google Fit) +- Documentation still evolving +- Android version compatibility (API 34+ recommended) +- Device fragmentation (different OEM implementations) +- Health Connect app must be installed separately +- More complex testing matrix (device/OS combinations) + +**Development Requirements:** +- Android Studio +- Minimum SDK: API 26 (Android 8) with compatibility layer +- Recommended SDK: API 34 (Android 14) for full features +- Kotlin or Java +- Health Connect Jetpack library +- Google Play Services (optional but recommended) + +--- + +## Recommended MVP Integration Strategy + +### Phase 1: Manual Entry (Current MVP Scope) +**Timeline:** Week 1-4 +**Features:** +- Manual entry of weight, height +- Manual entry of basic vitals (heart rate, blood pressure, temperature) +- Web-based interface only +- No mobile integration yet + +### Phase 2: Mobile Foundation +**Timeline:** Week 5-8 +**Features:** +- Build basic iOS and Android apps +- Implement authentication +- Manual data entry on mobile +- Sync with server + +### Phase 3: Health Framework Integration +**Timeline:** Week 9-12 +**Features:** +- Implement HealthKit on iOS +- Implement Health Connect on Android +- Support top 5 most important data types: + 1. Weight + 2. Heart Rate + 3. Blood Pressure + 4. Sleep (duration) + 5. Steps (count) +- Background sync every 15-30 minutes +- Historical data import (last 30 days) + +### Phase 4: Expanded Data Types +**Timeline:** Week 13-16 +**Features:** +- Add all common data types +- Support for exercise tracking +- Nutrition tracking +- Advanced sleep analysis +- Menstrual cycle tracking + +--- + +## Data Model Recommendations + +### Enhanced health_metrics Table + +```sql +ALTER TABLE health_metrics ADD COLUMN metric_source VARCHAR(50) + CHECK (metric_source IN ('manual', 'healthkit', 'healthconnect', 'third_party_device', 'unknown')); + +ALTER TABLE health_metrics ADD COLUMN source_device_id VARCHAR(255); + -- Stores identifier for source device/app (e.g., "com.apple.health.Health", "com.fitbit.FitbitMobile") + +ALTER TABLE health_metrics ADD COLUMN accuracy DECIMAL(5,2); + -- Sensor accuracy for automatic measurements (0.0-1.0, where 1.0 = perfect) + +ALTER TABLE health_metrics ADD COLUMN metadata JSONB; + -- Flexible storage for platform-specific data: + -- iOS: {"HKDevice": "iPhone14,2", "HKSource": "com.apple.Health"} + -- Android: {"device": "Samsung Galaxy S21", "package": "com.sec.android.app.health"} +``` + +### New Table: health_metric_sources +```sql +CREATE TABLE health_metric_sources ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + platform VARCHAR(20) NOT NULL, -- 'ios' or 'android' + device_name VARCHAR(255), + source_bundle_id VARCHAR(255), -- App/package ID + first_sync TIMESTAMP DEFAULT NOW(), + last_sync TIMESTAMP DEFAULT NOW(), + is_active BOOLEAN DEFAULT TRUE, + + UNIQUE(user_id, platform, source_bundle_id) +); + +CREATE INDEX idx_metric_sources_user ON health_metric_sources(user_id); +``` + +### New Table: sync_history +```sql +CREATE TABLE sync_history ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + platform VARCHAR(20) NOT NULL, + sync_type VARCHAR(50) NOT NULL, -- 'initial', 'incremental', 'manual' + records_imported INTEGER DEFAULT 0, + records_failed INTEGER DEFAULT 0, + sync_duration_seconds INTEGER, + error_message TEXT, + synced_from TIMESTAMP, + synced_to TIMESTAMP, + created_at TIMESTAMP DEFAULT NOW() +); + +CREATE INDEX idx_sync_history_user ON sync_history(user_id, created_at DESC); +``` + +--- + +## Sync Strategy + +### Initial Sync (First Connection) +When user first connects health framework: +1. Request last 30 days of data (common window) +2. Import in batches to avoid overwhelming server +3. Show progress to user +4. Handle errors gracefully +5. Store sync timestamp for incremental updates + +### Incremental Sync (Background) +Every 15-30 minutes: +1. Query for new data since last sync +2. Send new records to server +3. Handle conflicts (same metric, multiple sources) +4. Update last sync timestamp + +### Conflict Resolution Strategy +When same metric type exists from multiple sources: +1. **Automatic Entry** (sensor/device) > **Manual Entry** +2. **More Recent** > **Older** (for time-series data) +3. **More Accurate** > **Less Accurate** (based on metadata) +4. **User Preference** (if user sets preferred source) + +### Battery Optimization +- Limit sync frequency when battery < 20% +- Use WorkManager (Android) and Background Tasks (iOS) +- Batch requests to minimize wake-ups +- Sync only when on Wi-Fi (user preference) +- Respect battery saver mode + +--- + +## Security & Privacy Considerations + +### Data Transmission +- **Always use HTTPS** (TLS 1.3) +- **Encrypt sensitive data** at REST on server +- **Never store credentials** on device (use tokens) +- **Certificate pinning** for API calls + +### Data Storage +- **Encrypt at rest** using database encryption +- **Separate encryption keys** per user +- **No plaintext passwords** (bcrypt/scrypt/Argon2) +- **Secure key derivation** for data access + +### User Privacy +- **Clear permission requests** explaining why data is needed +- **Granular controls** - user chooses what to share +- **Easy data deletion** - "nuke option" from intro.md +- **No data sharing** with third parties without explicit consent +- **Transparent data usage** - show user what's stored + +### Compliance +- **GDPR** (Europe) +- **HIPAA** (if handling protected health information in US) +- **CCPA** (California) +- **App Store Review Guidelines** (Apple) +- **Google Play Policy** (Android) + +--- + +## Open Questions & Further Research + +### Priority 1 (MVP Blocking) +1. **Conflict Resolution Algorithm** + - What if user manually enters weight but scale also sent data? + - Need comprehensive conflict resolution policy + +2. **Background Sync Optimization** + - Optimal sync interval for battery vs data freshness + - How to handle offline scenarios + +3. **Data Retention Policy** + - How long to keep historical data? + - Should old data be archived or deleted? + +### Priority 2 (Post-MVP) +4. **Third-Party Device Integration** + - Fitbit, Garmin, Oura Ring, Whoop, etc. + - Each requires separate API integration + +5. **Data Export Format** + - What format for user downloads? + - JSON, CSV, FHIR (HL7), or custom? + +6. **Advanced Analytics** + - Trends, correlations, predictions + - Privacy-preserving computations? + +7. **Cross-Platform Sync** + - What if user has both iOS and Android devices? + - How to merge data from both? + +### Priority 3 (Future) +8. **Real-Time Monitoring** + - Live heart rate, blood glucose alerts? + - Push notification strategy + +9. **Data Visualization** + - Charts, graphs, heatmaps + - What library to use? + +10. **International Units** + - Automatic unit conversion based on user location? + - Support for medical vs customary units? + +--- + +## Implementation Checklist + +### Pre-Development +- [ ] Finalize data model with source tracking +- [ ] Design conflict resolution algorithm +- [ ] Create API endpoints for bulk data import +- [ ] Set up database encryption + +### iOS Development +- [ ] Add HealthKit capability in Xcode +- [ ] Write permission request code +- [ ] Implement HealthKit queries for top 5 data types +- [ ] Implement background sync with BGTaskScheduler +- [ ] Test on physical device (simulator has limited support) + +### Android Development +- [ ] Add Health Connect dependencies +- [ ] Add permissions to AndroidManifest +- [ ] Write permission request code +- [ ] Implement Health Connect queries for top 5 data types +- [ ] Implement background sync with WorkManager +- [ ] Test on multiple Android versions/devices + +### Backend Development +- [ ] Create bulk import API endpoints +- [ ] Implement conflict resolution logic +- [ ] Add sync history tracking +- [ ] Optimize database indexes for time-series queries +- [ ] Implement data deletion endpoint ("nuke") + +### Testing +- [ ] Unit tests for data parsing +- [ ] Integration tests for sync logic +- [ ] Manual testing on physical devices +- [ ] Battery usage profiling +- [ ] Security audit +- [ ] Load testing with thousands of records + +--- + +## Conclusion + +**Feasibility:** โœ… **Highly Feasible** + +Both mobile platforms provide robust, well-documented frameworks for health data access. The integration is straightforward for common data types (weight, height, heart rate, blood pressure, sleep, steps). + +**Recommendation for MVP:** +- Start with **Phase 1** (manual entry) to validate core architecture +- Move to **Phase 2** (mobile apps) for basic platform functionality +- Implement **Phase 3** (health frameworks) with top 5 data types +- Expand in **Phase 4** based on user feedback + +**Timeline Estimate:** +- Phase 1: 4 weeks (manual entry web app) +- Phase 2: 4 weeks (mobile app foundation) +- Phase 3: 4 weeks (health framework integration) +- Phase 4: 4 weeks (expanded data types) + +**Total to Full Mobile Integration:** ~16 weeks (4 months) + +--- + +## References + +### Official Documentation +- [Apple HealthKit Documentation](https://developer.apple.com/documentation/healthkit) +- [Google Health Connect Documentation](https://developer.android.com/health-connect) +- [Apple Human Interface Guidelines - Health](https://developer.apple.com/design/human-interface-guidelines/health) +- [Google Play - Health Apps Policy](https://play.google.com/console/about/health/) + +### Data Type References +- [HealthKit HKObjectType Constants](https://developer.apple.com/documentation/healthkit/hkobjecttype) +- [Health Connect Data Types](https://developer.android.com/reference/kotlin/androidx/health/data/class) +- [Common Data Elements - FHIR](https://hl7.org/fhir/observation.html) + +### Code Examples +- Apple Sample Code: HKWorkoutSession, HKHealthStore +- Android Sample Code: Health Connect Samples on GitHub + +--- + +**Next Steps:** +1. Review this research with stakeholders +2. Prioritize which data types for MVP +3. Choose mobile development framework (React Native vs native) +4. Begin implementation with Phase 1 (manual entry) diff --git a/thoughts/research/2026-01-12-android-health-connect-data-types-research.md b/thoughts/research/2026-01-12-android-health-connect-data-types-research.md new file mode 100644 index 0000000..2c95432 --- /dev/null +++ b/thoughts/research/2026-01-12-android-health-connect-data-types-research.md @@ -0,0 +1,431 @@ +# Android Health Connect - Available Data Types Research + +**Date**: 2026-01-12 +**Platform**: Android Health Connect API +**Source**: https://developer.android.com/health-and-fitness/guides/health-connect/plan/data-types + +--- + +## Overview + +Android Health Connect is a unified API that allows apps to read and write health and fitness data from a central on-device store. It's compatible with Android SDK 28 (Pie) and higher. + +**Key Points**: +- Requires explicit user permissions for each data type +- All data is stored locally on the device +- Apps can read/write data with user consent +- Supports medical records and health data +- Privacy-focused design + +--- + +## Complete Data Types Catalog (41 Types) + +### ๐Ÿƒ Physical Activity & Movement + +| Data Type | Description | Use Case | +|-----------|-------------|----------| +| **StepsRecord** | Step count over time | Daily activity tracking | +| **DistanceRecord** | Distance traveled | Walking/running/cycling distances | +| **FloorsClimbedRecord** | Number of floors climbed | Stair climbing activity | +| **ElevationGainedRecord** | Elevation gained | Hiking/mountain activities | +| **SpeedRecord** | Speed measurement | Running/cycling pace | +| **StepsCadenceRecord** | Steps per minute | Running/cycling cadence | +| **CyclingPedalingCadenceRecord** | Pedal cadence | Cycling performance | +| **WheelchairPushesRecord** | Wheelchair pushes | Accessibility tracking | +| **ExerciseSessionRecord** | Complete workout sessions | Gym/fitness activities | +| **PlannedExerciseSessionRecord** | Scheduled workouts | Workout planning | +| **ActivityIntensityRecord** | Activity intensity levels | Exercise intensity zones | + +--- + +### ๐Ÿ’ช Body Composition & Measurements + +| Data Type | Description | Use Case | +|-----------|-------------|----------| +| **WeightRecord** | Body weight | Weight tracking | +| **HeightRecord** | Height | BMI calculations | +| **BodyFatRecord** | Body fat percentage | Body composition | +| **BodyWaterMassRecord** | Body water mass | Hydration tracking | +| **BoneMassRecord** | Bone mass | Bone health | +| **LeanBodyMassRecord** | Lean muscle mass | Fitness progress | + +--- + +### โค๏ธ Heart & Cardiovascular + +| Data Type | Description | Use Case | +|-----------|-------------|----------| +| **HeartRateRecord** | Real-time heart rate | Heart rate monitoring | +| **RestingHeartRateRecord** | Resting heart rate | Cardiovascular health | +| **HeartRateVariabilityRmssdRecord** | HRV (RMSSD) | Stress/recovery tracking | +| **BloodPressureRecord** | Systolic/diastolic pressure | Hypertension monitoring | +| **RespiratoryRateRecord** | Breaths per minute | Respiratory health | +| **Vo2MaxRecord** | Maximum oxygen uptake | Cardiovascular fitness | +| **OxygenSaturationRecord** | Blood oxygen levels (SpO2) | Oxygen monitoring | + +--- + +### ๐ŸŒก๏ธ Temperature & Metabolism + +| Data Type | Description | Use Case | +|-----------|-------------|----------| +| **BodyTemperatureRecord** | Body temperature | Fever/health monitoring | +| **BasalBodyTemperatureRecord** | Basal body temperature | Fertility tracking | +| **SkinTemperatureRecord** | Skin temperature | Sleep/stress monitoring | +| **BasalMetabolicRateRecord** | BMR | Metabolism tracking | + +--- + +### ๐Ÿ”ฅ Calories & Energy + +| Data Type | Description | Use Case | +|-----------|-------------|----------| +| **ActiveCaloriesBurnedRecord** | Calories from activity | Exercise calorie burn | +| **TotalCaloriesBurnedRecord** | Total daily calories | Complete energy expenditure | + +--- + +### ๐Ÿ’ง Hydration & Nutrition + +| Data Type | Description | Use Case | +|-----------|-------------|----------| +| **HydrationRecord** | Water intake | Hydration tracking | +| **NutritionRecord** | Detailed nutrition data | Diet/macronutrient tracking | + +--- + +### ๐Ÿ’ค Sleep & Mindfulness + +| Data Type | Description | Use Case | +|-----------|-------------|----------| +| **SleepSessionRecord** | Complete sleep sessions | Sleep analysis | +| **MindfulnessSessionRecord** | Meditation/mindfulness | Mental wellness | + +--- + +### ๐Ÿฉธ Women's Health + +| Data Type | Description | Use Case | +|-----------|-------------|----------| +| **MenstruationPeriodRecord** | Menstrual cycle | Period tracking | +| **MenstruationFlowRecord** | Flow intensity | Cycle details | +| **IntermenstrualBleedingRecord** | Spotting between periods | Cycle health | +| **CervicalMucusRecord** | Cervical mucus | Fertility tracking | +| **OvulationTestRecord** | Ovulation test results | Fertility planning | +| **SexualActivityRecord** | Sexual activity logs | Health tracking | + +--- + +### ๐Ÿฉบ Blood & Medical + +| Data Type | Description | Use Case | +|-----------|-------------|----------| +| **BloodGlucoseRecord** | Blood glucose levels | Diabetes management | + +--- + +### โšก Power & Performance + +| Data Type | Description | Use Case | +|-----------|-------------|----------| +| **PowerRecord** | Power output | Cycling/rowing performance | +| **ForceRecord** | Force measurement | Strength training | + +--- + +## Permissions Model + +Each data type requires specific health permissions: + +### Examples of Permission Strings +- `android.permission.health.READ_STEPS` +- `android.permission.health.WRITE_STEPS` +- `android.permission.health.READ_HEART_RATE` +- `android.permission.health.WRITE_HEART_RATE` +- `android.permission.health.READ_BLOOD_PRESSURE` +- `android.permission.health.WRITE_BLOOD_PRESSURE` + +**Important**: Users must grant each permission individually through the Health Connect interface. + +--- + +## Data Structure Format + +Most records follow this structure: +```kotlin +Record( + startTime: Instant, + startZoneOffset: ZoneOffset, + endTime: Instant, + endZoneOffset: ZoneOffset, + metadata: Metadata { + id: String, + dataOrigin: DataOrigin, + lastModifiedTime: Instant, + clientRecordId: String?, + device: Device?, + recordingMethod: RecordingMethod? + } +) +``` + +Example: **BloodPressureRecord** +```kotlin +BloodPressureRecord( + systolic = Pressure.millimetersOfMercury(120.0), + diastolic = Pressure.millimetersOfMercury(80.0), + time = Instant.now(), + zoneOffset = ZoneOffset.UTC, + metadata = Metadata(...) +) +``` + +--- + +## Medical Records (New Feature) + +Health Connect now supports medical records: +- **Medical resource format**: FHIR-based structure +- **Reading medical data**: Requires additional permissions +- **Writing medical data**: Vaccination records, lab results, etc. +- **Data format**: Structured medical records with standardized fields + +### Medical Record Types +- Immunizations +- Lab results +- Vital signs +- Medications +- Allergies +- Conditions +- Procedures + +--- + +## Integration Approaches for Normogen + +### 1. Direct Health Connect Integration (Recommended) +**Pros**: +- Native Android integration +- No third-party dependencies +- Unified API for all data types +- Privacy-preserving (local storage) + +**Cons**: +- Android-only +- Requires Android 9+ (API 28+) +- Need to handle user permissions +- Not available on older Android versions + +**Implementation**: +```kotlin +// Dependency +implementation("androidx.health:health-connect-client:1.1.0-alpha07") + +// Check availability +val healthConnectManager = HealthConnectManager.getOrCreate(context) +if (healthConnectManager.isAvailable) { + // Use Health Connect +} +``` + +### 2. Cross-Platform Wrapper Libraries + +**Example**: Flutter Health Package (`health` package on pub.dev) + +**Supported Data Types** (limited subset): +- Steps +- Heart rate +- Sleep +- Blood oxygen +- Blood pressure +- Weight +- Height +- Active energy burned +- Total energy burned +- Distance +- Water intake +- Nutrition + +**Pros**: +- Cross-platform (iOS & Android) +- Simple API +- Active community + +**Cons**: +- Limited data types +- May not support all Health Connect features +- Dependency on third-party maintenance + +### 3. Hybrid Approach (Recommended for Normogen) + +**Android**: Use native Health Connect API +- Access all 41 data types +- Full permission control +- Medical records support + +**iOS**: Use HealthKit +- Equivalent data types +- Similar permission model + +**Web/PWA**: Web Bluetooth API (limited) +- Connect to BLE devices directly +- Very limited device support + +--- + +## Data Type Mapping to Normogen Features + +| Normogen Feature | Health Connect Data Types | +|-----------------|---------------------------| +| **General Health Stats** | WeightRecord, HeightRecord, BodyFatRecord | +| **Physical Activity** | StepsRecord, DistanceRecord, ExerciseSessionRecord | +| **Heart Monitoring** | HeartRateRecord, RestingHeartRateRecord, HeartRateVariabilityRmssdRecord | +| **Blood Pressure** | BloodPressureRecord | +| **Sleep Tracking** | SleepSessionRecord | +| **Temperature** | BodyTemperatureRecord, BasalBodyTemperatureRecord, SkinTemperatureRecord | +| **Respiration** | RespiratoryRateRecord, OxygenSaturationRecord | +| **Period Tracking** | MenstruationPeriodRecord, MenstruationFlowRecord, CervicalMucusRecord, OvulationTestRecord | +| **Hydration** | HydrationRecord | +| **Nutrition** | NutritionRecord | +| **Blood Glucose** | BloodGlucoseRecord (diabetes) | +| **Lab Results** | Medical records API | +| **Medication** | Medical records API | + +--- + +## Limitations & Considerations + +### โš ๏ธ Missing Data Types +- **Pill identification**: No API for identifying pills by shape/appearance +- **Medication reminders**: Not built into Health Connect (app-level feature) +- **Dental information**: Not covered +- **Medical appointments**: Not covered (calendar events) + +### ๐Ÿ”’ Privacy Requirements +- User must grant each permission explicitly +- Cannot force permissions +- Some data types require additional health permissions +- Medical records require special handling + +### ๐Ÿ“ฑ Device Compatibility +- **Minimum**: Android 9 (API 28) +- **Optimal**: Android 14 (API 34) for full feature set +- **Health Connect module**: Must be installed from Play Store (on Android 13) or pre-installed (Android 14+) + +### ๐Ÿ“Š Data Granularity +- **Real-time**: Available (heart rate, steps during exercise) +- **Daily summaries**: Available (most data types) +- **Historical queries**: Supported with time ranges + +--- + +## Implementation Example + +### Reading Steps Data + +```kotlin +suspend fun readSteps( + healthConnectManager: HealthConnectManager, + startTime: Instant, + endTime: Instant +): List { + val response = healthConnectManager.readRecords( + ReadRecordsRequest( + recordType = StepsRecord::class, + timeRangeFilter = TimeRangeFilter.between(startTime, endTime) + ) + ) + return response.records +} +``` + +### Writing Blood Pressure Data + +```kotlin +suspend fun writeBloodPressure( + healthConnectManager: HealthConnectManager, + systolic: Double, + diastolic: Double, + timestamp: Instant +) { + val record = BloodPressureRecord( + systolic = Pressure.millimetersOfMercury(systolic), + diastolic = Pressure.millimetersOfMercury(diastolic), + time = timestamp, + zoneOffset = ZoneOffset.systemDefault(), + metadata = Metadata( + dataOrigin = DataOrigin("com.normogen.app"), + lastModifiedTime = Instant.now() + ) + ) + + healthConnectManager.insertRecords(listOf(record)) +} +``` + +### Reading Sleep Sessions + +```kotlin +suspend fun readSleepSessions( + healthConnectManager: HealthConnectManager, + startTime: Instant, + endTime: Instant +): List { + val response = healthConnectManager.readRecords( + ReadRecordsRequest( + recordType = SleepSessionRecord::class, + timeRangeFilter = TimeRangeFilter.between(startTime, endTime) + ) + ) + return response.records +} +``` + +--- + +## Recommendations for Normogen + +### โœ… Use Health Connect For: +1. **All sensor data collection** (steps, heart rate, sleep, etc.) +2. **Physical activity tracking** (exercise sessions, distance, calories) +3. **Women's health features** (period tracking, ovulation, etc.) +4. **Vital signs** (blood pressure, blood glucose, temperature) +5. **Body measurements** (weight, height, body composition) + +### โŒ Don't Use Health Connect For: +1. **Medication reminders** - Use app-level scheduling +2. **Pill identification** - Not available in API +3. **Medical appointments** - Use calendar integration +4. **Lab results storage** - Store encrypted on server (as planned) +5. **Dental records** - Custom data model needed + +### ๐ŸŽฏ Integration Strategy: +1. **Primary data source**: Health Connect for automatic sensor data +2. **Manual entry**: Allow users to manually input data not available via sensors +3. **Background sync**: Periodic sync with Health Connect to update records +4. **Privacy**: All data synced to server should be encrypted client-side (zero-knowledge) + +--- + +## Next Steps + +1. โœ… **Research complete** - All 41 data types documented +2. โณ **Create data mapping** - Map Normogen features to Health Connect types +3. โณ **Design integration** - Plan permission flow and UI +4. โณ **Implement PoC** - Build prototype with key data types +5. โณ **iOS equivalent** - Research HealthKit for comparison + +--- + +## Resources + +- [Official Documentation](https://developer.android.com/health-and-fitness/guides/health-connect/plan/data-types) +- [GitHub Samples](https://github.com/android/health-samples) +- [Health Connect on Play Store](https://play.google.com/store/apps/details?id=com.google.android.apps.healthdata) +- [Privacy Policy](https://developer.android.com/health-and-fitness/health-connect/privacy) + +--- + +**Generated by**: goose AI assistant +**Last Updated**: 2026-01-12