Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
30 changes: 30 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions android-health-connect/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/.gradle/
/build/
/app/build/
/local.properties
*.iml
.idea/
*.jks
*.keystore
**/captures/
23 changes: 23 additions & 0 deletions android-health-connect/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# ClubKeep Personal — Android Health Connect companion

This is a dedicated, native **read-only** Android companion for authorized
fitness sync. The main HM2 Personal experience stays in Next.js. No clinical
records, advertising/analytics SDKs, background-reading or write-back
permissions are requested. minSdk 28, targetSdk 36.

Requires Android Studio with JDK 17, Android SDK 36 and Gradle 8.13. Use
`gradle :app:assembleDebug -PclubkeepBaseUrl=https://YOUR_REVIEWED_CLUBKEEP_ORIGIN`.
A local `gradle` install or CI-provisioned Gradle is required; no unsigned
Gradle wrapper JAR is committed. The placeholder `invalid.clubkeep.example`
intentionally refuses pairing. Before publishing, verify the real
applicationId, Play app ownership, signing keys, Privacy Policy and Health
Connect declarations.

**No APK is released by merging this source PR.** Device tests and platform
approval must precede enabling the server-side connector gate.

Native source is developed alongside `docs/P1C_HEALTH_CONNECT.md`; Play
declarations, physical-device permission testing and signing are release gates.
The server stores only SHA-256 hashes of the one-time pairing and device
capabilities. Do not submit any Android Health Connect permissions declaration
until the privacy and Play policy review is completed.
45 changes: 45 additions & 0 deletions android-health-connect/app/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -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")
}
2 changes: 2 additions & 0 deletions android-health-connect/app/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -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.
42 changes: 42 additions & 0 deletions android-health-connect/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.health.READ_STEPS" />
<uses-permission android:name="android.permission.health.READ_EXERCISE" />
<uses-permission android:name="android.permission.health.READ_SLEEP" />
<uses-permission android:name="android.permission.health.READ_ACTIVE_CALORIES_BURNED" />
<uses-permission android:name="android.permission.health.READ_HYDRATION" />

<queries>
<package android:name="com.google.android.apps.healthdata" />
</queries>
<application
android:label="@string/app_name"
android:theme="@style/Theme.ClubKeep"
android:allowBackup="false"
android:fullBackupContent="false"
android:usesCleartextTraffic="false"
android:supportsRtl="true">
<activity android:name=".PrivacyRationaleActivity" android:exported="true">
<intent-filter>
<action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
</intent-filter>
</activity>
<activity-alias
android:name=".HealthPermissionUsage"
android:exported="true"
android:targetActivity=".PrivacyRationaleActivity"
android:permission="android.permission.START_VIEW_PERMISSION_USAGE">
<intent-filter>
<action android:name="android.intent.action.VIEW_PERMISSION_USAGE"/>
<category android:name="android.intent.category.HEALTH_PERMISSIONS"/>
</intent-filter>
</activity-alias>
<activity android:name=".MainActivity" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
Original file line number Diff line number Diff line change
@@ -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() }
}
}
Original file line number Diff line number Diff line change
@@ -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() }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package com.bababuilds.clubkeep.health

import androidx.health.connect.client.HealthConnectClient
import androidx.health.connect.client.request.AggregateRequest
import androidx.health.connect.client.records.ActiveCaloriesBurnedRecord
import androidx.health.connect.client.records.ExerciseSessionRecord
import androidx.health.connect.client.records.HydrationRecord
import androidx.health.connect.client.records.SleepSessionRecord
import androidx.health.connect.client.records.StepsRecord
import androidx.health.connect.client.request.ReadRecordsRequest
import androidx.health.connect.client.time.TimeRangeFilter
import org.json.JSONObject
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId
import kotlin.math.roundToInt

/** Streams bounded pages rather than buffering an entire wearable history. */
class HealthConnectSnapshotReader(private val client: HealthConnectClient) {
private fun record(kind: String, id: String, source: String, start: Instant,
end: Instant, value: Int? = null, exerciseType: Int? = null): JSONObject =
JSONObject().put("recordType", kind).put("externalId", id)
.put("sourcePackage", source).put("startedAt", start.toString())
.put("endedAt", end.toString())
.apply {
if (value != null) put("value", value)
if (exerciseType != null) put("exerciseType", exerciseType)
}

/** Changes API carries typed upserts; deletions have only an id. */
fun changed(source: androidx.health.connect.client.records.Record): JSONObject? =
when (source) {
is ExerciseSessionRecord -> record("WORKOUT", source.metadata.id,
source.metadata.dataOrigin.packageName, source.startTime, source.endTime,
exerciseType = source.exerciseType)
is SleepSessionRecord -> record("SLEEP", source.metadata.id,
source.metadata.dataOrigin.packageName, source.startTime, source.endTime)
is HydrationRecord -> {
val ml = source.volume.inMilliliters.roundToInt()
if (ml in 1..5000) record("HYDRATION", source.metadata.id,
source.metadata.dataOrigin.packageName, source.startTime, source.endTime, ml) else null
}
is ActiveCaloriesBurnedRecord -> {
val kcal = source.energy.inKilocalories.roundToInt()
if (kcal in 0..5000000) record("ACTIVE_CALORIES", source.metadata.id,
source.metadata.dataOrigin.packageName, source.startTime, source.endTime, kcal) else null
}
else -> null // No clinical record type is supported.
}

suspend fun snapshot(grants: Set<String>, from: Instant, until: Instant,
emit: suspend (List<JSONObject>) -> 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)
}
}
}
Loading
Loading