diff --git a/.env.example b/.env.example index e8afc941..e5e3bd48 100644 --- a/.env.example +++ b/.env.example @@ -74,3 +74,8 @@ BILLING_ENABLED=false # Personal P1-A is merged, the migration and privacy acceptance are complete. # Native HealthKit and Health Connect are NOT enabled by this flag. PERSONAL_WELLNESS_ENABLED=false + +# P1-C Android Health Connect: separate OFF-by-default gate. +# Native read-only sync requires BOTH flags, guarded Android permissions and +# an explicitly paired device. No Health Connect APIs run in the PWA browser. +PERSONAL_HEALTH_CONNECT_ENABLED=false diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1842545a..219b3716 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -160,6 +160,34 @@ jobs: echo "Archive: $(du -h "$archive" | cut -f1)" >> "$GITHUB_STEP_SUMMARY" echo "Prisma migration kit and standalone server verified in isolation." >> "$GITHUB_STEP_SUMMARY" + android-health-connect: + name: Android Health Connect debug compilation and unit tests + runs-on: ubuntu-24.04 + timeout-minutes: 30 + permissions: + contents: read + steps: + - name: Checkout + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "17" + - name: Install Android SDK 36 using hosted runner tools + run: | + set -euo pipefail + SDK_MANAGER="$(find "$ANDROID_HOME/cmdline-tools" -type f -path '*/bin/sdkmanager' | head -n1)" + test -x "$SDK_MANAGER" + "$SDK_MANAGER" --install "platforms;android-36" "build-tools;36.0.0" + - name: Gradle 8.13 + uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: "8.13" + - name: Compile read-only companion and run JVM tests + working-directory: android-health-connect + run: gradle --no-daemon :app:assembleDebug :app:testDebugUnitTest -PclubkeepBaseUrl=https://ci.clubkeep.invalid + migrations: name: PostgreSQL 17 baseline and identity migrations (native) runs-on: ubuntu-24.04 @@ -261,6 +289,8 @@ jobs: run: node --test tests/integration/personal-service.test.mjs - name: Validate P1-B wellness privacy, idempotency, export and erase on PG17 run: node --test tests/integration/p1b-wellness.test.mjs + - name: Validate P1-C Health Connect pairing, provenance, tombstones, export and erase on PG17 + run: node --test tests/integration/p1c-health-connect.test.mjs - name: Validate B8 operator billing tools (dry run, grant, revoke, reconcile parity) on PG17 run: | bash -n infra/billing/clubkeep-billing-ops.sh diff --git a/android-health-connect/.gitignore b/android-health-connect/.gitignore new file mode 100644 index 00000000..cdb2b243 --- /dev/null +++ b/android-health-connect/.gitignore @@ -0,0 +1,9 @@ +/.gradle/ +/build/ +/app/build/ +/local.properties +*.iml +.idea/ +*.jks +*.keystore +**/captures/ diff --git a/android-health-connect/README.md b/android-health-connect/README.md new file mode 100644 index 00000000..f1fdd211 --- /dev/null +++ b/android-health-connect/README.md @@ -0,0 +1,23 @@ +# ClubKeep Personal — Android Health Connect companion + +This is a dedicated, native **read-only** Android companion for authorized +fitness sync. The main HM2 Personal experience stays in Next.js. No clinical +records, advertising/analytics SDKs, background-reading or write-back +permissions are requested. minSdk 28, targetSdk 36. + +Requires Android Studio with JDK 17, Android SDK 36 and Gradle 8.13. Use +`gradle :app:assembleDebug -PclubkeepBaseUrl=https://YOUR_REVIEWED_CLUBKEEP_ORIGIN`. +A local `gradle` install or CI-provisioned Gradle is required; no unsigned +Gradle wrapper JAR is committed. The placeholder `invalid.clubkeep.example` +intentionally refuses pairing. Before publishing, verify the real +applicationId, Play app ownership, signing keys, Privacy Policy and Health +Connect declarations. + +**No APK is released by merging this source PR.** Device tests and platform +approval must precede enabling the server-side connector gate. + +Native source is developed alongside `docs/P1C_HEALTH_CONNECT.md`; Play +declarations, physical-device permission testing and signing are release gates. +The server stores only SHA-256 hashes of the one-time pairing and device +capabilities. Do not submit any Android Health Connect permissions declaration +until the privacy and Play policy review is completed. diff --git a/android-health-connect/app/build.gradle.kts b/android-health-connect/app/build.gradle.kts new file mode 100644 index 00000000..8670b8a9 --- /dev/null +++ b/android-health-connect/app/build.gradle.kts @@ -0,0 +1,45 @@ +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") +} + +val clubkeepBaseUrl = providers.gradleProperty("clubkeepBaseUrl").orElse("https://invalid.clubkeep.example").get() +require(clubkeepBaseUrl.startsWith("https://") && !clubkeepBaseUrl.contains('"')) { + "Only a trusted HTTPS ClubKeep origin may be configured" +} +android { + namespace = "com.bababuilds.clubkeep.health" + compileSdk = 36 + + defaultConfig { + applicationId = "com.bababuilds.clubkeep.health" + minSdk = 28 + targetSdk = 36 + versionCode = 1 + versionName = "0.1.0" + buildConfigField("String", "SERVER_BASE_URL", "\"$clubkeepBaseUrl\"") + } + buildFeatures { buildConfig = true; viewBinding = true } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + kotlinOptions { jvmTarget = "17" } + buildTypes { + release { + isMinifyEnabled = true + isShrinkResources = true + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + debug { isMinifyEnabled = false } + } +} + +dependencies { + implementation("androidx.activity:activity-ktx:1.13.0") + implementation("androidx.core:core-ktx:1.17.0") + implementation("androidx.health.connect:connect-client:1.1.0") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") + implementation("com.google.android.material:material:1.13.0") + testImplementation("junit:junit:4.13.2") +} diff --git a/android-health-connect/app/proguard-rules.pro b/android-health-connect/app/proguard-rules.pro new file mode 100644 index 00000000..c8f56892 --- /dev/null +++ b/android-health-connect/app/proguard-rules.pro @@ -0,0 +1,2 @@ +# Library consumer rules are bundled by Health Connect and AndroidX. +# Do not print raw Health Connect records or pairing credentials in Logcat. diff --git a/android-health-connect/app/src/main/AndroidManifest.xml b/android-health-connect/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..dd38b925 --- /dev/null +++ b/android-health-connect/app/src/main/AndroidManifest.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/ClubKeepApi.kt b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/ClubKeepApi.kt new file mode 100644 index 00000000..b5758f57 --- /dev/null +++ b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/ClubKeepApi.kt @@ -0,0 +1,34 @@ +package com.bababuilds.clubkeep.health + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.json.JSONObject +import java.net.HttpURLConnection +import java.net.URL + +/** No cookies, redirects, third-party telemetry or raw health-data logs. */ +class ClubKeepApi(private val origin: String) { + init { require(origin.startsWith("https://") && !origin.contains("invalid.clubkeep.example")) } + suspend fun post(path: String, body: JSONObject, token: String? = null): JSONObject = + withContext(Dispatchers.IO) { + require(path.startsWith("/api/native/health-connect/")) + val c = URL(origin.trimEnd('/') + path).openConnection() as HttpURLConnection + try { + c.requestMethod = "POST" + c.connectTimeout = 12000 + c.readTimeout = 25000 + c.doOutput = true + c.instanceFollowRedirects = false + c.setRequestProperty("Content-Type", "application/json") + c.setRequestProperty("Accept", "application/json") + if (token != null) c.setRequestProperty("Authorization", "Bearer $token") + val raw = body.toString().toByteArray(Charsets.UTF_8) + require(raw.size <= 65536) { "Sync request too large" } + c.outputStream.use { it.write(raw) } + if (c.responseCode !in 200..299) { + throw IllegalStateException("ClubKeep rejected the request (HTTP " + c.responseCode + ").") + } + JSONObject(c.inputStream.bufferedReader().use { it.readText() }) + } finally { c.disconnect() } + } +} diff --git a/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/CredentialVault.kt b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/CredentialVault.kt new file mode 100644 index 00000000..c5e16eb6 --- /dev/null +++ b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/CredentialVault.kt @@ -0,0 +1,47 @@ +package com.bababuilds.clubkeep.health + +import android.content.Context +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.util.Base64 +import java.security.KeyStore +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec + +/** Keystore AES-GCM protects bearer tokens and Health Connect cursors at rest. */ +class CredentialVault(context: Context) { + private val prefs = context.getSharedPreferences("ck_hc_private", Context.MODE_PRIVATE) + private val alias = "clubkeep-health-connect-v1" + private fun key(): SecretKey { + val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + (store.getKey(alias, null) as? SecretKey)?.let { return it } + return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply { + init(KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + .build()) + }.generateKey() + } + fun put(name: String, value: String) { + val c = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.ENCRYPT_MODE, key()) } + val iv = Base64.encodeToString(c.iv, Base64.NO_WRAP) + val encrypted = Base64.encodeToString(c.doFinal(value.toByteArray(Charsets.UTF_8)), Base64.NO_WRAP) + prefs.edit().putString(name, "$iv:$encrypted").apply() + } + fun get(name: String): String? { + val blob = prefs.getString(name, null) ?: return null + return try { + val parts = blob.split(":", limit = 2) + if (parts.size != 2) return null + val c = Cipher.getInstance("AES/GCM/NoPadding").apply { + init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, Base64.decode(parts[0], Base64.NO_WRAP))) + } + String(c.doFinal(Base64.decode(parts[1], Base64.NO_WRAP)), Charsets.UTF_8) + } catch (_: Exception) { null } // corrupted keys require re-pair, never fail open + } + fun remove(name: String) { prefs.edit().remove(name).apply() } + fun clear() { prefs.edit().clear().apply() } +} diff --git a/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/HealthConnectSnapshotReader.kt b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/HealthConnectSnapshotReader.kt new file mode 100644 index 00000000..01d72b85 --- /dev/null +++ b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/HealthConnectSnapshotReader.kt @@ -0,0 +1,128 @@ +package com.bababuilds.clubkeep.health + +import androidx.health.connect.client.HealthConnectClient +import androidx.health.connect.client.request.AggregateRequest +import androidx.health.connect.client.records.ActiveCaloriesBurnedRecord +import androidx.health.connect.client.records.ExerciseSessionRecord +import androidx.health.connect.client.records.HydrationRecord +import androidx.health.connect.client.records.SleepSessionRecord +import androidx.health.connect.client.records.StepsRecord +import androidx.health.connect.client.request.ReadRecordsRequest +import androidx.health.connect.client.time.TimeRangeFilter +import org.json.JSONObject +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import kotlin.math.roundToInt + +/** Streams bounded pages rather than buffering an entire wearable history. */ +class HealthConnectSnapshotReader(private val client: HealthConnectClient) { + private fun record(kind: String, id: String, source: String, start: Instant, + end: Instant, value: Int? = null, exerciseType: Int? = null): JSONObject = + JSONObject().put("recordType", kind).put("externalId", id) + .put("sourcePackage", source).put("startedAt", start.toString()) + .put("endedAt", end.toString()) + .apply { + if (value != null) put("value", value) + if (exerciseType != null) put("exerciseType", exerciseType) + } + + /** Changes API carries typed upserts; deletions have only an id. */ + fun changed(source: androidx.health.connect.client.records.Record): JSONObject? = + when (source) { + is ExerciseSessionRecord -> record("WORKOUT", source.metadata.id, + source.metadata.dataOrigin.packageName, source.startTime, source.endTime, + exerciseType = source.exerciseType) + is SleepSessionRecord -> record("SLEEP", source.metadata.id, + source.metadata.dataOrigin.packageName, source.startTime, source.endTime) + is HydrationRecord -> { + val ml = source.volume.inMilliliters.roundToInt() + if (ml in 1..5000) record("HYDRATION", source.metadata.id, + source.metadata.dataOrigin.packageName, source.startTime, source.endTime, ml) else null + } + is ActiveCaloriesBurnedRecord -> { + val kcal = source.energy.inKilocalories.roundToInt() + if (kcal in 0..5000000) record("ACTIVE_CALORIES", source.metadata.id, + source.metadata.dataOrigin.packageName, source.startTime, source.endTime, kcal) else null + } + else -> null // No clinical record type is supported. + } + + suspend fun snapshot(grants: Set, from: Instant, until: Instant, + emit: suspend (List) -> Unit) { + val filter = TimeRangeFilter.between(from, until) + + // The HC aggregate API resolves duplicated step sources; raw step samples don't. + if ("STEPS_DAILY" in grants) { + val zone = ZoneId.systemDefault() + var day = LocalDate.ofInstant(from, zone) + val latest = LocalDate.ofInstant(until, zone) + while (!day.isAfter(latest)) { + val start = day.atStartOfDay(zone).toInstant() + val end = day.plusDays(1).atStartOfDay(zone).toInstant() + if (start < until && end > from) { + val total = client.aggregate(AggregateRequest( + metrics = setOf(StepsRecord.COUNT_TOTAL), + timeRangeFilter = TimeRangeFilter.between(start, minOf(end, until)) + ))[StepsRecord.COUNT_TOTAL] + if (total != null && total in 0L..5000000L) { + emit(listOf(record("STEPS_DAILY", day.toString(), "health-connect-aggregate", + start, minOf(end, until), total.toInt()))) + } + } + day = day.plusDays(1) + } + } + if ("WORKOUT" in grants) { + var token: String? = null + do { + val page = client.readRecords(ReadRecordsRequest( + ExerciseSessionRecord::class, timeRangeFilter = filter, + pageSize = 100, pageToken = token)) + emit(page.records.map { r -> record("WORKOUT", r.metadata.id, + r.metadata.dataOrigin.packageName, r.startTime, r.endTime, + exerciseType = r.exerciseType) }) + token = page.pageToken + } while (token != null) + } + if ("SLEEP" in grants) { + var token: String? = null + do { + val page = client.readRecords(ReadRecordsRequest( + SleepSessionRecord::class, timeRangeFilter = filter, + pageSize = 100, pageToken = token)) + emit(page.records.map { r -> record("SLEEP", r.metadata.id, + r.metadata.dataOrigin.packageName, r.startTime, r.endTime) }) + token = page.pageToken + } while (token != null) + } + if ("HYDRATION" in grants) { + var token: String? = null + do { + val page = client.readRecords(ReadRecordsRequest( + HydrationRecord::class, timeRangeFilter = filter, + pageSize = 100, pageToken = token)) + emit(page.records.mapNotNull { r -> + val ml = r.volume.inMilliliters.roundToInt() + if (ml in 1..5000) record("HYDRATION", r.metadata.id, + r.metadata.dataOrigin.packageName, r.startTime, r.endTime, ml) else null + }) + token = page.pageToken + } while (token != null) + } + if ("ACTIVE_CALORIES" in grants) { + var token: String? = null + do { + val page = client.readRecords(ReadRecordsRequest( + ActiveCaloriesBurnedRecord::class, timeRangeFilter = filter, + pageSize = 100, pageToken = token)) + emit(page.records.mapNotNull { r -> + val kcal = r.energy.inKilocalories.roundToInt() + if (kcal in 0..5000000) record("ACTIVE_CALORIES", r.metadata.id, + r.metadata.dataOrigin.packageName, r.startTime, r.endTime, kcal) else null + }) + token = page.pageToken + } while (token != null) + } + } +} diff --git a/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/HealthConnectSyncEngine.kt b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/HealthConnectSyncEngine.kt new file mode 100644 index 00000000..e79b1d0e --- /dev/null +++ b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/HealthConnectSyncEngine.kt @@ -0,0 +1,177 @@ +package com.bababuilds.clubkeep.health + +import androidx.health.connect.client.HealthConnectClient +import androidx.health.connect.client.changes.DeletionChange +import androidx.health.connect.client.changes.UpsertionChange +import androidx.health.connect.client.records.ActiveCaloriesBurnedRecord +import androidx.health.connect.client.records.ExerciseSessionRecord +import androidx.health.connect.client.records.HydrationRecord +import androidx.health.connect.client.records.SleepSessionRecord +import androidx.health.connect.client.request.ChangesTokenRequest +import kotlinx.coroutines.delay +import org.json.JSONArray +import org.json.JSONObject +import java.time.Instant +import java.time.temporal.ChronoUnit +import java.util.UUID + +data class SyncReport(val imported: Int, val deleted: Int, val mode: String) + +/** + * Foreground user-initiated sync only. No background Health Connect permission. + * The encrypted cursor is committed only AFTER all corresponding server batches + * acknowledge success. Missing/revoked categories are never read. + */ +class HealthConnectSyncEngine( + private val client: HealthConnectClient, + private val api: ClubKeepApi, + private val vault: CredentialVault +) { + private val reader = HealthConnectSnapshotReader(client) + private val batchSize = 60 + + private fun subscribedTypes(granted: Set) = buildSet { + if ("WORKOUT" in granted) add(ExerciseSessionRecord::class) + if ("SLEEP" in granted) add(SleepSessionRecord::class) + if ("HYDRATION" in granted) add(HydrationRecord::class) + if ("ACTIVE_CALORIES" in granted) add(ActiveCaloriesBurnedRecord::class) + } + + private fun indexKey(record: JSONObject) = record.getString("externalId") + private fun indexValue(record: JSONObject) = + record.getString("recordType") + "|" + record.getString("sourcePackage") + private fun saveIndex(index: JSONObject) { vault.put("sourceIndex", index.toString()) } + private fun openIndex(): JSONObject = try { + JSONObject(vault.get("sourceIndex") ?: "{}") + } catch (_: Exception) { JSONObject() } + + private suspend fun transmit( + token: String, grants: Set, index: JSONObject, + items: List, deletions: List + ): Pair { + var imported = 0 + var deleted = 0 + val scope = JSONArray(grants.sorted()) + val upChunks = items.chunked(batchSize) + val delChunks = deletions.chunked(batchSize) + val batches = maxOf(upChunks.size, delChunks.size, 1) + for (i in 0 until batches) { + val up = if (i < upChunks.size) upChunks[i] else emptyList() + val gone = if (i < delChunks.size) delChunks[i] else emptyList() + val body = JSONObject() + .put("requestId", UUID.randomUUID().toString()) + .put("grantedTypes", scope) + .put("records", JSONArray(up)) + .put("deletions", JSONArray(gone)) + // The native code never logs request bodies, bearer tokens or source IDs. + var failure: Exception? = null + var accepted = false + for (attempt in 0..2) { + try { + api.post("/api/native/health-connect/batches", body, token) + accepted = true + break + } catch (e: Exception) { + failure = e + if (attempt < 2) delay(500L * (attempt + 1)) + } + } + if (!accepted) throw failure ?: IllegalStateException("Sync rejected") + for (record in up) index.put(indexKey(record), indexValue(record)) + for (record in gone) index.remove(record.getString("externalId")) + saveIndex(index) + imported += up.size + deleted += gone.size + } + return imported to deleted + } + + suspend fun sync(token: String): SyncReport { + val actual = client.permissionController.getGrantedPermissions() + val grants = HealthPermissions.grantedCategories(actual) + val scope = grants.sorted().joinToString("|") + val previous = vault.get("changesToken") + val index = openIndex() + if (grants.isEmpty()) { + transmit(token, grants, index, emptyList(), emptyList()) + vault.remove("changesToken") + vault.remove("changesScope") + return SyncReport(0, 0, "no permission") + } + val changedTypes = subscribedTypes(grants) + val scopeChanged = vault.get("changesScope") != scope + if (previous == null || scopeChanged || changedTypes.isEmpty()) { + // Take a cursor BEFORE the snapshot to avoid missing changes during + // its pagination. Replaying later is safe because backend upserts. + val initial = if (changedTypes.isEmpty()) null else + client.getChangesToken(ChangesTokenRequest(changedTypes)) + var count = 0 + val from = Instant.now().minus(29, ChronoUnit.DAYS) + reader.snapshot(grants, from, Instant.now()) { rows -> + if (rows.isNotEmpty()) { + val result = transmit(token, grants, index, rows, emptyList()) + count += result.first + } + } + // Even an empty snapshot reports the currently granted categories. + if (count == 0) transmit(token, grants, index, emptyList(), emptyList()) + if (initial != null) vault.put("changesToken", initial) + else vault.remove("changesToken") + vault.put("changesScope", scope) + vault.put("lastSyncedAt", Instant.now().toString()) + return SyncReport(count, 0, "initial snapshot") + } + + var cursor: String = requireNotNull(previous) + var count = 0 + var removed = 0 + do { + val response = client.getChanges(cursor) + if (response.changesTokenExpired) { + // Expired credentials cannot be used for incremental deletions. + // Re-snapshot conservatively and inform user in the review UI. + vault.remove("changesToken") + return sync(token) + } + val upserts = mutableListOf() + val deletions = mutableListOf() + for (change in response.changes) { + when (change) { + is UpsertionChange -> { + val item = reader.changed(change.record) ?: continue + if (item.getString("recordType") in grants) upserts.add(item) + } + is DeletionChange -> { + val tracked = index.optString(change.recordId, "") + val parts = tracked.split("|", limit = 2) + if (parts.size == 2) { + deletions.add(JSONObject().put("recordType", parts[0]) + .put("sourcePackage", parts[1]) + .put("externalId", change.recordId)) + } + } + } + } + val result = transmit(token, grants, index, upserts, deletions) + count += result.first + removed += result.second + // This token advances only after ALL batches in this changes page commit. + cursor = response.nextChangesToken + vault.put("changesToken", cursor) + } while (response.hasMore) + + // Daily aggregate repair captures changed steps without raw duplicates. + if ("STEPS_DAILY" in grants) { + reader.snapshot(setOf("STEPS_DAILY"), Instant.now().minus(29, ChronoUnit.DAYS), + Instant.now()) { rows -> + if (rows.isNotEmpty()) { + val result = transmit(token, grants, index, rows, emptyList()) + count += result.first + } + } + } + vault.put("changesScope", scope) + vault.put("lastSyncedAt", Instant.now().toString()) + return SyncReport(count, removed, "incremental") + } +} diff --git a/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/HealthPermissions.kt b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/HealthPermissions.kt new file mode 100644 index 00000000..3d5d280b --- /dev/null +++ b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/HealthPermissions.kt @@ -0,0 +1,38 @@ +package com.bababuilds.clubkeep.health + +import android.content.Context +import androidx.health.connect.client.HealthConnectClient +import androidx.health.connect.client.permission.HealthPermission +import androidx.health.connect.client.records.ActiveCaloriesBurnedRecord +import androidx.health.connect.client.records.ExerciseSessionRecord +import androidx.health.connect.client.records.HydrationRecord +import androidx.health.connect.client.records.SleepSessionRecord +import androidx.health.connect.client.records.StepsRecord + +/** Only fitness categories; no heart rate, glucose, medications, clinical records or write rights. */ +object HealthPermissions { + val steps = HealthPermission.getReadPermission(StepsRecord::class) + val workouts = HealthPermission.getReadPermission(ExerciseSessionRecord::class) + val sleep = HealthPermission.getReadPermission(SleepSessionRecord::class) + val calories = HealthPermission.getReadPermission(ActiveCaloriesBurnedRecord::class) + val hydration = HealthPermission.getReadPermission(HydrationRecord::class) + + val default = setOf(steps, workouts, sleep, calories) + fun requested(includeHydration: Boolean): Set = + if (includeHydration) default + hydration else default + + fun available(context: Context): Boolean = + HealthConnectClient.getSdkStatus(context) == HealthConnectClient.SDK_AVAILABLE + + fun client(context: Context): HealthConnectClient { + check(available(context)) { "Health Connect is not installed or supported." } + return HealthConnectClient.getOrCreate(context) + } + fun grantedCategories(permissions: Set): Set = buildSet { + if (steps in permissions) add("STEPS_DAILY") + if (workouts in permissions) add("WORKOUT") + if (sleep in permissions) add("SLEEP") + if (calories in permissions) add("ACTIVE_CALORIES") + if (hydration in permissions) add("HYDRATION") + } +} diff --git a/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/MainActivity.kt b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/MainActivity.kt new file mode 100644 index 00000000..28442e45 --- /dev/null +++ b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/MainActivity.kt @@ -0,0 +1,130 @@ +package com.bababuilds.clubkeep.health + +import android.content.Intent +import android.os.Bundle +import android.os.Build +import androidx.activity.ComponentActivity +import androidx.health.connect.client.PermissionController +import androidx.lifecycle.lifecycleScope +import com.bababuilds.clubkeep.health.databinding.ActivityMainBinding +import kotlinx.coroutines.launch +import org.json.JSONObject +import java.util.UUID + +/** + * Native companion with deliberate user-facing controls. Health Connect never + * runs on page load, never sends a grant implicitly, and has no background sync. + */ +class MainActivity : ComponentActivity() { + private lateinit var views: ActivityMainBinding + private lateinit var vault: CredentialVault + private var working = false + private val permissionRequest = registerForActivityResult( + PermissionController.createRequestPermissionResultContract() + ) { granted -> + showStatus(if (granted.isEmpty()) "No fitness permissions granted." else + "Permissions reviewed. Use Sync only when you want to upload.") + updateControls() + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + views = ActivityMainBinding.inflate(layoutInflater) + setContentView(views.root) + vault = CredentialVault(applicationContext) + views.connect.setOnClickListener { connect() } + views.permissions.setOnClickListener { requestPermissions() } + views.sync.setOnClickListener { syncNow() } + views.disconnect.setOnClickListener { disconnect() } + views.privacy.setOnClickListener { + startActivity(Intent(this, PrivacyRationaleActivity::class.java)) + } + updateControls() + showStatus(when { + !configured() -> "This build has no reviewed ClubKeep HTTPS origin." + vault.get("token") != null -> "Paired. Permissions are checked again before every sync." + else -> "Open Personal Connections in the browser and copy a one-time pairing code." + }) + } + + private fun configured() = BuildConfig.SERVER_BASE_URL.startsWith("https://") && + !BuildConfig.SERVER_BASE_URL.contains("invalid.clubkeep.example") + + private fun updateControls() { + val linked = configured() && vault.get("token") != null + views.connect.isEnabled = !working && configured() + views.permissions.isEnabled = !working && linked && HealthPermissions.available(this) + views.sync.isEnabled = !working && linked && HealthPermissions.available(this) + views.disconnect.isEnabled = !working && linked + } + private fun showStatus(value: String) { views.status.text = value } + private fun connect() { + if (working || !configured()) return + val code = views.pairCode.text?.toString()?.trim() ?: "" + if (!Regex("^[A-Za-z0-9_-]{43}$").matches(code)) { + showStatus("Paste the entire short-lived pairing code."); return + } + working = true; updateControls() + lifecycleScope.launch { + try { + val installId = vault.get("installationId") ?: UUID.randomUUID().toString() + val payload = JSONObject() + .put("pairCode", code).put("installationId", installId) + .put("label", "Android " + Build.MODEL.take(50)) + val response = ClubKeepApi(BuildConfig.SERVER_BASE_URL) + .post("/api/native/health-connect/claim", payload) + vault.put("installationId", installId) + vault.put("token", response.getString("token")) + vault.put("connectionId", response.getString("connectionId")) + vault.remove("changesToken") + vault.remove("sourceIndex") + vault.remove("changesScope") + views.pairCode.text?.clear() + showStatus("Account paired. Choose the permissions you want to grant.") + } catch (_: Exception) { + showStatus("Pairing failed. Confirm the code, server and connection, then retry.") + } finally { working = false; updateControls() } + } + } + + private fun requestPermissions() { + if (vault.get("token") == null || !HealthPermissions.available(this)) return + permissionRequest.launch(HealthPermissions.requested(views.includeHydration.isChecked)) + } + + private fun disconnect() { + val token = vault.get("token") ?: return + if (working) return + working = true; updateControls() + lifecycleScope.launch { + try { + ClubKeepApi(BuildConfig.SERVER_BASE_URL) + .post("/api/native/health-connect/disconnect", JSONObject(), token) + vault.clear() + views.pairCode.text?.clear() + showStatus("Disconnected on ClubKeep. Imported history can be erased in Personal.") + } catch (_: Exception) { + showStatus("Cannot confirm remote disconnect. Use Personal Connections to revoke.") + } finally { working = false; updateControls() } + } + } + private fun syncNow() { + val token = vault.get("token") ?: return + if (working || !HealthPermissions.available(this)) return + working = true; updateControls() + showStatus("Reading authorized fitness data. Do not close this screen until sync completes.") + lifecycleScope.launch { + try { + val result = HealthConnectSyncEngine( + HealthPermissions.client(this@MainActivity), + ClubKeepApi(BuildConfig.SERVER_BASE_URL), vault + ).sync(token) + showStatus("Sync complete (" + result.mode + "): " + + result.imported + " records updated, " + result.deleted + " removed.") + } catch (_: Exception) { + showStatus("Sync incomplete. Your acknowledged history is safe. Retry with the app open.") + } finally { working = false; updateControls() } + } + } + +} diff --git a/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/PrivacyRationaleActivity.kt b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/PrivacyRationaleActivity.kt new file mode 100644 index 00000000..a7d4257c --- /dev/null +++ b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/PrivacyRationaleActivity.kt @@ -0,0 +1,18 @@ +package com.bababuilds.clubkeep.health + +import android.os.Bundle +import android.widget.TextView +import androidx.activity.ComponentActivity + +/** Shown from Health Connect's official permission rationale path. */ +class PrivacyRationaleActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(TextView(this).apply { + text = getString(R.string.privacy_description) + textSize = 18f + setPadding(42, 64, 42, 48) + contentDescription = text + }) + } +} diff --git a/android-health-connect/app/src/main/res/layout/activity_main.xml b/android-health-connect/app/src/main/res/layout/activity_main.xml new file mode 100644 index 00000000..a42df286 --- /dev/null +++ b/android-health-connect/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + diff --git a/android-health-connect/app/src/main/res/values/colors.xml b/android-health-connect/app/src/main/res/values/colors.xml new file mode 100644 index 00000000..f7d0bb6a --- /dev/null +++ b/android-health-connect/app/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ + + #F8F4E8 + #224C3A + #DDE9D7 + #586B5E + diff --git a/android-health-connect/app/src/main/res/values/strings.xml b/android-health-connect/app/src/main/res/values/strings.xml new file mode 100644 index 00000000..f4f71eea --- /dev/null +++ b/android-health-connect/app/src/main/res/values/strings.xml @@ -0,0 +1,11 @@ + + ClubKeep Health + Your health, your choice + Paste the one-time code from ClubKeep Personal + Connect my account + Choose data to share + Sync permitted fitness data + Disconnect this device + Why we ask for fitness data + Only categories you approve are read on this device and sent to your own ClubKeep Personal account. Clinic records are never requested. Disconnect stops uploads; you can delete imported copies in Personal. No ads or club staff receive these records. + diff --git a/android-health-connect/app/src/main/res/values/styles.xml b/android-health-connect/app/src/main/res/values/styles.xml new file mode 100644 index 00000000..a8ecba17 --- /dev/null +++ b/android-health-connect/app/src/main/res/values/styles.xml @@ -0,0 +1,9 @@ + + + diff --git a/android-health-connect/app/src/test/java/com/bababuilds/clubkeep/health/SyncContractTest.kt b/android-health-connect/app/src/test/java/com/bababuilds/clubkeep/health/SyncContractTest.kt new file mode 100644 index 00000000..b9fa734e --- /dev/null +++ b/android-health-connect/app/src/test/java/com/bababuilds/clubkeep/health/SyncContractTest.kt @@ -0,0 +1,13 @@ +package com.bababuilds.clubkeep.health + +import org.junit.Assert.assertEquals +import org.junit.Test + +class SyncContractTest { + @Test fun reportsAreExplicitAboutReplayedWorkAndSource() { + val report = SyncReport(12, 2, "incremental") + assertEquals(12, report.imported) + assertEquals(2, report.deleted) + assertEquals("incremental", report.mode) + } +} diff --git a/android-health-connect/build.gradle.kts b/android-health-connect/build.gradle.kts new file mode 100644 index 00000000..13cf2cff --- /dev/null +++ b/android-health-connect/build.gradle.kts @@ -0,0 +1,4 @@ +plugins { + id("com.android.application") version "8.13.2" apply false + id("org.jetbrains.kotlin.android") version "2.2.20" apply false +} diff --git a/android-health-connect/gradle.properties b/android-health-connect/gradle.properties new file mode 100644 index 00000000..c6517c20 --- /dev/null +++ b/android-health-connect/gradle.properties @@ -0,0 +1,4 @@ +org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8 +org.gradle.caching=true +android.useAndroidX=true +kotlin.code.style=official diff --git a/android-health-connect/settings.gradle.kts b/android-health-connect/settings.gradle.kts new file mode 100644 index 00000000..31772194 --- /dev/null +++ b/android-health-connect/settings.gradle.kts @@ -0,0 +1,7 @@ +pluginManagement { repositories { google(); maven { url = uri("https://repo1.maven.org/maven2/") }; mavenCentral(); gradlePluginPortal() } } +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { google(); mavenCentral() } +} +rootProject.name = "ClubKeepHealthConnect" +include(":app") diff --git a/docs/P1C_HEALTH_CONNECT.md b/docs/P1C_HEALTH_CONNECT.md new file mode 100644 index 00000000..92c39e92 --- /dev/null +++ b/docs/P1C_HEALTH_CONNECT.md @@ -0,0 +1,98 @@ +# Personal P1-C — Android Health Connect native companion + +**Status:** implementation PR, **NOT** an activated, approved, deployed mobile health integration. +Base: merged Personal P1-A/B. Server launch requires both +`PERSONAL_WELLNESS_ENABLED=true` and `PERSONAL_HEALTH_CONNECT_ENABLED=true`. +Both remain off in the repository sample environment. Production flags MUST +remain disabled until release acceptance, legal review and real device tests. + +## Native application +- `android-health-connect/` is a new, deliberately small Android app. Build: + `gradle :app:assembleDebug :app:testDebugUnitTest -PclubkeepBaseUrl=https://REVIEWED-CLUBKEEP-ORIGIN`. + Gradle 8.13, JDK 17, Android SDK 36; AGP 8.13.2, stable Health Connect 1.1.0. +- The placeholder `https://invalid.clubkeep.example` refuses pairing. Before + a Play release, confirm actual package ID, Play ownership, upload signing, + website origin and approved privacy statement. A merge never uploads an APK. +- Foreground-only user-initiated sync. **NO** background permission, full-history + permission, writes, heart rate, medication, blood glucose, clinical data, ads + SDK, analytics SDK or external AI transmission. +- Read permissions: steps, workout sessions, sleep, active energy; hydration + must be checked separately. Android/Health Connect may grant partial subsets. + System grants are checked immediately before each sync. The server sees + **device-reported categories**, never a claim of OS-attested permissions. + +## Secure account pairing +1. Verified adult signs in through Better Auth at `/me/connections`, then + explicitly requests a single-use 256-bit pairing code (10 minutes). +2. Enters code in the native app, which transmits the code over the operator- + configured HTTPS origin. No web cookies or password are stored on Android. +3. Server atomically redeems one code for a 256-bit 30-day device bearer + capability scoped to its user's **Personal** fitness-only routes. +4. Android stores token, installation ID, HC change cursor and deletion index + encrypted using Android Keystore AES-GCM; Android auto-backup is off. + Credentials are **encrypted at rest** but are still bearer credentials, not + hardware-attested cryptographic device signatures. Treat rooted devices + and device compromise as material residual risks. +5. The user may revoke from either device or web. Re-pairing rotates the + secret; expiration requires new pairing. No club role authorizes access. + +## Data flow and source correctness +- Aggregated daily steps use `StepsRecord.COUNT_TOTAL`, not summed raw samples. +- Session/energy/hydration data are read with paginated, bounded queries. +- Snapshots import up to 29 days of authorized history. The connector does + not request Health Connect's extended history permission. Actual readable + history depends on the user's OS and grants. +- Source IDs are user+record-kind+package+external-ID unique, retaining exact + source provenance. Each upload is an atomic, size-limited, retry-safe batch; + source tombstones prevent accidental resurrection. +- Device-side Changes tokens advance **only after server acknowledgement**. + Deletion changes contain no record type: encrypted local source indexing is + used. Unknown deleted IDs are not guessed. Expired tokens trigger bounded + re-snapshot. Daily steps are refreshed with aggregate queries. This does not + promise perfect deletion reconciliation for unavailable historical records; + a device/source reconciliation workflow is a follow-up. +- Imported activity is displayed separately from manual workout goals. Mirrored + fitness apps may describe the same workout: do not sum blindly or infer + clinical readiness. Reconciliation and canonical cross-source goal counting + are separate hardening tasks. + +## Privacy and operations +- Sources live only under the global Personal User. No club join, sponsor, + Business admin, leaderboard, advertisement or insurance integration has + access to the imported content. +- `/api/me/data/export` includes normalized imported data and non-secret + connection metadata; never exports connection token hashes or pairing codes. +- `/api/me/data/delete` invalidates connections and deletes their imported + data and batches as part of Personal erasure. User may instead disconnect + devices without deleting prior copies, or explicitly purge imported copies + (which also revokes connections to prevent immediate re-import). +- Retain only private `no-store` HTTP responses. Do not log tokens, raw + payloads, exercise/sleep record IDs, personal health metrics or data in + third-party crash/analytics products. +- Server-side rollback: set `PERSONAL_HEALTH_CONNECT_ENABLED=false` in + protected ClubKeep environment, restart only `clubkeep-web`. Never delete + the additive schema as part of a rollback, never touch ERP/MenuMinute. + +## Mandatory acceptance before launch +1. PG17 migration, drift check, legacy preservation, export/erase/cross-user, + two-device duplicate and revoked-device tests green. +2. x64 and ARM64 builds green with existing Business/Personal smoke tests; + Android JDK17, Gradle, SDK 36 `assembleDebug` and unit tests green. +3. On real Android 13 and Android 14+ devices: missing Health Connect, + unavailable SDK, partial grant, denial/revoke during sync, token expiry, + disconnected account and repeated pairing. +4. Steps from multiple original apps must not double count, imported workouts + retain package identity, duplicate batch retry is safe; interrupted sync + does not skip changes; deleted local data is reconciled to tombstones. +5. Validate permission rationale, Play Console Health app + per-type HC + declarations, a public monitored privacy contact, consent, data safety, + data deletion and target API policies. Check legal minimum account age + versus conservative 19+ Personal wellness rule. +6. Physical UI checks at mobile font scaling, light/dark, TalkBack. + Confirm no signed Play release is made without owner approval. + +**Open / explicitly deferred:** Health Connect extended-history/background +permissions, WorkManager schedule, push reminders, native read-to-HealthKit, +source conflict review UX, canonical combined goal metrics, encrypted offline +upload queue beyond the local cursor, Play Integrity attestation, advanced +analytics entitlements, medical/clinical features, signed production APK. diff --git a/prisma/migrations/20261119120000_personal_p1c_health_connect/migration.sql b/prisma/migrations/20261119120000_personal_p1c_health_connect/migration.sql new file mode 100644 index 00000000..f094dc2a --- /dev/null +++ b/prisma/migrations/20261119120000_personal_p1c_health_connect/migration.sql @@ -0,0 +1,72 @@ +-- Additive P1-C nonclinical Health Connect data; all data remains self-owned. +CREATE TYPE "HealthConnectRecordType" AS ENUM ('STEPS_DAILY','WORKOUT','SLEEP','ACTIVE_CALORIES','HYDRATION'); + +CREATE TABLE "HealthConnectPairing" ( + "id" TEXT PRIMARY KEY, + "userId" TEXT NOT NULL, + "codeHash" VARCHAR(64) NOT NULL, + "expiresAt" TIMESTAMP(3) NOT NULL, + "claimedAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "HealthConnectPairing_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE +); +CREATE UNIQUE INDEX "HealthConnectPairing_codeHash_key" ON "HealthConnectPairing"("codeHash"); +CREATE INDEX "HealthConnectPairing_userId_expiresAt_idx" ON "HealthConnectPairing"("userId","expiresAt"); + +CREATE TABLE "HealthConnectConnection" ( + "id" TEXT PRIMARY KEY, + "userId" TEXT NOT NULL, + "installationId" VARCHAR(64) NOT NULL, + "label" VARCHAR(80) NOT NULL, + "tokenHash" VARCHAR(64) NOT NULL, + "tokenExpiresAt" TIMESTAMP(3) NOT NULL, + "grantedTypes" TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[], + "lastSeenAt" TIMESTAMP(3), + "lastSyncAt" TIMESTAMP(3), + "revokedAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + CONSTRAINT "HealthConnectConnection_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE +); +CREATE UNIQUE INDEX "HealthConnectConnection_tokenHash_key" ON "HealthConnectConnection"("tokenHash"); +CREATE UNIQUE INDEX "HealthConnectConnection_userId_installationId_key" ON "HealthConnectConnection"("userId","installationId"); +CREATE INDEX "HealthConnectConnection_userId_revokedAt_idx" ON "HealthConnectConnection"("userId","revokedAt"); + +CREATE TABLE "HealthConnectSyncBatch" ( + "id" TEXT PRIMARY KEY, + "connectionId" TEXT NOT NULL, + "requestId" UUID NOT NULL, + "contentHash" VARCHAR(64) NOT NULL, + "importedCount" INTEGER NOT NULL, + "deletedCount" INTEGER NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "HealthConnectSyncBatch_connectionId_fkey" FOREIGN KEY ("connectionId") REFERENCES "HealthConnectConnection"("id") ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT "HealthConnectSyncBatch_counts_check" CHECK ("importedCount" >= 0 AND "deletedCount" >= 0) +); +CREATE UNIQUE INDEX "hcb_connection_request_key" ON "HealthConnectSyncBatch"("connectionId","requestId"); +CREATE INDEX "HealthConnectSyncBatch_connectionId_createdAt_idx" ON "HealthConnectSyncBatch"("connectionId","createdAt"); + +CREATE TABLE "HealthConnectRecord" ( + "id" TEXT PRIMARY KEY, + "userId" TEXT NOT NULL, + "recordType" "HealthConnectRecordType" NOT NULL, + "externalId" VARCHAR(160) NOT NULL, + "sourcePackage" VARCHAR(160) NOT NULL, + "startedAt" TIMESTAMP(3) NOT NULL, + "endedAt" TIMESTAMP(3) NOT NULL, + "value" INTEGER, + "exerciseType" INTEGER, + "deletedAt" TIMESTAMP(3), + "lastDeviceId" VARCHAR(64) NOT NULL, + "lastSeenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + CONSTRAINT "HealthConnectRecord_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT "HealthConnectRecord_window_check" CHECK ("endedAt" > "startedAt"), + CONSTRAINT "HealthConnectRecord_value_check" CHECK ("value" IS NULL OR "value" BETWEEN 0 AND 5000000), + CONSTRAINT "HealthConnectRecord_steps_check" CHECK ( + "recordType" <> 'STEPS_DAILY' OR ("value" IS NOT NULL AND "sourcePackage" = 'health-connect-aggregate') + ) +); +CREATE UNIQUE INDEX "hcr_dedup" ON "HealthConnectRecord"("userId","recordType","sourcePackage","externalId"); +CREATE INDEX "hcr_user_kind_end" ON "HealthConnectRecord"("userId","recordType","endedAt"); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index b3c15e67..531ce1dd 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -42,6 +42,9 @@ model User { wellnessHydration HydrationEntry[] wellnessRecovery RecoveryCheckIn[] wellnessSources WellnessSourceRecord[] + healthConnectConnections HealthConnectConnection[] + healthConnectPairings HealthConnectPairing[] + healthConnectRecords HealthConnectRecord[] clubMemberships ClubMembership[] issuedInvites ClubInvite[] @relation("InviteIssuer") claimedInvites ClubInvite[] @relation("InviteClaimant") @@ -390,6 +393,82 @@ model WellnessSourceRecord { @@index([userId, provider]) } + +// Health Connect supplies only consented nonclinical fitness data. Never +// join provider records to Club or use their fields for club authorization. +enum HealthConnectRecordType { + STEPS_DAILY + WORKOUT + SLEEP + ACTIVE_CALORIES + HYDRATION +} + +model HealthConnectPairing { + id String @id @default(cuid()) + userId String + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + codeHash String @unique @db.VarChar(64) + expiresAt DateTime + claimedAt DateTime? + createdAt DateTime @default(now()) + @@index([userId, expiresAt]) +} + +model HealthConnectConnection { + id String @id @default(cuid()) + userId String + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + installationId String @db.VarChar(64) + label String @db.VarChar(80) + tokenHash String @unique @db.VarChar(64) + tokenExpiresAt DateTime + grantedTypes String[] @default([]) + lastSeenAt DateTime? + lastSyncAt DateTime? + revokedAt DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + batches HealthConnectSyncBatch[] + @@unique([userId, installationId]) + @@index([userId, revokedAt]) +} + +model HealthConnectSyncBatch { + id String @id @default(cuid()) + connectionId String + connection HealthConnectConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade) + requestId String @db.Uuid + contentHash String @db.VarChar(64) + importedCount Int + deletedCount Int + createdAt DateTime @default(now()) + @@unique([connectionId, requestId], map: "hcb_connection_request_key") + @@index([connectionId, createdAt]) +} + +model HealthConnectRecord { + id String @id @default(cuid()) + userId String + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + recordType HealthConnectRecordType + externalId String @db.VarChar(160) + sourcePackage String @db.VarChar(160) + startedAt DateTime + endedAt DateTime + // STEPS_DAILY=count, ACTIVE_CALORIES=kcal, HYDRATION=mL. + // WORKOUT/SLEEP duration is derived from start/end; unknown amounts are null. + value Int? + exerciseType Int? + deletedAt DateTime? + lastDeviceId String @db.VarChar(64) + lastSeenAt DateTime @default(now()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + @@unique([userId, recordType, sourcePackage, externalId], map: "hcr_dedup") + @@index([userId, recordType, endedAt], map: "hcr_user_kind_end") +} + enum PlatformRole { USER PLATFORM_ADMIN diff --git a/src/app/api/me/connections/health-connect/pair/route.ts b/src/app/api/me/connections/health-connect/pair/route.ts new file mode 100644 index 00000000..1c5ffd4e --- /dev/null +++ b/src/app/api/me/connections/health-connect/pair/route.ts @@ -0,0 +1,9 @@ +import type { NextRequest } from "next/server"; +import { z } from "zod"; +import { wellnessPost } from "@/lib/personal/wellness-http"; +import { beginHealthPairing } from "@/lib/personal/health-connect/connections"; +export async function POST(request: NextRequest) { + return wellnessPost(request, "health-pair", 6, z.object({}).strict(), (db, userId) => + beginHealthPairing(db, userId) + ); +} diff --git a/src/app/api/me/connections/health-connect/purge/route.ts b/src/app/api/me/connections/health-connect/purge/route.ts new file mode 100644 index 00000000..16be7167 --- /dev/null +++ b/src/app/api/me/connections/health-connect/purge/route.ts @@ -0,0 +1,11 @@ +import type { NextRequest } from "next/server"; +import { wellnessPost } from "@/lib/personal/wellness-http"; +import { purgeHealthImports } from "@/lib/personal/health-connect/connections"; +import { healthPurgeInput } from "@/lib/validations/health-connect"; +import { assertHealthConnectEnabled } from "@/lib/personal/health-connect/flags"; +export async function POST(request: NextRequest) { + return wellnessPost(request, "health-purge", 5, healthPurgeInput, (db, userId) => { + assertHealthConnectEnabled(); + return purgeHealthImports(db, userId); + }); +} diff --git a/src/app/api/me/connections/health-connect/records/route.ts b/src/app/api/me/connections/health-connect/records/route.ts new file mode 100644 index 00000000..aedee825 --- /dev/null +++ b/src/app/api/me/connections/health-connect/records/route.ts @@ -0,0 +1,11 @@ +import type { NextRequest } from "next/server"; +import { wellnessRead } from "@/lib/personal/wellness-http"; +import { assertHealthConnectEnabled } from "@/lib/personal/health-connect/flags"; +import { listImportedFitness } from "@/lib/personal/health-connect/ingestion"; + +export async function GET(request: NextRequest): Promise { + return wellnessRead(request, (db, userId) => { + assertHealthConnectEnabled(); + return listImportedFitness(db, userId); + }); +} diff --git a/src/app/api/me/connections/health-connect/revoke/route.ts b/src/app/api/me/connections/health-connect/revoke/route.ts new file mode 100644 index 00000000..db755800 --- /dev/null +++ b/src/app/api/me/connections/health-connect/revoke/route.ts @@ -0,0 +1,11 @@ +import type { NextRequest } from "next/server"; +import { wellnessPost } from "@/lib/personal/wellness-http"; +import { revokeHealthConnection } from "@/lib/personal/health-connect/connections"; +import { healthConnectionIdInput } from "@/lib/validations/health-connect"; +import { assertHealthConnectEnabled } from "@/lib/personal/health-connect/flags"; +export async function POST(request: NextRequest) { + return wellnessPost(request, "health-revoke", 12, healthConnectionIdInput, (db, userId, data) => { + assertHealthConnectEnabled(); + return revokeHealthConnection(db, userId, data.id); + }); +} diff --git a/src/app/api/me/connections/health-connect/route.ts b/src/app/api/me/connections/health-connect/route.ts new file mode 100644 index 00000000..2a205bd1 --- /dev/null +++ b/src/app/api/me/connections/health-connect/route.ts @@ -0,0 +1,6 @@ +import type { NextRequest } from "next/server"; +import { wellnessRead } from "@/lib/personal/wellness-http"; +import { listHealthConnections } from "@/lib/personal/health-connect/connections"; +export async function GET(request: NextRequest) { + return wellnessRead(request, (db, userId) => listHealthConnections(db, userId)); +} diff --git a/src/app/api/native/health-connect/batches/route.ts b/src/app/api/native/health-connect/batches/route.ts new file mode 100644 index 00000000..64cc4d8e --- /dev/null +++ b/src/app/api/native/health-connect/batches/route.ts @@ -0,0 +1,19 @@ +import type { NextRequest } from "next/server"; +import { prisma } from "@/lib/prisma"; +import { OnboardingError } from "@/lib/club-onboarding"; +import { jsonPrivate, onboardingFailure } from "@/lib/onboarding-http"; +import { requireHealthDevice } from "@/lib/personal/health-connect/native-http"; +import { acceptHealthBatch } from "@/lib/personal/health-connect/ingestion"; +import { readNativeBatch } from "@/lib/personal/health-connect/read-body"; +import { healthBatchInput } from "@/lib/validations/health-connect-batch"; + +export async function POST(request: NextRequest): Promise { + try { + const device = await requireHealthDevice(request); + const input = healthBatchInput.safeParse(await readNativeBatch(request)); + if (!input.success) throw new OnboardingError(400, "Invalid fitness sync batch."); + return jsonPrivate({ ok: true, ...(await acceptHealthBatch(prisma, device, input.data)) }); + } catch (error) { + return onboardingFailure(error); + } +} diff --git a/src/app/api/native/health-connect/claim/route.ts b/src/app/api/native/health-connect/claim/route.ts new file mode 100644 index 00000000..05bd0b1e --- /dev/null +++ b/src/app/api/native/health-connect/claim/route.ts @@ -0,0 +1,30 @@ +import type { NextRequest } from "next/server"; +import { prisma } from "@/lib/prisma"; +import { authLimiter } from "@/lib/auth"; +import { OnboardingError } from "@/lib/club-onboarding"; +import { jsonPrivate, onboardingFailure, readOnboardingBody } from "@/lib/onboarding-http"; +import { assertHealthConnectEnabled } from "@/lib/personal/health-connect/flags"; +import { rejectBrowserOrigin, limitNativeRequest } from "@/lib/personal/health-connect/native-http"; +import { claimHealthPairing, hashCapability } from "@/lib/personal/health-connect/connections"; +import { healthPairClaimInput } from "@/lib/validations/health-connect"; +export async function POST(request: NextRequest) { + try { + assertHealthConnectEnabled(); + rejectBrowserOrigin(request); + await limitNativeRequest(request, "claim-ip", 30); + const result = healthPairClaimInput.safeParse(await readOnboardingBody(request)); + if (!result.success) throw new OnboardingError(400, "Invalid pairing request."); + if (!authLimiter) throw new OnboardingError(503, "Security service unavailable."); + const decision = await authLimiter.consume( + "hc-pair-hash", + hashCapability(result.data.pairCode), + 600, + 5 + ); + if (decision.unavailable) throw new OnboardingError(503, "Security service unavailable."); + if (!decision.allowed) throw new OnboardingError(429, "Too many attempts."); + return jsonPrivate({ ok: true, ...(await claimHealthPairing(prisma, result.data)) }); + } catch (error) { + return onboardingFailure(error); + } +} diff --git a/src/app/api/native/health-connect/disconnect/route.ts b/src/app/api/native/health-connect/disconnect/route.ts new file mode 100644 index 00000000..a4a9c901 --- /dev/null +++ b/src/app/api/native/health-connect/disconnect/route.ts @@ -0,0 +1,16 @@ +import type { NextRequest } from "next/server"; +import { jsonPrivate, onboardingFailure } from "@/lib/onboarding-http"; +import { requireHealthDevice } from "@/lib/personal/health-connect/native-http"; +import { prisma } from "@/lib/prisma"; +export async function POST(request: NextRequest) { + try { + const d = await requireHealthDevice(request); + await prisma.healthConnectConnection.updateMany({ + where: { id: d.id, userId: d.userId, revokedAt: null }, + data: { revokedAt: new Date(), grantedTypes: [] }, + }); + return jsonPrivate({ ok: true, revoked: true }); + } catch (error) { + return onboardingFailure(error); + } +} diff --git a/src/app/api/native/health-connect/status/route.ts b/src/app/api/native/health-connect/status/route.ts new file mode 100644 index 00000000..8affd300 --- /dev/null +++ b/src/app/api/native/health-connect/status/route.ts @@ -0,0 +1,16 @@ +import type { NextRequest } from "next/server"; +import { jsonPrivate, onboardingFailure } from "@/lib/onboarding-http"; +import { requireHealthDevice } from "@/lib/personal/health-connect/native-http"; +import { prisma } from "@/lib/prisma"; +export async function GET(request: NextRequest) { + try { + const d = await requireHealthDevice(request); + await prisma.healthConnectConnection.updateMany({ + where: { id: d.id, revokedAt: null }, + data: { lastSeenAt: new Date() }, + }); + return jsonPrivate({ ok: true, connectionId: d.id, label: d.label }); + } catch (error) { + return onboardingFailure(error); + } +} diff --git a/src/app/me/connections/loading.tsx b/src/app/me/connections/loading.tsx new file mode 100644 index 00000000..10410c34 --- /dev/null +++ b/src/app/me/connections/loading.tsx @@ -0,0 +1,7 @@ +export default function Loading() { + return ( +

