From 35372f247f90faad8a3501433cc4314f0edfc3c9 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Thu, 19 Nov 2026 13:26:49 +0530 Subject: [PATCH 1/8] feat(personal): add isolated Health Connect pairing, source, batch and permission schema --- .env.example | 5 ++ .../migration.sql | 72 +++++++++++++++++ prisma/schema.prisma | 79 +++++++++++++++++++ src/lib/personal/health-connect/flags.ts | 11 +++ 4 files changed, 167 insertions(+) create mode 100644 prisma/migrations/20261119120000_personal_p1c_health_connect/migration.sql create mode 100644 src/lib/personal/health-connect/flags.ts 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/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..f2bb37db --- /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_user_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_user_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_connection_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_user_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/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."); + } +} From ee700db7bc9a040c27126df74a6166bcfe979447 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Thu, 19 Nov 2026 13:26:56 +0530 Subject: [PATCH 2/8] feat(android): scaffold read-only Health Connect companion with Play-facing privacy UI --- android-health-connect/.gitignore | 9 ++++ android-health-connect/README.md | 17 +++++++ android-health-connect/app/build.gradle.kts | 45 +++++++++++++++++++ android-health-connect/app/proguard-rules.pro | 2 + .../app/src/main/AndroidManifest.xml | 42 +++++++++++++++++ .../clubkeep/health/MainActivity.kt | 28 ++++++++++++ .../health/PrivacyRationaleActivity.kt | 18 ++++++++ .../app/src/main/res/layout/activity_main.xml | 42 +++++++++++++++++ .../app/src/main/res/values/colors.xml | 6 +++ .../app/src/main/res/values/strings.xml | 11 +++++ .../app/src/main/res/values/styles.xml | 9 ++++ android-health-connect/build.gradle.kts | 4 ++ android-health-connect/gradle.properties | 4 ++ android-health-connect/settings.gradle.kts | 7 +++ 14 files changed, 244 insertions(+) create mode 100644 android-health-connect/.gitignore create mode 100644 android-health-connect/README.md create mode 100644 android-health-connect/app/build.gradle.kts create mode 100644 android-health-connect/app/proguard-rules.pro create mode 100644 android-health-connect/app/src/main/AndroidManifest.xml create mode 100644 android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/MainActivity.kt create mode 100644 android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/PrivacyRationaleActivity.kt create mode 100644 android-health-connect/app/src/main/res/layout/activity_main.xml create mode 100644 android-health-connect/app/src/main/res/values/colors.xml create mode 100644 android-health-connect/app/src/main/res/values/strings.xml create mode 100644 android-health-connect/app/src/main/res/values/styles.xml create mode 100644 android-health-connect/build.gradle.kts create mode 100644 android-health-connect/gradle.properties create mode 100644 android-health-connect/settings.gradle.kts 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..1f4572cc --- /dev/null +++ b/android-health-connect/README.md @@ -0,0 +1,17 @@ +# 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. 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/MainActivity.kt b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/MainActivity.kt new file mode 100644 index 00000000..b7e5e600 --- /dev/null +++ b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/MainActivity.kt @@ -0,0 +1,28 @@ +package com.bababuilds.clubkeep.health + +import android.os.Bundle +import androidx.activity.ComponentActivity +import com.bababuilds.clubkeep.health.databinding.ActivityMainBinding + +/** Native companion, not a replacement for ClubKeep Personal's web interface. */ +class MainActivity : ComponentActivity() { + private lateinit var views: ActivityMainBinding + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + views = ActivityMainBinding.inflate(layoutInflater) + setContentView(views.root) + val configured = !BuildConfig.SERVER_BASE_URL.contains("invalid.clubkeep.example") + views.status.text = if (configured) { + "Connect an adult ClubKeep Personal account to choose your permissions." + } else { + "This build has no trusted ClubKeep origin. Configure the server before pairing." + } + listOf(views.connect, views.permissions, views.sync, views.disconnect).forEach { + it.isEnabled = false // Enabled by explicit pairing and permission workflow in P1-C. + } + views.privacy.setOnClickListener { + startActivity(android.content.Intent(this, PrivacyRationaleActivity::class.java)) + } + } +} 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..064d2184 --- /dev/null +++ b/android-health-connect/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + 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/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..4a17d0a0 --- /dev/null +++ b/android-health-connect/settings.gradle.kts @@ -0,0 +1,7 @@ +pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } } +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { google(); mavenCentral() } +} +rootProject.name = "ClubKeepHealthConnect" +include(":app") From 496f535b8444f654e5a286d2b6b29c6734d4b4de Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Thu, 19 Nov 2026 13:27:03 +0530 Subject: [PATCH 3/8] feat(personal): secure one-time native pairing, Keystore storage and revocable credentials --- .../bababuilds/clubkeep/health/ClubKeepApi.kt | 34 ++++++ .../clubkeep/health/CredentialVault.kt | 47 ++++++++ .../connections/health-connect/pair/route.ts | 8 ++ .../connections/health-connect/purge/route.ts | 9 ++ .../health-connect/revoke/route.ts | 9 ++ .../me/connections/health-connect/route.ts | 6 + .../api/native/health-connect/claim/route.ts | 23 ++++ .../native/health-connect/disconnect/route.ts | 14 +++ .../api/native/health-connect/status/route.ts | 13 ++ .../personal/health-connect/connections.ts | 112 ++++++++++++++++++ .../personal/health-connect/native-http.ts | 50 ++++++++ src/lib/validations/health-connect.ts | 8 ++ 12 files changed, 333 insertions(+) create mode 100644 android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/ClubKeepApi.kt create mode 100644 android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/CredentialVault.kt create mode 100644 src/app/api/me/connections/health-connect/pair/route.ts create mode 100644 src/app/api/me/connections/health-connect/purge/route.ts create mode 100644 src/app/api/me/connections/health-connect/revoke/route.ts create mode 100644 src/app/api/me/connections/health-connect/route.ts create mode 100644 src/app/api/native/health-connect/claim/route.ts create mode 100644 src/app/api/native/health-connect/disconnect/route.ts create mode 100644 src/app/api/native/health-connect/status/route.ts create mode 100644 src/lib/personal/health-connect/connections.ts create mode 100644 src/lib/personal/health-connect/native-http.ts create mode 100644 src/lib/validations/health-connect.ts 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/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..17ca7de7 --- /dev/null +++ b/src/app/api/me/connections/health-connect/pair/route.ts @@ -0,0 +1,8 @@ +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..5f77ec22 --- /dev/null +++ b/src/app/api/me/connections/health-connect/purge/route.ts @@ -0,0 +1,9 @@ +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/revoke/route.ts b/src/app/api/me/connections/health-connect/revoke/route.ts new file mode 100644 index 00000000..e8fb884a --- /dev/null +++ b/src/app/api/me/connections/health-connect/revoke/route.ts @@ -0,0 +1,9 @@ +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/claim/route.ts b/src/app/api/native/health-connect/claim/route.ts new file mode 100644 index 00000000..74a26e99 --- /dev/null +++ b/src/app/api/native/health-connect/claim/route.ts @@ -0,0 +1,23 @@ +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..ecaedbde --- /dev/null +++ b/src/app/api/native/health-connect/disconnect/route.ts @@ -0,0 +1,14 @@ +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..c945f2cc --- /dev/null +++ b/src/app/api/native/health-connect/status/route.ts @@ -0,0 +1,13 @@ +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/lib/personal/health-connect/connections.ts b/src/lib/personal/health-connect/connections.ts new file mode 100644 index 00000000..740d5365 --- /dev/null +++ b/src/lib/personal/health-connect/connections.ts @@ -0,0 +1,112 @@ +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/native-http.ts b/src/lib/personal/health-connect/native-http.ts new file mode 100644 index 00000000..44b86bfa --- /dev/null +++ b/src/lib/personal/health-connect/native-http.ts @@ -0,0 +1,50 @@ +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/validations/health-connect.ts b/src/lib/validations/health-connect.ts new file mode 100644 index 00000000..e45f21de --- /dev/null +++ b/src/lib/validations/health-connect.ts @@ -0,0 +1,8 @@ +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(); From 1f3c02febfb5f5237e63846130ef2eb5c9b0fa91 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Thu, 19 Nov 2026 13:27:19 +0530 Subject: [PATCH 4/8] feat(android): granular read-only Health Connect permissions and explicit native linking flow --- .../clubkeep/health/HealthPermissions.kt | 38 +++++++ .../clubkeep/health/MainActivity.kt | 102 ++++++++++++++++-- .../app/src/main/res/layout/activity_main.xml | 4 + 3 files changed, 134 insertions(+), 10 deletions(-) create mode 100644 android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/HealthPermissions.kt 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 index b7e5e600..8a4539de 100644 --- 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 @@ -1,28 +1,110 @@ 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, not a replacement for ClubKeep Personal's web interface. */ +/** + * 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) - val configured = !BuildConfig.SERVER_BASE_URL.contains("invalid.clubkeep.example") - views.status.text = if (configured) { - "Connect an adult ClubKeep Personal account to choose your permissions." - } else { - "This build has no trusted ClubKeep origin. Configure the server before pairing." + vault = CredentialVault(applicationContext) + views.connect.setOnClickListener { connect() } + views.permissions.setOnClickListener { requestPermissions() } + views.sync.setOnClickListener { showStatus("Sync is not yet configured for this build.") } + 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 = false // Activated with the real incremental sync engine. + 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 } - listOf(views.connect, views.permissions, views.sync, views.disconnect).forEach { - it.isEnabled = false // Enabled by explicit pairing and permission workflow in P1-C. + 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") + 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() } } - views.privacy.setOnClickListener { - startActivity(android.content.Intent(this, PrivacyRationaleActivity::class.java)) + } + + 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() } } } } 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 index 064d2184..a42df286 100644 --- a/android-health-connect/app/src/main/res/layout/activity_main.xml +++ b/android-health-connect/app/src/main/res/layout/activity_main.xml @@ -28,6 +28,10 @@ + From b6634dba114ca53118a8ea31ff7c3055932dc97f Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Thu, 19 Nov 2026 13:27:26 +0530 Subject: [PATCH 5/8] feat(personal): import read-only fitness with source provenance, bounds and atomic batch deduplication --- .../health/HealthConnectSnapshotReader.kt | 107 ++++++++++++++++++ .../native/health-connect/batches/route.ts | 17 +++ src/lib/personal/health-connect/ingestion.ts | 107 ++++++++++++++++++ src/lib/personal/health-connect/read-body.ts | 29 +++++ src/lib/validations/health-connect-batch.ts | 58 ++++++++++ 5 files changed, 318 insertions(+) create mode 100644 android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/HealthConnectSnapshotReader.kt create mode 100644 src/app/api/native/health-connect/batches/route.ts create mode 100644 src/lib/personal/health-connect/ingestion.ts create mode 100644 src/lib/personal/health-connect/read-body.ts create mode 100644 src/lib/validations/health-connect-batch.ts 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..8c2d07c8 --- /dev/null +++ b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/HealthConnectSnapshotReader.kt @@ -0,0 +1,107 @@ +package com.bababuilds.clubkeep.health + +import androidx.health.connect.client.HealthConnectClient +import androidx.health.connect.client.aggregate.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) + } + + 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/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..e482575e --- /dev/null +++ b/src/app/api/native/health-connect/batches/route.ts @@ -0,0 +1,17 @@ +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/lib/personal/health-connect/ingestion.ts b/src/lib/personal/health-connect/ingestion.ts new file mode 100644 index 00000000..b5710db0 --- /dev/null +++ b/src/lib/personal/health-connect/ingestion.ts @@ -0,0 +1,107 @@ +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"; + +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/read-body.ts b/src/lib/personal/health-connect/read-body.ts new file mode 100644 index 00000000..868c3526 --- /dev/null +++ b/src/lib/personal/health-connect/read-body.ts @@ -0,0 +1,29 @@ +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/validations/health-connect-batch.ts b/src/lib/validations/health-connect-batch.ts new file mode 100644 index 00000000..436bc5da --- /dev/null +++ b/src/lib/validations/health-connect-batch.ts @@ -0,0 +1,58 @@ +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; From e4f28736fa7bd0176589dbd78084a9c76a0bddda Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Thu, 19 Nov 2026 13:27:33 +0530 Subject: [PATCH 6/8] feat(android): cursor-based foreground sync, encrypted checkpoints, deletion replay and recovery --- .../health/HealthConnectSnapshotReader.kt | 21 +++ .../health/HealthConnectSyncEngine.kt | 177 ++++++++++++++++++ .../clubkeep/health/MainActivity.kt | 24 ++- 3 files changed, 220 insertions(+), 2 deletions(-) create mode 100644 android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/HealthConnectSyncEngine.kt 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 index 8c2d07c8..9307a2e4 100644 --- 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 @@ -27,6 +27,27 @@ class HealthConnectSnapshotReader(private val client: HealthConnectClient) { 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) 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..4ee8405a --- /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 = 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/MainActivity.kt b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/MainActivity.kt index 8a4539de..28442e45 100644 --- 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 @@ -34,7 +34,7 @@ class MainActivity : ComponentActivity() { vault = CredentialVault(applicationContext) views.connect.setOnClickListener { connect() } views.permissions.setOnClickListener { requestPermissions() } - views.sync.setOnClickListener { showStatus("Sync is not yet configured for this build.") } + views.sync.setOnClickListener { syncNow() } views.disconnect.setOnClickListener { disconnect() } views.privacy.setOnClickListener { startActivity(Intent(this, PrivacyRationaleActivity::class.java)) @@ -54,7 +54,7 @@ class MainActivity : ComponentActivity() { val linked = configured() && vault.get("token") != null views.connect.isEnabled = !working && configured() views.permissions.isEnabled = !working && linked && HealthPermissions.available(this) - views.sync.isEnabled = false // Activated with the real incremental sync engine. + views.sync.isEnabled = !working && linked && HealthPermissions.available(this) views.disconnect.isEnabled = !working && linked } private fun showStatus(value: String) { views.status.text = value } @@ -78,6 +78,7 @@ class MainActivity : ComponentActivity() { 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) { @@ -107,4 +108,23 @@ class MainActivity : ComponentActivity() { } 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() } + } + } + } From 4c8a6dd903957761ae940f94ca41058f928ca3c6 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Thu, 19 Nov 2026 13:27:48 +0530 Subject: [PATCH 7/8] feat(personal): connected-device controls, imported provenance, separate insights and full data erasure --- .../health-connect/records/route.ts | 11 ++ src/app/me/connections/loading.tsx | 1 + src/app/me/connections/page.tsx | 45 +++++++ src/app/me/page.tsx | 3 + src/app/me/profile/page.tsx | 8 ++ .../personal/health-connect-controls.tsx | 110 ++++++++++++++++++ src/components/personal/personal.css | 12 ++ src/components/personal/wellness-insights.tsx | 14 +++ src/lib/personal/personal-service.ts | 14 +++ src/lib/personal/wellness-insights.ts | 38 +++++- 10 files changed, 254 insertions(+), 2 deletions(-) create mode 100644 src/app/api/me/connections/health-connect/records/route.ts create mode 100644 src/app/me/connections/loading.tsx create mode 100644 src/app/me/connections/page.tsx create mode 100644 src/components/personal/health-connect-controls.tsx 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/me/connections/loading.tsx b/src/app/me/connections/loading.tsx new file mode 100644 index 00000000..12f5572d --- /dev/null +++ b/src/app/me/connections/loading.tsx @@ -0,0 +1 @@ +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..583626a9 --- /dev/null +++ b/src/app/me/connections/page.tsx @@ -0,0 +1,45 @@ +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..40548cd6 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..b5dea501 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,13 @@ 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..93e588ed --- /dev/null +++ b/src/components/personal/health-connect-controls.tsx @@ -0,0 +1,110 @@ +"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..cc7cc75c 100644 --- a/src/components/personal/wellness-insights.tsx +++ b/src/components/personal/wellness-insights.tsx @@ -31,6 +31,20 @@ 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/personal-service.ts b/src/lib/personal/personal-service.ts index d197aec4..e6b4bd16 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,13 @@ 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 +284,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 +302,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..8c4d3aa6 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,11 @@ 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 +169,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.", }; } From fef3b672bc95d9faecaf578813092bd54c51ae67 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Thu, 19 Nov 2026 13:27:54 +0530 Subject: [PATCH 8/8] test(personal): native Health Connect, PostgreSQL, privacy, CI and rollout acceptance --- .github/workflows/ci.yml | 30 +++ android-health-connect/README.md | 6 + .../health/HealthConnectSnapshotReader.kt | 2 +- .../health/HealthConnectSyncEngine.kt | 2 +- .../clubkeep/health/SyncContractTest.kt | 13 ++ android-health-connect/settings.gradle.kts | 2 +- docs/P1C_HEALTH_CONNECT.md | 98 ++++++++++ .../migration.sql | 8 +- .../connections/health-connect/pair/route.ts | 5 +- .../connections/health-connect/purge/route.ts | 6 +- .../health-connect/revoke/route.ts | 6 +- .../native/health-connect/batches/route.ts | 4 +- .../api/native/health-connect/claim/route.ts | 11 +- .../native/health-connect/disconnect/route.ts | 4 +- .../api/native/health-connect/status/route.ts | 7 +- src/app/me/connections/loading.tsx | 8 +- src/app/me/connections/page.tsx | 55 ++++-- src/app/me/page.tsx | 6 +- src/app/me/profile/page.tsx | 8 +- .../personal/health-connect-controls.tsx | 178 +++++++++++++----- src/components/personal/wellness-insights.tsx | 24 ++- .../personal/health-connect/connections.ts | 50 +++-- src/lib/personal/health-connect/ingestion.ts | 85 ++++++--- .../personal/health-connect/native-http.ts | 14 +- src/lib/personal/health-connect/read-body.ts | 7 +- src/lib/personal/personal-service.ts | 12 +- src/lib/personal/wellness-insights.ts | 13 +- src/lib/validations/health-connect-batch.ts | 145 +++++++++----- src/lib/validations/health-connect.ts | 12 +- tests/integration/p1c-health-connect.test.mjs | 141 ++++++++++++++ tests/unit/health-connect-validation.test.mjs | 98 ++++++++++ 31 files changed, 864 insertions(+), 196 deletions(-) create mode 100644 android-health-connect/app/src/test/java/com/bababuilds/clubkeep/health/SyncContractTest.kt create mode 100644 docs/P1C_HEALTH_CONNECT.md create mode 100644 tests/integration/p1c-health-connect.test.mjs create mode 100644 tests/unit/health-connect-validation.test.mjs 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/README.md b/android-health-connect/README.md index 1f4572cc..f1fdd211 100644 --- a/android-health-connect/README.md +++ b/android-health-connect/README.md @@ -15,3 +15,9 @@ 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/src/main/java/com/bababuilds/clubkeep/health/HealthConnectSnapshotReader.kt b/android-health-connect/app/src/main/java/com/bababuilds/clubkeep/health/HealthConnectSnapshotReader.kt index 9307a2e4..01d72b85 100644 --- 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 @@ -1,7 +1,7 @@ package com.bababuilds.clubkeep.health import androidx.health.connect.client.HealthConnectClient -import androidx.health.connect.client.aggregate.AggregateRequest +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 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 index 4ee8405a..e79b1d0e 100644 --- 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 @@ -122,7 +122,7 @@ class HealthConnectSyncEngine( return SyncReport(count, 0, "initial snapshot") } - var cursor = previous + var cursor: String = requireNotNull(previous) var count = 0 var removed = 0 do { 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/settings.gradle.kts b/android-health-connect/settings.gradle.kts index 4a17d0a0..31772194 100644 --- a/android-health-connect/settings.gradle.kts +++ b/android-health-connect/settings.gradle.kts @@ -1,4 +1,4 @@ -pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } } +pluginManagement { repositories { google(); maven { url = uri("https://repo1.maven.org/maven2/") }; mavenCentral(); gradlePluginPortal() } } dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google(); mavenCentral() } 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 index f2bb37db..f094dc2a 100644 --- a/prisma/migrations/20261119120000_personal_p1c_health_connect/migration.sql +++ b/prisma/migrations/20261119120000_personal_p1c_health_connect/migration.sql @@ -8,7 +8,7 @@ CREATE TABLE "HealthConnectPairing" ( "expiresAt" TIMESTAMP(3) NOT NULL, "claimedAt" TIMESTAMP(3), "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - CONSTRAINT "HealthConnectPairing_user_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE + 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"); @@ -26,7 +26,7 @@ CREATE TABLE "HealthConnectConnection" ( "revokedAt" TIMESTAMP(3), "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TIMESTAMP(3) NOT NULL, - CONSTRAINT "HealthConnectConnection_user_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE + 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"); @@ -40,7 +40,7 @@ CREATE TABLE "HealthConnectSyncBatch" ( "importedCount" INTEGER NOT NULL, "deletedCount" INTEGER NOT NULL, "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - CONSTRAINT "HealthConnectSyncBatch_connection_fkey" FOREIGN KEY ("connectionId") REFERENCES "HealthConnectConnection"("id") ON DELETE CASCADE ON UPDATE CASCADE, + 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"); @@ -61,7 +61,7 @@ CREATE TABLE "HealthConnectRecord" ( "lastSeenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TIMESTAMP(3) NOT NULL, - CONSTRAINT "HealthConnectRecord_user_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE, + 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 ( diff --git a/src/app/api/me/connections/health-connect/pair/route.ts b/src/app/api/me/connections/health-connect/pair/route.ts index 17ca7de7..1c5ffd4e 100644 --- a/src/app/api/me/connections/health-connect/pair/route.ts +++ b/src/app/api/me/connections/health-connect/pair/route.ts @@ -3,6 +3,7 @@ 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)); + 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 index 5f77ec22..16be7167 100644 --- a/src/app/api/me/connections/health-connect/purge/route.ts +++ b/src/app/api/me/connections/health-connect/purge/route.ts @@ -4,6 +4,8 @@ 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); }); + return wellnessPost(request, "health-purge", 5, healthPurgeInput, (db, userId) => { + assertHealthConnectEnabled(); + return purgeHealthImports(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 index e8fb884a..db755800 100644 --- a/src/app/api/me/connections/health-connect/revoke/route.ts +++ b/src/app/api/me/connections/health-connect/revoke/route.ts @@ -4,6 +4,8 @@ import { revokeHealthConnection } from "@/lib/personal/health-connect/connection 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); }); + return wellnessPost(request, "health-revoke", 12, healthConnectionIdInput, (db, userId, data) => { + assertHealthConnectEnabled(); + return revokeHealthConnection(db, userId, data.id); + }); } diff --git a/src/app/api/native/health-connect/batches/route.ts b/src/app/api/native/health-connect/batches/route.ts index e482575e..64cc4d8e 100644 --- a/src/app/api/native/health-connect/batches/route.ts +++ b/src/app/api/native/health-connect/batches/route.ts @@ -13,5 +13,7 @@ export async function POST(request: NextRequest): Promise { 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); } + } 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 index 74a26e99..05bd0b1e 100644 --- a/src/app/api/native/health-connect/claim/route.ts +++ b/src/app/api/native/health-connect/claim/route.ts @@ -15,9 +15,16 @@ export async function POST(request: NextRequest) { 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); + 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); } + } 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 index ecaedbde..a4a9c901 100644 --- a/src/app/api/native/health-connect/disconnect/route.ts +++ b/src/app/api/native/health-connect/disconnect/route.ts @@ -10,5 +10,7 @@ export async function POST(request: NextRequest) { data: { revokedAt: new Date(), grantedTypes: [] }, }); return jsonPrivate({ ok: true, revoked: true }); - } catch (error) { return onboardingFailure(error); } + } 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 index c945f2cc..8affd300 100644 --- a/src/app/api/native/health-connect/status/route.ts +++ b/src/app/api/native/health-connect/status/route.ts @@ -6,8 +6,11 @@ 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() }, + 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); } + } catch (error) { + return onboardingFailure(error); + } } diff --git a/src/app/me/connections/loading.tsx b/src/app/me/connections/loading.tsx index 12f5572d..10410c34 100644 --- a/src/app/me/connections/loading.tsx +++ b/src/app/me/connections/loading.tsx @@ -1 +1,7 @@ -export default function Loading() { return

