Files
HealthLog/src/hooks/use-grant-document-reading-consent.ts
T
Marc-André Bombeck e2b7e7350e fix(consent): mint AI consent receipts only on an explicit agreement
The AI settings page posted to /api/consent/ai/web on every mount and the
server minted an ai_full receipt for it, so an account that had agreed to
nothing sent its health data to the operator's provider from background
jobs. Native builds synced a receipt the same way on every launch.

- Both grant routes now require `confirm: true`; anything else writes
  nothing and answers 400 consent.ai.confirmRequired.
- Remove the mount-time heal. A consent card names the operator's service
  and the data that would go there, with one Agree button, in Settings > AI
  and on the Insights overview while AI is closed by the missing consent
  alone.
- Publish the standing consent as `ai.consent` on /api/auth/me (status,
  since, recipients); the settings card renders active-since and the
  withdraw control from it.
- Existing receipts stay valid.
- Guard that no client grants outside a click handler, route tests for the
  confirmation, and an integration test that a fresh operator-key account
  gets no background AI text until it agrees.
2026-10-16 17:11:04 +02:00

55 lines
1.9 KiB
TypeScript

"use client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiPost } from "@/lib/api/api-fetch";
import {
aiInputDependentKeys,
invalidateKeys,
queryKeys,
} from "@/lib/query-keys";
/**
* Grant the consent for reading documents (`ai_extraction`) from the place
* that needs it.
*
* Sending a document, a lab report scan or a typed medication description to
* an AI service outside this server needs its own receipt. The narrow kind
* covers exactly that and never the Coach or AI analysis, so asking for it
* where a document is being read asks for no more than the reader is about to
* do. The tap on the prompt IS the consent act; the receipt records it with
* its source, the same way the web settings record a full grant.
*
* On success `/api/auth/me` is refetched, because the capabilities it
* publishes (`documentAi`, `labsOcr`, `medicationExtract`) are what every
* reading surface renders from.
*/
export function useGrantDocumentReadingConsent() {
const queryClient = useQueryClient();
return useMutation({
mutationKey: queryKeys.aiExtractionConsentGrant(),
mutationFn: async () => {
const signedAt = new Date().toISOString();
return apiPost("/api/consent/ai", {
kind: "ai_extraction",
// The tap on the prompt is the consent act; the server records a
// receipt only for a request that says so.
confirm: true,
signedAt,
artefact: JSON.stringify({
source: "web",
kind: "ai_extraction",
grantedAt: signedAt,
note: "In-app affirmative consent to reading documents, granted via the web client.",
}),
});
},
onSuccess: () => {
void invalidateKeys(queryClient, aiInputDependentKeys);
void queryClient.invalidateQueries({
queryKey: queryKeys.aiConsentReceipt("ai_extraction"),
});
},
});
}