+ Loading connected sources… +

+ ); +} diff --git a/src/app/me/connections/page.tsx b/src/app/me/connections/page.tsx new file mode 100644 index 00000000..10e263c0 --- /dev/null +++ b/src/app/me/connections/page.tsx @@ -0,0 +1,70 @@ +import { notFound } from "next/navigation"; +import { prisma } from "@/lib/prisma"; +import { requireWellnessPage } from "@/lib/personal/wellness-page"; +import { listHealthConnections } from "@/lib/personal/health-connect/connections"; +import { listImportedFitness } from "@/lib/personal/health-connect/ingestion"; +import { HealthConnectControls } from "@/components/personal/health-connect-controls"; + +export default async function HealthConnectPage() { + if (process.env.PERSONAL_HEALTH_CONNECT_ENABLED !== "true") notFound(); + const userId = await requireWellnessPage(); + const [connections, records] = await Promise.all([ + listHealthConnections(prisma, userId), + listImportedFitness(prisma, userId), + ]); + return ( + <> +
+

Connected sources

+

Android Health Connect

+

+ Only fitness records you permit. Private to you and separate from every club. +

+
+ ({ + id: x.id, + label: x.label, + grantedTypes: x.grantedTypes, + lastSyncAt: x.lastSyncAt?.toISOString() ?? null, + revokedAt: x.revokedAt?.toISOString() ?? null, + tokenExpiresAt: x.tokenExpiresAt.toISOString(), + }))} + /> +
+