Loading connected sources…

; } +export default function Loading() { + return ( +

+ Loading connected sources… +

+ ); +} diff --git a/src/app/me/connections/page.tsx b/src/app/me/connections/page.tsx index 583626a9..10e263c0 100644 --- a/src/app/me/connections/page.tsx +++ b/src/app/me/connections/page.tsx @@ -17,28 +17,53 @@ export default async function HealthConnectPage() {

Connected sources

Android Health Connect

-

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

+

+ 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(), - }))} /> + ({ + 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.

: +

+ 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 => ( + {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} + + {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 40548cd6..2f278700 100644 --- a/src/app/me/page.tsx +++ b/src/app/me/page.tsx @@ -40,9 +40,9 @@ export default async function TodayPage() { Nutrition Recovery Insights - {process.env.PERSONAL_HEALTH_CONNECT_ENABLED === "true" && ( - Connected sources - )} + {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 b5dea501..db64e84d 100644 --- a/src/app/me/profile/page.tsx +++ b/src/app/me/profile/page.tsx @@ -17,8 +17,12 @@ export default async function ProfilePage() { {process.env.PERSONAL_HEALTH_CONNECT_ENABLED === "true" && (

Connected sources

-

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

- Manage Health Connect +

+ 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 index 93e588ed..808700c2 100644 --- a/src/components/personal/health-connect-controls.tsx +++ b/src/components/personal/health-connect-controls.tsx @@ -5,8 +5,12 @@ 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; + id: string; + label: string; + grantedTypes: string[]; + lastSyncAt: string | null; + revokedAt: string | null; + tokenExpiresAt: string; }; export function HealthConnectControls({ connections }: { connections: Connection[] }) { @@ -16,18 +20,28 @@ export function HealthConnectControls({ connections }: { connections: Connection 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()); + const active = connections.filter((c) => !c.revokedAt && new Date(c.tokenExpiresAt) > new Date()); function pair() { start(async () => { - setCode(""); setExpiration(""); setMessage(""); + 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: "{}", + 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 }; + 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; + setMessage(result.error ?? "Unable to create pairing code."); + return; } setCode(result.pairCode); setExpiration(result.expiresAt ?? ""); @@ -40,7 +54,9 @@ export function HealthConnectControls({ connections }: { connections: Connection 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); + setMessage( + result.ok ? "Device revoked. Existing imports remain until you delete them." : result.error + ); if (result.ok) router.refresh(); }); } @@ -49,7 +65,8 @@ export function HealthConnectControls({ connections }: { connections: Connection 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(""); + setCode(""); + setExpiration(""); if (result.ok) router.refresh(); }); } @@ -58,53 +75,126 @@ export function HealthConnectControls({ connections }: { connections: Connection

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. + 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()}} + {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 && } -
)} +

+ 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}

} + {message && ( +

+ {message} +

+ )} ); } diff --git a/src/components/personal/wellness-insights.tsx b/src/components/personal/wellness-insights.tsx index cc7cc75c..a2582093 100644 --- a/src/components/personal/wellness-insights.tsx +++ b/src/components/personal/wellness-insights.tsx @@ -35,14 +35,28 @@ export async function WellnessInsightsSection({ userId }: { userId: string }) {

Health Connect

- Manage sources + + Manage sources +
-

{insights.importedThisWeek.steps} steps reported this week

-

{insights.importedThisWeek.workoutRecords} imported exercise records

-

{insights.importedThisWeek.waterMl} mL imported hydration

+

+ {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.

+

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

)}

Active goals

diff --git a/src/lib/personal/health-connect/connections.ts b/src/lib/personal/health-connect/connections.ts index 740d5365..72732ff5 100644 --- a/src/lib/personal/health-connect/connections.ts +++ b/src/lib/personal/health-connect/connections.ts @@ -10,17 +10,28 @@ 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"); } +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, + where: { userId }, + select: { + id: true, + label: true, + grantedTypes: true, + createdAt: true, + lastSyncAt: true, + lastSeenAt: true, + revokedAt: true, + tokenExpiresAt: true, + }, + orderBy: { createdAt: "desc" }, + take: 20, }); } @@ -42,7 +53,8 @@ export async function beginHealthPairing(db: PrismaClient, userId: string) { } export async function claimHealthPairing( - db: PrismaClient, input: { pairCode: string; installationId: string; label: string } + db: PrismaClient, + input: { pairCode: string; installationId: string; label: string } ) { assertHealthConnectEnabled(); const codeHash = hashCapability(input.pairCode); @@ -55,7 +67,8 @@ export async function claimHealthPairing( 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 }, + where: { userId: pair.userId }, + select: { birthYear: true }, }); if (!profile?.birthYear || now.getUTCFullYear() - profile.birthYear < 19) throw new OnboardingError(403, "Adult Personal access required."); @@ -65,7 +78,9 @@ export async function claimHealthPairing( }); 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 } }, + where: { + userId_installationId: { userId: pair.userId, installationId: input.installationId }, + }, }); if (!previous) { const active = await tx.healthConnectConnection.count({ @@ -74,14 +89,23 @@ export async function claimHealthPairing( 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 } }, + where: { + userId_installationId: { userId: pair.userId, installationId: input.installationId }, + }, create: { - userId: pair.userId, installationId: input.installationId, - label: input.label, tokenHash, tokenExpiresAt: expiresAt, + userId: pair.userId, + installationId: input.installationId, + label: input.label, + tokenHash, + tokenExpiresAt: expiresAt, }, update: { - label: input.label, tokenHash, tokenExpiresAt: expiresAt, - revokedAt: null, grantedTypes: [], lastSyncAt: null, + label: input.label, + tokenHash, + tokenExpiresAt: expiresAt, + revokedAt: null, + grantedTypes: [], + lastSyncAt: null, }, select: { id: true }, }); diff --git a/src/lib/personal/health-connect/ingestion.ts b/src/lib/personal/health-connect/ingestion.ts index b5710db0..a9d7829c 100644 --- a/src/lib/personal/health-connect/ingestion.ts +++ b/src/lib/personal/health-connect/ingestion.ts @@ -1,21 +1,25 @@ 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"; +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() + 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."); + if (known.contentHash !== digest) + throw new OnboardingError(409, "Batch ID used with different content."); return { imported: known.importedCount, deleted: known.deletedCount, replayed: true }; } @@ -24,9 +28,15 @@ export async function acceptHealthBatch( // 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 }, + where: { id: device.id }, + select: { userId: true, revokedAt: true, tokenExpiresAt: true }, }); - if (!current || current.userId !== device.userId || current.revokedAt || current.tokenExpiresAt <= now) + 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 } }, @@ -36,41 +46,64 @@ export async function acceptHealthBatch( 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 }; + 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, + ...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, + 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 }; + 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, + ...key, + startedAt: new Date(now.getTime() - 1000), + endedAt: now, value: record.recordType === "STEPS_DAILY" ? 0 : null, - deletedAt: now, lastDeviceId: device.id, lastSeenAt: now, + 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 }, + 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 }, @@ -85,7 +118,8 @@ export async function acceptHealthBatch( 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."); + if (result.contentHash !== digest) + throw new OnboardingError(409, "Batch ID used with different content."); return { imported: result.importedCount, deleted: result.deletedCount, replayed: true }; } } @@ -100,8 +134,13 @@ export async function listImportedFitness(db: PrismaClient, userId: string) { orderBy: { endedAt: "desc" }, take: 150, select: { - id: true, recordType: true, startedAt: true, endedAt: true, - value: true, exerciseType: true, sourcePackage: true, + 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 index 44b86bfa..e7a7e77b 100644 --- a/src/lib/personal/health-connect/native-http.ts +++ b/src/lib/personal/health-connect/native-http.ts @@ -16,7 +16,8 @@ export async function limitNativeRequest(request: NextRequest, scope: string, ma if (!authLimiter) throw new OnboardingError(503, "Security service unavailable."); const config = resolveAuthConfig(); const ip = config.trustedIpHeader - ? (request.headers.get(config.trustedIpHeader) ?? "unknown") : "unknown"; + ? (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."); @@ -39,12 +40,17 @@ export async function requireHealthDevice(request: NextRequest) { } export async function nativePost( request: NextRequest, - handler: (device: Awaited>, body: unknown) => Promise + 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); } + 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 index 868c3526..37ce5471 100644 --- a/src/lib/personal/health-connect/read-body.ts +++ b/src/lib/personal/health-connect/read-body.ts @@ -8,7 +8,8 @@ export async function readNativeBatch(request: NextRequest): Promise { 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; + let body = "", + bytes = 0; try { for (;;) { const part = await reader.read(); @@ -25,5 +26,7 @@ export async function readNativeBatch(request: NextRequest): Promise { } catch (error) { if (error instanceof OnboardingError) throw error; throw new OnboardingError(400, "Invalid JSON."); - } finally { reader.releaseLock(); } + } finally { + reader.releaseLock(); + } } diff --git a/src/lib/personal/personal-service.ts b/src/lib/personal/personal-service.ts index e6b4bd16..52c42337 100644 --- a/src/lib/personal/personal-service.ts +++ b/src/lib/personal/personal-service.ts @@ -258,9 +258,15 @@ export async function exportPersonalData(db: PrismaClient, userId: string, now = 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, + where: { userId }, + select: { + id: true, + label: true, + installationId: true, + grantedTypes: true, + lastSyncAt: true, + revokedAt: true, + createdAt: true, }, }), ]); diff --git a/src/lib/personal/wellness-insights.ts b/src/lib/personal/wellness-insights.ts index 8c4d3aa6..76b4e80a 100644 --- a/src/lib/personal/wellness-insights.ts +++ b/src/lib/personal/wellness-insights.ts @@ -119,11 +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 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. diff --git a/src/lib/validations/health-connect-batch.ts b/src/lib/validations/health-connect-batch.ts index 436bc5da..7ea624f1 100644 --- a/src/lib/validations/health-connect-batch.ts +++ b/src/lib/validations/health-connect-batch.ts @@ -1,58 +1,99 @@ import { z } from "zod"; export const healthRecordTypes = [ - "STEPS_DAILY", "WORKOUT", "SLEEP", "ACTIVE_CALORIES", "HYDRATION", + "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" }); - } -}); +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 index e45f21de..9e10dc5d 100644 --- a/src/lib/validations/health-connect.ts +++ b/src/lib/validations/health-connect.ts @@ -1,8 +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 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); +});