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