Recently imported records

+

+ Imported entries preserve their source. They do not replace manual workouts or medical + history. +

+ {records.length === 0 ? ( +

+ Nothing imported yet. Pair the Android companion, choose permissions, then tap Sync. +

+ ) : ( +
    + {records.slice(0, 25).map((x) => ( +
  • + + {x.recordType.replaceAll("_", " ").toLowerCase()} ·{" "} + {x.endedAt.toLocaleDateString()} + + + {x.value === null + ? "No numeric value" + : x.value + + (x.recordType === "STEPS_DAILY" + ? " steps" + : x.recordType === "HYDRATION" + ? " mL" + : " kcal")}{" "} + · {x.sourcePackage} + +
  • + ))} +
+ )} +
+ + ); +} diff --git a/src/app/me/page.tsx b/src/app/me/page.tsx index a1dcb57c..2f278700 100644 --- a/src/app/me/page.tsx +++ b/src/app/me/page.tsx @@ -40,6 +40,9 @@ export default async function TodayPage() { Nutrition Recovery Insights + {process.env.PERSONAL_HEALTH_CONNECT_ENABLED === "true" && ( + Connected sources + )} diff --git a/src/app/me/profile/page.tsx b/src/app/me/profile/page.tsx index 4ea4a944..db64e84d 100644 --- a/src/app/me/profile/page.tsx +++ b/src/app/me/profile/page.tsx @@ -1,3 +1,4 @@ +import Link from "next/link"; import { prisma } from "@/lib/prisma"; import { requireSession } from "@/lib/required-session"; import { getOverview } from "@/lib/personal/personal-service"; @@ -13,6 +14,17 @@ export default async function ProfilePage() {

Profile

+ {process.env.PERSONAL_HEALTH_CONNECT_ENABLED === "true" && ( +
+

Connected sources

+

+ Choose the Android fitness categories you allow and manage your imported copies. +

+ + Manage Health Connect + +
+ )} ); diff --git a/src/components/personal/health-connect-controls.tsx b/src/components/personal/health-connect-controls.tsx new file mode 100644 index 00000000..808700c2 --- /dev/null +++ b/src/components/personal/health-connect-controls.tsx @@ -0,0 +1,200 @@ +"use client"; + +import { useState, useTransition } from "react"; +import { useRouter } from "next/navigation"; +import { postJson } from "@/components/personal/post-json"; + +type Connection = { + id: string; + label: string; + grantedTypes: string[]; + lastSyncAt: string | null; + revokedAt: string | null; + tokenExpiresAt: string; +}; + +export function HealthConnectControls({ connections }: { connections: Connection[] }) { + const router = useRouter(); + const [pending, start] = useTransition(); + const [code, setCode] = useState(""); + const [expiration, setExpiration] = useState(""); + const [message, setMessage] = useState(""); + const [confirmErase, setConfirmErase] = useState(false); + const active = connections.filter((c) => !c.revokedAt && new Date(c.tokenExpiresAt) > new Date()); + function pair() { + start(async () => { + setCode(""); + setExpiration(""); + setMessage(""); + try { + const response = await fetch("/api/me/connections/health-connect/pair", { + method: "POST", + credentials: "same-origin", + cache: "no-store", + headers: { "content-type": "application/json" }, + body: "{}", + }); + const result = (await response.json()) as { + pairCode?: string; + expiresAt?: string; + error?: string; + }; + if (!response.ok || !result.pairCode) { + setMessage(result.error ?? "Unable to create pairing code."); + return; + } + setCode(result.pairCode); + setExpiration(result.expiresAt ?? ""); + setMessage("This code pairs one device and expires after 10 minutes. Keep it private."); + } catch { + setMessage("Connection failed. Try again."); + } + }); + } + function revoke(id: string) { + start(async () => { + const result = await postJson("/api/me/connections/health-connect/revoke", { id }); + setMessage( + result.ok ? "Device revoked. Existing imports remain until you delete them." : result.error + ); + if (result.ok) router.refresh(); + }); + } + function purge() { + start(async () => { + const result = await postJson("/api/me/connections/health-connect/purge", { confirm: true }); + setMessage(result.ok ? "Connections revoked and imported copies deleted." : result.error); + setConfirmErase(false); + setCode(""); + setExpiration(""); + if (result.ok) router.refresh(); + }); + } + return ( + <> +
+

Pair your Android companion

+

+ Sign in to ClubKeep on the web, then copy this one-time code into the native Android + companion. The companion is not available through Play yet; initial installation requires + a reviewed test build. Health Connect permissions are requested only on your phone. +

+ + {code && ( +
+

One-time pairing code — never share it publicly

+ {code} +
+ + {expiration && ( + + Expires {new Date(expiration).toLocaleTimeString()} + + )} +
+
+ )} +
+
+

Connected Android devices

+

+ Permission categories below are last reported by each device; manage actual grants in + Android Health Connect settings. +

+ {connections.length === 0 ? ( +

No paired devices.

+ ) : ( + connections.map((c) => ( +
+
+ {c.label} + + {c.revokedAt + ? "Disconnected" + : new Date(c.tokenExpiresAt) < new Date() + ? "Re-pair required" + : "Linked"} + +
+

+ Last successful sync:{" "} + {c.lastSyncAt ? new Date(c.lastSyncAt).toLocaleString() : "Not yet synced"} +

+

+ Last reported categories:{" "} + {c.grantedTypes.length ? c.grantedTypes.join(", ") : "None"} +

+ {!c.revokedAt && ( + + )} +
+ )) + )} +
+
+

Remove imported copies

+

+ Disconnects every Health Connect device, then permanently erases its imported records from + ClubKeep Personal. It does not delete the originals stored on your phone. Manual entries + and club membership remain intact. +

+ {!confirmErase ? ( + + ) : ( +
+ + +
+ )} +
+ {message && ( +

+ {message} +

+ )} + + ); +} diff --git a/src/components/personal/personal.css b/src/components/personal/personal.css index 98fe8759..3d87f67c 100644 --- a/src/components/personal/personal.css +++ b/src/components/personal/personal.css @@ -184,3 +184,15 @@ grid-template-columns: repeat(3, minmax(0, 1fr)); } } + +.hm-hc-pair-code { + display: block; + overflow-wrap: anywhere; + padding: 1rem; + border-radius: 12px; + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; + font-size: 1.1rem; + background: var(--hm-raised); + border: 1px dashed var(--hm-line); + user-select: all; +} diff --git a/src/components/personal/wellness-insights.tsx b/src/components/personal/wellness-insights.tsx index 542cc4f7..a2582093 100644 --- a/src/components/personal/wellness-insights.tsx +++ b/src/components/personal/wellness-insights.tsx @@ -31,6 +31,34 @@ export async function WellnessInsightsSection({ userId }: { userId: string }) { {insights.thisWeek.hydrationMl} mL + {process.env.PERSONAL_HEALTH_CONNECT_ENABLED === "true" && ( +
+
+

Health Connect

+ + Manage sources + +
+
+

+ {insights.importedThisWeek.steps} + steps reported this week +

+

+ {insights.importedThisWeek.workoutRecords} + imported exercise records +

+

+ {insights.importedThisWeek.waterMl} + mL imported hydration +

+
+

+ Imported workouts can overlap across source apps and are not added to manual goals + automatically. +

+
+ )}

Active goals

{insights.goals.length === 0 ? (

Add a goal to see your measured progress.

diff --git a/src/lib/personal/health-connect/connections.ts b/src/lib/personal/health-connect/connections.ts new file mode 100644 index 00000000..72732ff5 --- /dev/null +++ b/src/lib/personal/health-connect/connections.ts @@ -0,0 +1,136 @@ +import { createHash, randomBytes } from "node:crypto"; +import type { PrismaClient } from "@/generated/prisma/client"; +import { OnboardingError } from "@/lib/club-onboarding"; +import { assertHealthConnectEnabled } from "./flags"; +import { assertWellnessAdult } from "@/lib/personal/wellness-policy"; + +const PAIR_LIFETIME_MS = 10 * 60_000; +const DEVICE_LIFETIME_MS = 30 * 86400000; +const MAX_DEVICES = 4; +export function hashCapability(value: string): string { + return createHash("sha256").update(value, "utf8").digest("hex"); +} +export function newCapability(): string { + return randomBytes(32).toString("base64url"); +} + +/** Public device state only: never expose bearer tokens or capability hashes. */ +export async function listHealthConnections(db: PrismaClient, userId: string) { + assertHealthConnectEnabled(); + await assertWellnessAdult(db, userId); + return db.healthConnectConnection.findMany({ + where: { userId }, + select: { + id: true, + label: true, + grantedTypes: true, + createdAt: true, + lastSyncAt: true, + lastSeenAt: true, + revokedAt: true, + tokenExpiresAt: true, + }, + orderBy: { createdAt: "desc" }, + take: 20, + }); +} + +export async function beginHealthPairing(db: PrismaClient, userId: string) { + assertHealthConnectEnabled(); + await assertWellnessAdult(db, userId); + const now = new Date(); + const active = await db.healthConnectConnection.count({ + where: { userId, revokedAt: null, tokenExpiresAt: { gt: now } }, + }); + if (active >= MAX_DEVICES) throw new OnboardingError(409, "Disconnect an older device first."); + await db.healthConnectPairing.deleteMany({ where: { userId, expiresAt: { lt: now } } }); + const pairCode = newCapability(); + const expiresAt = new Date(now.getTime() + PAIR_LIFETIME_MS); + await db.healthConnectPairing.create({ + data: { userId, codeHash: hashCapability(pairCode), expiresAt }, + }); + return { pairCode, expiresAt: expiresAt.toISOString() }; +} + +export async function claimHealthPairing( + db: PrismaClient, + input: { pairCode: string; installationId: string; label: string } +) { + assertHealthConnectEnabled(); + const codeHash = hashCapability(input.pairCode); + const now = new Date(); + const token = newCapability(); + const tokenHash = hashCapability(token); + const expiresAt = new Date(now.getTime() + DEVICE_LIFETIME_MS); + const connectionId = await db.$transaction(async (tx) => { + const pair = await tx.healthConnectPairing.findUnique({ where: { codeHash } }); + if (!pair || pair.claimedAt || pair.expiresAt <= now) + throw new OnboardingError(401, "Pairing code is invalid or expired."); + const profile = await tx.personalProfile.findUnique({ + where: { userId: pair.userId }, + select: { birthYear: true }, + }); + if (!profile?.birthYear || now.getUTCFullYear() - profile.birthYear < 19) + throw new OnboardingError(403, "Adult Personal access required."); + const consumed = await tx.healthConnectPairing.updateMany({ + where: { id: pair.id, claimedAt: null, expiresAt: { gt: now } }, + data: { claimedAt: now }, + }); + if (consumed.count !== 1) throw new OnboardingError(401, "Pairing code already used."); + const previous = await tx.healthConnectConnection.findUnique({ + where: { + userId_installationId: { userId: pair.userId, installationId: input.installationId }, + }, + }); + if (!previous) { + const active = await tx.healthConnectConnection.count({ + where: { userId: pair.userId, revokedAt: null, tokenExpiresAt: { gt: now } }, + }); + if (active >= MAX_DEVICES) throw new OnboardingError(409, "Device limit reached."); + } + const connection = await tx.healthConnectConnection.upsert({ + where: { + userId_installationId: { userId: pair.userId, installationId: input.installationId }, + }, + create: { + userId: pair.userId, + installationId: input.installationId, + label: input.label, + tokenHash, + tokenExpiresAt: expiresAt, + }, + update: { + label: input.label, + tokenHash, + tokenExpiresAt: expiresAt, + revokedAt: null, + grantedTypes: [], + lastSyncAt: null, + }, + select: { id: true }, + }); + return connection.id; + }); + return { connectionId, token, expiresAt: expiresAt.toISOString() }; +} + +export async function revokeHealthConnection(db: PrismaClient, userId: string, id: string) { + const changed = await db.healthConnectConnection.updateMany({ + where: { id, userId, revokedAt: null }, + data: { revokedAt: new Date(), grantedTypes: [] }, + }); + if (!changed.count) throw new OnboardingError(404, "Active connection not found."); + return { revoked: true }; +} + +export async function purgeHealthImports(db: PrismaClient, userId: string) { + await db.$transaction([ + db.healthConnectConnection.updateMany({ + where: { userId, revokedAt: null }, + data: { revokedAt: new Date(), grantedTypes: [] }, + }), + db.healthConnectRecord.deleteMany({ where: { userId } }), + db.healthConnectPairing.deleteMany({ where: { userId } }), + ]); + return { removed: true, connectionsRevoked: true }; +} diff --git a/src/lib/personal/health-connect/flags.ts b/src/lib/personal/health-connect/flags.ts new file mode 100644 index 00000000..9985368f --- /dev/null +++ b/src/lib/personal/health-connect/flags.ts @@ -0,0 +1,11 @@ +import { OnboardingError } from "@/lib/club-onboarding"; +import { assertWellnessEnabled } from "@/lib/personal/wellness-policy"; + +// A production activation requires BOTH independent feature gates. +// An unfinished native companion must never create a public fitness ingestion endpoint. +export function assertHealthConnectEnabled(): void { + assertWellnessEnabled(); + if (process.env.PERSONAL_HEALTH_CONNECT_ENABLED !== "true") { + throw new OnboardingError(503, "Health Connect sync is not enabled yet."); + } +} diff --git a/src/lib/personal/health-connect/ingestion.ts b/src/lib/personal/health-connect/ingestion.ts new file mode 100644 index 00000000..a9d7829c --- /dev/null +++ b/src/lib/personal/health-connect/ingestion.ts @@ -0,0 +1,146 @@ +import { createHash } from "node:crypto"; +import type { PrismaClient } from "@/generated/prisma/client"; +import { OnboardingError } from "@/lib/club-onboarding"; +import type { HealthBatchInput } from "@/lib/validations/health-connect-batch"; + +const hashBatch = (body: HealthBatchInput) => + createHash("sha256").update(JSON.stringify(body)).digest("hex"); + +/** Every batch is all-or-nothing, scoped to one active device and user. */ +export async function acceptHealthBatch( + db: PrismaClient, + device: { id: string; userId: string }, + body: HealthBatchInput, + now = new Date() +) { + const digest = hashBatch(body); + const known = await db.healthConnectSyncBatch.findUnique({ + where: { connectionId_requestId: { connectionId: device.id, requestId: body.requestId } }, + }); + if (known) { + if (known.contentHash !== digest) + throw new OnboardingError(409, "Batch ID used with different content."); + return { imported: known.importedCount, deleted: known.deletedCount, replayed: true }; + } + + try { + return await db.$transaction(async (tx) => { + // A device revocation or Personal purge acquires the same connection row lock. + await tx.$queryRaw`SELECT "id" FROM "HealthConnectConnection" WHERE "id" = ${device.id} FOR UPDATE`; + const current = await tx.healthConnectConnection.findUnique({ + where: { id: device.id }, + select: { userId: true, revokedAt: true, tokenExpiresAt: true }, + }); + if ( + !current || + current.userId !== device.userId || + current.revokedAt || + current.tokenExpiresAt <= now + ) + throw new OnboardingError(401, "Connection expired or revoked."); + const old = await tx.healthConnectSyncBatch.findUnique({ + where: { connectionId_requestId: { connectionId: device.id, requestId: body.requestId } }, + }); + if (old) { + if (old.contentHash !== digest) throw new OnboardingError(409, "Batch content changed."); + return { imported: old.importedCount, deleted: old.deletedCount, replayed: true }; + } + for (const record of body.records) { + const key = { + userId: device.userId, + recordType: record.recordType, + sourcePackage: record.sourcePackage, + externalId: record.externalId, + }; + // Important: never resurrect a tombstoned record on stale duplicate replay. + await tx.healthConnectRecord.upsert({ + where: { userId_recordType_sourcePackage_externalId: key }, + create: { + ...key, + startedAt: new Date(record.startedAt), + endedAt: new Date(record.endedAt), + value: record.value, + exerciseType: record.exerciseType, + lastDeviceId: device.id, + lastSeenAt: now, + }, + update: { + startedAt: new Date(record.startedAt), + endedAt: new Date(record.endedAt), + value: record.value ?? null, + exerciseType: record.exerciseType ?? null, + lastDeviceId: device.id, + lastSeenAt: now, + // deletedAt is deliberately never nulled by an ordinary upsert. + }, + }); + } + for (const record of body.deletions) { + const key = { + userId: device.userId, + recordType: record.recordType, + sourcePackage: record.sourcePackage, + externalId: record.externalId, + }; + await tx.healthConnectRecord.upsert({ + where: { userId_recordType_sourcePackage_externalId: key }, + create: { + ...key, + startedAt: new Date(now.getTime() - 1000), + endedAt: now, + value: record.recordType === "STEPS_DAILY" ? 0 : null, + deletedAt: now, + lastDeviceId: device.id, + lastSeenAt: now, + }, + update: { deletedAt: now, lastDeviceId: device.id, lastSeenAt: now }, + }); + } + await tx.healthConnectSyncBatch.create({ + data: { + connectionId: device.id, + requestId: body.requestId, + contentHash: digest, + importedCount: body.records.length, + deletedCount: body.deletions.length, + }, + }); + await tx.healthConnectConnection.updateMany({ + where: { id: device.id, userId: device.userId, revokedAt: null }, + data: { lastSyncAt: now, lastSeenAt: now, grantedTypes: body.grantedTypes }, + }); + return { imported: body.records.length, deleted: body.deletions.length, replayed: false }; + }); + } catch (error) { + // A concurrent replay can hit the unique constraint before its own lookup. + if (typeof error === "object" && error !== null && "code" in error && error.code === "P2002") { + const result = await db.healthConnectSyncBatch.findUnique({ + where: { connectionId_requestId: { connectionId: device.id, requestId: body.requestId } }, + }); + if (result) { + if (result.contentHash !== digest) + throw new OnboardingError(409, "Batch ID used with different content."); + return { imported: result.importedCount, deleted: result.deletedCount, replayed: true }; + } + } + throw error; + } +} + +/** Single source of truth: imported copies never overwrite user-entered Manual rows. */ +export async function listImportedFitness(db: PrismaClient, userId: string) { + return db.healthConnectRecord.findMany({ + where: { userId, deletedAt: null }, + orderBy: { endedAt: "desc" }, + take: 150, + select: { + id: true, + recordType: true, + startedAt: true, + endedAt: true, + value: true, + exerciseType: true, + sourcePackage: true, + }, + }); +} diff --git a/src/lib/personal/health-connect/native-http.ts b/src/lib/personal/health-connect/native-http.ts new file mode 100644 index 00000000..e7a7e77b --- /dev/null +++ b/src/lib/personal/health-connect/native-http.ts @@ -0,0 +1,56 @@ +import type { NextRequest } from "next/server"; +import { authLimiter } from "@/lib/auth"; +import { resolveAuthConfig } from "@/lib/auth-config"; +import { OnboardingError } from "@/lib/club-onboarding"; +import { jsonPrivate, onboardingFailure, readOnboardingBody } from "@/lib/onboarding-http"; +import { prisma } from "@/lib/prisma"; +import { hashCapability } from "./connections"; +import { assertHealthConnectEnabled } from "./flags"; +import { assertWellnessAdult } from "@/lib/personal/wellness-policy"; + +export function rejectBrowserOrigin(request: NextRequest): void { + if (request.headers.has("origin") || request.headers.has("sec-fetch-site")) + throw new OnboardingError(403, "Native companion only."); +} +export async function limitNativeRequest(request: NextRequest, scope: string, max: number) { + if (!authLimiter) throw new OnboardingError(503, "Security service unavailable."); + const config = resolveAuthConfig(); + const ip = config.trustedIpHeader + ? (request.headers.get(config.trustedIpHeader) ?? "unknown") + : "unknown"; + const result = await authLimiter.consume("hc-native:" + scope, ip, 3600, max); + if (result.unavailable) throw new OnboardingError(503, "Security service unavailable."); + if (!result.allowed) throw new OnboardingError(429, "Too many requests."); +} +export async function requireHealthDevice(request: NextRequest) { + assertHealthConnectEnabled(); + rejectBrowserOrigin(request); + const value = request.headers.get("authorization") ?? ""; + if (!/^Bearer [A-Za-z0-9_-]{43}$/.test(value)) + throw new OnboardingError(401, "Pair the Android device again."); + const device = await prisma.healthConnectConnection.findUnique({ + where: { tokenHash: hashCapability(value.slice(7)) }, + select: { id: true, userId: true, revokedAt: true, tokenExpiresAt: true, label: true }, + }); + if (!device || device.revokedAt || device.tokenExpiresAt <= new Date()) + throw new OnboardingError(401, "Connection expired or revoked."); + await assertWellnessAdult(prisma, device.userId); + await limitNativeRequest(request, "device-" + device.id, 600); + return device; +} +export async function nativePost( + request: NextRequest, + handler: ( + device: Awaited>, + body: unknown + ) => Promise +): Promise { + try { + const device = await requireHealthDevice(request); + const body = await readOnboardingBody(request); + const result = await handler(device, body); + return jsonPrivate({ ok: true, ...(result && typeof result === "object" ? result : {}) }); + } catch (error) { + return onboardingFailure(error); + } +} diff --git a/src/lib/personal/health-connect/read-body.ts b/src/lib/personal/health-connect/read-body.ts new file mode 100644 index 00000000..37ce5471 --- /dev/null +++ b/src/lib/personal/health-connect/read-body.ts @@ -0,0 +1,32 @@ +import type { NextRequest } from "next/server"; +import { OnboardingError } from "@/lib/club-onboarding"; + +/** Native uploads have a larger limit than the 4KB web mutation guard. */ +export async function readNativeBatch(request: NextRequest): Promise { + if (!request.headers.get("content-type")?.toLowerCase().startsWith("application/json")) + throw new OnboardingError(415, "Expected JSON."); + const reader = request.body?.getReader(); + if (!reader) throw new OnboardingError(400, "Body required."); + const decoder = new TextDecoder("utf-8", { fatal: true }); + let body = "", + bytes = 0; + try { + for (;;) { + const part = await reader.read(); + if (part.done) break; + bytes += part.value.byteLength; + if (bytes > 65536) { + await reader.cancel(); + throw new OnboardingError(413, "Native upload too large."); + } + body += decoder.decode(part.value, { stream: true }); + } + body += decoder.decode(); + return JSON.parse(body) as unknown; + } catch (error) { + if (error instanceof OnboardingError) throw error; + throw new OnboardingError(400, "Invalid JSON."); + } finally { + reader.releaseLock(); + } +} diff --git a/src/lib/personal/personal-service.ts b/src/lib/personal/personal-service.ts index d197aec4..52c42337 100644 --- a/src/lib/personal/personal-service.ts +++ b/src/lib/personal/personal-service.ts @@ -230,6 +230,8 @@ export async function exportPersonalData(db: PrismaClient, userId: string, now = hydration, recovery, sources, + importedFitness, + connectedDevices, ] = await Promise.all([ db.personalMeasurement.findMany({ where: { userId }, @@ -254,6 +256,19 @@ export async function exportPersonalData(db: PrismaClient, userId: string, now = db.hydrationEntry.findMany({ where: { userId } }), db.recoveryCheckIn.findMany({ where: { userId } }), db.wellnessSourceRecord.findMany({ where: { userId } }), + db.healthConnectRecord.findMany({ where: { userId }, orderBy: { endedAt: "asc" } }), + db.healthConnectConnection.findMany({ + where: { userId }, + select: { + id: true, + label: true, + installationId: true, + grantedTypes: true, + lastSyncAt: true, + revokedAt: true, + createdAt: true, + }, + }), ]); const units = profile.units as Units; return { @@ -275,6 +290,7 @@ export async function exportPersonalData(db: PrismaClient, userId: string, now = activities, clubSignalConsents: consents, wellness: { goals, workouts, sleep, meals, hydration, recovery, sources }, + healthConnect: { importedFitness, connectedDevices }, }; } @@ -292,6 +308,10 @@ export async function deleteAllPersonalData(db: PrismaClient, userId: string) { db.hydrationEntry.deleteMany({ where: { userId } }), db.recoveryCheckIn.deleteMany({ where: { userId } }), db.wellnessSourceRecord.deleteMany({ where: { userId } }), + // Erasure also invalidates native credentials; related batches cascade. + db.healthConnectRecord.deleteMany({ where: { userId } }), + db.healthConnectPairing.deleteMany({ where: { userId } }), + db.healthConnectConnection.deleteMany({ where: { userId } }), db.personalProfile.updateMany({ where: { userId }, data: { diff --git a/src/lib/personal/wellness-insights.ts b/src/lib/personal/wellness-insights.ts index fdbaf4c9..76b4e80a 100644 --- a/src/lib/personal/wellness-insights.ts +++ b/src/lib/personal/wellness-insights.ts @@ -3,7 +3,7 @@ import { localDate, mondayUtc, safeRate, sleepMinutes } from "./wellness-rules"; export async function wellnessInsights(db: PrismaClient, userId: string, now = new Date()) { const since = new Date(now.getTime() - 90 * 86400000); - const [profile, workouts, sleeps, waters, meals, recovery, goals] = await Promise.all([ + const [profile, workouts, sleeps, waters, meals, recovery, goals, imports] = await Promise.all([ db.personalProfile.findUnique({ where: { userId }, select: { timezone: true } }), db.workoutSession.findMany({ where: { userId, endedAt: { gte: since, lte: now } }, @@ -31,6 +31,11 @@ export async function wellnessInsights(db: PrismaClient, userId: string, now = n select: { localDate: true, energy: true, soreness: true, stress: true, satisfaction: true }, }), db.personalGoalInstance.findMany({ where: { userId, status: "ACTIVE" }, take: 20 }), + db.healthConnectRecord.findMany({ + where: { userId, deletedAt: null, endedAt: { gte: since, lte: now } }, + select: { recordType: true, externalId: true, endedAt: true, value: true }, + take: 15000, + }), ]); const zone = profile?.timezone ?? "UTC"; const days = new Map< @@ -43,6 +48,10 @@ export async function wellnessInsights(db: PrismaClient, userId: string, now = n hydrationMl: number | null; meals: number; energy: number | null; + importedSteps: number | null; + importedWorkouts: number; + importedSleepMinutes: number | null; + importedWaterMl: number | null; } >(); const day = (d: string) => { @@ -56,6 +65,10 @@ export async function wellnessInsights(db: PrismaClient, userId: string, now = n hydrationMl: null, meals: 0, energy: null, + importedSteps: null, + importedWorkouts: 0, + importedSleepMinutes: null, + importedWaterMl: null, }; days.set(d, entry); } @@ -77,6 +90,21 @@ export async function wellnessInsights(db: PrismaClient, userId: string, now = n } for (const m of meals) day(localDate(m.eatenAt, zone)).meals += 1; for (const r of recovery) day(r.localDate).energy = r.energy; + // Raw imported sources remain separate from manual metrics to avoid pretending + // that mirrored device workouts are necessarily distinct sessions. + for (const r of imports) { + const date = r.recordType === "STEPS_DAILY" ? r.externalId : localDate(r.endedAt, zone); + const d = day(date); + if (r.recordType === "STEPS_DAILY") d.importedSteps = r.value; + if (r.recordType === "WORKOUT") d.importedWorkouts += 1; + if (r.recordType === "SLEEP") { + // Duration for imported sleep is deliberately shown only in Connection history + // until source-comparability and nap semantics are fully reconciled. + d.importedSleepMinutes = null; + } + if (r.recordType === "HYDRATION") d.importedWaterMl = (d.importedWaterMl ?? 0) + (r.value ?? 0); + } + const today = localDate(now, zone); const weekStart = mondayUtc(new Date(today + "T12:00:00Z")) .toISOString() @@ -91,6 +119,14 @@ export async function wellnessInsights(db: PrismaClient, userId: string, now = n }), { workouts: 0, activityMinutes: 0, sleepMinutes: 0, hydrationMl: 0 } ); + const importedThisWeek = weekly.reduce( + (a, d) => ({ + steps: a.steps + (d.importedSteps ?? 0), + workoutRecords: a.workoutRecords + d.importedWorkouts, + waterMl: a.waterMl + (d.importedWaterMl ?? 0), + }), + { steps: 0, workoutRecords: 0, waterMl: 0 } + ); const goalProgress = await Promise.all( goals.map(async (goal) => { // TOTAL goals must not silently truncate to the 90-day chart horizon. @@ -136,12 +172,13 @@ export async function wellnessInsights(db: PrismaClient, userId: string, now = n today, timezone: zone, thisWeek, + importedThisWeek, goals: goalProgress, days: [...days.values()] .filter((x) => x.date <= today) .sort((a, b) => a.date.localeCompare(b.date)) .slice(-90), disclosure: - "Manual observations and completed workouts only. Missing data is not zero. No clinical recovery score.", + "Manual goal progress is kept separate from imported device observations to prevent unverified double counts. Missing data is not zero. No clinical recovery score.", }; } diff --git a/src/lib/validations/health-connect-batch.ts b/src/lib/validations/health-connect-batch.ts new file mode 100644 index 00000000..7ea624f1 --- /dev/null +++ b/src/lib/validations/health-connect-batch.ts @@ -0,0 +1,99 @@ +import { z } from "zod"; +export const healthRecordTypes = [ + "STEPS_DAILY", + "WORKOUT", + "SLEEP", + "ACTIVE_CALORIES", + "HYDRATION", +] as const; +export type HealthRecordType = (typeof healthRecordTypes)[number]; +const kind = z.enum(healthRecordTypes); +const stableId = z + .string() + .min(1) + .max(160) + .regex(/^[a-zA-Z0-9_.:@\/-]+$/); +const source = z + .string() + .min(2) + .max(160) + .regex(/^[a-zA-Z0-9_.-]+$/); +export const healthRecordInput = z + .object({ + recordType: kind, + externalId: stableId, + sourcePackage: source, + startedAt: z.iso.datetime({ offset: true }), + endedAt: z.iso.datetime({ offset: true }), + value: z.number().int().min(0).max(5000000).optional(), + exerciseType: z.number().int().min(0).max(100000).optional(), + }) + .strict(); +export const healthDeletionInput = z + .object({ + recordType: kind, + externalId: stableId, + sourcePackage: source, + }) + .strict(); +export const healthBatchInput = z + .object({ + requestId: z.uuid(), + grantedTypes: z + .array(kind) + .max(5) + .refine((v) => new Set(v).size === v.length), + records: z.array(healthRecordInput).max(80).default([]), + deletions: z.array(healthDeletionInput).max(80).default([]), + }) + .strict() + .superRefine((v, ctx) => { + if (v.records.length + v.deletions.length > 80) { + ctx.addIssue({ code: "custom", message: "Batch size exceeded" }); + } + const ids = new Set(); + for (const item of [...v.records, ...v.deletions]) { + const key = item.recordType + ":" + item.sourcePackage + ":" + item.externalId; + if (ids.has(key)) + ctx.addIssue({ code: "custom", message: "Duplicate source record in batch" }); + ids.add(key); + } + for (const item of v.records) { + if (!v.grantedTypes.includes(item.recordType)) + ctx.addIssue({ code: "custom", message: "Record type has not been reported as granted" }); + const a = Date.parse(item.startedAt), + b = Date.parse(item.endedAt); + const maxHours = item.recordType === "STEPS_DAILY" ? 26 : 24; + if ( + !Number.isFinite(a) || + !Number.isFinite(b) || + b <= a || + b - a > maxHours * 3600000 || + a < Date.UTC(2000, 0, 1) || + b > Date.now() + 5 * 60000 + ) + ctx.addIssue({ code: "custom", message: "Invalid record time range" }); + if ( + item.recordType === "STEPS_DAILY" && + (item.sourcePackage !== "health-connect-aggregate" || + item.value === undefined || + item.exerciseType !== undefined) + ) + ctx.addIssue({ + code: "custom", + message: "Step totals must come from the Health Connect aggregate API", + }); + if ( + ["HYDRATION", "ACTIVE_CALORIES"].includes(item.recordType) && + (item.value === undefined || item.exerciseType !== undefined) + ) + ctx.addIssue({ code: "custom", message: "A measured value is required" }); + if (item.recordType === "HYDRATION" && item.value !== undefined && item.value > 5000) + ctx.addIssue({ code: "custom", message: "Hydration entry too large" }); + if (["WORKOUT", "SLEEP"].includes(item.recordType) && item.value !== undefined) + ctx.addIssue({ code: "custom", message: "Duration is derived from timestamps" }); + if (item.recordType !== "WORKOUT" && item.exerciseType !== undefined) + ctx.addIssue({ code: "custom", message: "Exercise type applies only to workouts" }); + } + }); +export type HealthBatchInput = z.infer; diff --git a/src/lib/validations/health-connect.ts b/src/lib/validations/health-connect.ts new file mode 100644 index 00000000..9e10dc5d --- /dev/null +++ b/src/lib/validations/health-connect.ts @@ -0,0 +1,10 @@ +import { z } from "zod"; +export const healthPairClaimInput = z + .object({ + pairCode: z.string().regex(/^[A-Za-z0-9_-]{43}$/), + installationId: z.uuid(), + label: z.string().trim().min(2).max(80), + }) + .strict(); +export const healthConnectionIdInput = z.object({ id: z.string().min(10).max(128) }).strict(); +export const healthPurgeInput = z.object({ confirm: z.literal(true) }).strict(); diff --git a/tests/integration/p1c-health-connect.test.mjs b/tests/integration/p1c-health-connect.test.mjs new file mode 100644 index 00000000..70056548 --- /dev/null +++ b/tests/integration/p1c-health-connect.test.mjs @@ -0,0 +1,141 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { randomUUID } from "node:crypto"; +import { register } from "node:module"; +import pg from "pg"; +assert.ok(process.env.DATABASE_URL, "Use disposable migrated PostgreSQL 17"); +register("./helpers/src-alias-hook.mjs", import.meta.url); +process.env.PERSONAL_WELLNESS_ENABLED = "true"; +process.env.PERSONAL_HEALTH_CONNECT_ENABLED = "true"; +const { PrismaClient } = await import("../../src/generated/prisma/client.ts"); +const { PrismaPg } = await import("@prisma/adapter-pg"); +const [accounts, ingest, personal, schemas] = await Promise.all([ + import("../../src/lib/personal/health-connect/connections.ts"), + import("../../src/lib/personal/health-connect/ingestion.ts"), + import("../../src/lib/personal/personal-service.ts"), + import("../../src/lib/validations/health-connect-batch.ts"), +]); +const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); +const db = new PrismaClient({ adapter: new PrismaPg(pool) }); +test.after(() => pool.end()); + +test("P1-C pairing, replay-safety, owner-only reading, tombstones, purge and full erase", async () => { + const me = await db.user.create({ + data: { name: "Fitness test", email: randomUUID() + "@example.invalid" }, + }); + const other = await db.user.create({ + data: { name: "Unrelated", email: randomUUID() + "@example.invalid" }, + }); + try { + await personal.updateBio(db, me.id, { birthYear: 1990 }); + await personal.updateBio(db, other.id, { birthYear: 1990 }); + const pair = await accounts.beginHealthPairing(db, me.id); + assert.match(pair.pairCode, /^[A-Za-z0-9_-]{43}$/); + const install = randomUUID(); + const claim = await accounts.claimHealthPairing(db, { + pairCode: pair.pairCode, + installationId: install, + label: "Android test", + }); + assert.match(claim.token, /^[A-Za-z0-9_-]{43}$/); + await assert.rejects( + accounts.claimHealthPairing(db, { + pairCode: pair.pairCode, + installationId: randomUUID(), + label: "Replay", + }), + (err) => err.status === 401 + ); + const [mine, theirs] = await Promise.all([ + accounts.listHealthConnections(db, me.id), + accounts.listHealthConnections(db, other.id), + ]); + assert.equal(mine.length, 1); + assert.equal(theirs.length, 0); + assert.ok(!JSON.stringify(mine).includes(claim.token)); + assert.ok(!JSON.stringify(mine).includes(accounts.hashCapability(claim.token))); + + const item = { + recordType: "STEPS_DAILY", + externalId: "2026-11-18", + sourcePackage: "health-connect-aggregate", + startedAt: "2026-11-18T00:00:00Z", + endedAt: "2026-11-18T23:59:00Z", + value: 5000, + }; + const body = schemas.healthBatchInput.parse({ + requestId: randomUUID(), + grantedTypes: ["STEPS_DAILY"], + records: [item], + deletions: [], + }); + const device = { id: claim.connectionId, userId: me.id }; + const first = await ingest.acceptHealthBatch(db, device, body); + assert.equal(first.imported, 1); + assert.equal((await ingest.acceptHealthBatch(db, device, body)).replayed, true); + await assert.rejects( + ingest.acceptHealthBatch(db, device, { + ...body, + records: [{ ...item, value: 7777 }], + }), + (err) => err.status === 409 + ); + assert.equal(await db.healthConnectRecord.count({ where: { userId: me.id } }), 1); + assert.equal((await ingest.listImportedFitness(db, other.id)).length, 0); + const exported = await personal.exportPersonalData(db, me.id); + assert.equal(exported.healthConnect.importedFitness.length, 1); + assert.ok(!JSON.stringify(exported).includes(claim.token)); + assert.ok(!JSON.stringify(exported).includes(accounts.hashCapability(claim.token))); + + const tombstone = schemas.healthBatchInput.parse({ + requestId: randomUUID(), + grantedTypes: ["STEPS_DAILY"], + records: [], + deletions: [ + { + recordType: "STEPS_DAILY", + externalId: item.externalId, + sourcePackage: item.sourcePackage, + }, + ], + }); + await ingest.acceptHealthBatch(db, device, tombstone); + assert.equal((await ingest.listImportedFitness(db, me.id)).length, 0); + await ingest.acceptHealthBatch(db, device, { + ...body, + requestId: randomUUID(), + }); // stale snapshot must not resurrect deleted data + assert.equal((await ingest.listImportedFitness(db, me.id)).length, 0); + await accounts.purgeHealthImports(db, me.id); + assert.equal(await db.healthConnectRecord.count({ where: { userId: me.id } }), 0); + assert.ok( + (await db.healthConnectConnection.findUnique({ where: { id: device.id } })).revokedAt + ); + await assert.rejects( + ingest.acceptHealthBatch(db, device, { + ...body, + requestId: randomUUID(), + }), + (err) => err.status === 401 + ); + + const secondPair = await accounts.beginHealthPairing(db, me.id); + const second = await accounts.claimHealthPairing(db, { + pairCode: secondPair.pairCode, + installationId: randomUUID(), + label: "Second Android", + }); + assert.ok(second.connectionId); + await personal.deleteAllPersonalData(db, me.id); + assert.equal(await db.healthConnectConnection.count({ where: { userId: me.id } }), 0); + assert.equal(await db.healthConnectPairing.count({ where: { userId: me.id } }), 0); + assert.equal( + await db.healthConnectSyncBatch.count({ where: { connectionId: second.connectionId } }), + 0 + ); + assert.equal(await db.healthConnectRecord.count({ where: { userId: me.id } }), 0); + assert.ok(await db.user.findUnique({ where: { id: me.id } })); + } finally { + await db.user.deleteMany({ where: { id: { in: [me.id, other.id] } } }); + } +}); diff --git a/tests/unit/health-connect-validation.test.mjs b/tests/unit/health-connect-validation.test.mjs new file mode 100644 index 00000000..1827c9f0 --- /dev/null +++ b/tests/unit/health-connect-validation.test.mjs @@ -0,0 +1,98 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { register } from "node:module"; +register("../integration/helpers/src-alias-hook.mjs", import.meta.url); +const { healthBatchInput } = await import("../../src/lib/validations/health-connect-batch.ts"); +const base = { + requestId: "0a1f57e1-0e68-4a4a-823b-0e8110f6c866", + grantedTypes: ["STEPS_DAILY"], + deletions: [], + records: [ + { + recordType: "STEPS_DAILY", + externalId: "2026-11-18", + sourcePackage: "health-connect-aggregate", + startedAt: "2026-11-18T00:00:00Z", + endedAt: "2026-11-18T23:59:00Z", + value: 4200, + }, + ], +}; +test("P1-C accepts only health fitness observations with explicit reported grants", () => { + assert.equal(healthBatchInput.parse(base).records[0].value, 4200); + assert.equal( + healthBatchInput.safeParse({ + ...base, + grantedTypes: [], + records: base.records, + }).success, + false + ); + assert.equal( + healthBatchInput.safeParse({ + ...base, + records: [{ ...base.records[0], diagnosis: "secret" }], + }).success, + false + ); + assert.equal( + healthBatchInput.safeParse({ + ...base, + records: [{ ...base.records[0], recordType: "BLOOD_GLUCOSE" }], + }).success, + false + ); + assert.equal( + healthBatchInput.safeParse({ + ...base, + records: [{ ...base.records[0], sourcePackage: "com.untrusted.steps" }], + }).success, + false + ); +}); +test("rejects future times, duplicate provider IDs, oversized batches and invalid amounts", () => { + assert.equal( + healthBatchInput.safeParse({ + ...base, + records: [base.records[0], base.records[0]], + }).success, + false + ); + assert.equal( + healthBatchInput.safeParse({ + ...base, + records: Array.from({ length: 81 }, (_, i) => ({ + ...base.records[0], + externalId: "2026-11-" + String((i % 30) + 1).padStart(2, "0"), + })), + }).success, + false + ); + assert.equal( + healthBatchInput.safeParse({ + ...base, + records: [ + { ...base.records[0], startedAt: "2027-01-01T00:00:00Z", endedAt: "2027-01-01T01:00:00Z" }, + ], + }).success, + false + ); + assert.equal( + healthBatchInput.safeParse({ + ...base, + records: [{ ...base.records[0], value: -1 }], + }).success, + false + ); +}); +test("a device may submit source tombstones but not silently add clinical data", () => { + const value = healthBatchInput.safeParse({ + ...base, + records: [], + grantedTypes: [], + deletions: [ + { recordType: "WORKOUT", externalId: "hc-unique-1", sourcePackage: "com.fitness.watch" }, + ], + }); + assert.equal(value.success, true); +});