diff --git a/README.md b/README.md index 592cf002..7d93ee80 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,16 @@ automated suite uses simulated email, so the live delivery checks remain open. See the [protected staging smoke checklist](./docs/testing/REAL_NEXT_E2E_HARNESS.md#protected-staging-smoke). +### Deferred production checks + +- [ ] Restore a recent production database backup into an isolated environment. + Verify that the restored data is usable and that previously deleted data stays + out of live use. Record the result in the restricted operations register. + This check remains required before inviting beta users and before deploying + production database changes. See the + [beta readiness checklist](./docs/BETA_READINESS.md#required-before-inviting-beta-users) + and [database release procedure](./docs/DEPLOYMENT.md#database-changes). + ## Legal And Compliance Status The repository contains a practical compliance draft for the current product, diff --git a/app/api/v1/README.md b/app/api/v1/README.md index 3bdcb901..16c0da50 100644 --- a/app/api/v1/README.md +++ b/app/api/v1/README.md @@ -110,6 +110,9 @@ Marking Review Support ---------------------- - GET `/support/marking-reviews` (authorised support) — Query: `status=PENDING|RESOLVED|ALL`. Returns the restricted review queue with case evidence and audit events. - POST `/support/guardian-withdrawals` (authorised privacy operator) — Records a verified withdrawal, revokes the learner's existing sessions, and reports both notice outcomes. Use the same private case reference to retry an incomplete notice. +- Verified guardian follow-ups use the same operator workspace. The guardian + confirms through a one-time link. Cancellation of verified guardian deletion + preserves the account restriction pending fresh approval. - PATCH `/support/marking-reviews/:id` (authorised support) — Body: `decision` (`UPHOLD` or `ADJUST`), `note`, and integer `score` for an adjustment. Resolves a pending case once. An adjustment updates the answer, recalculates the paper total and updates the subject progress record when this is the learner's latest graded paper in that subject. The decision and learner notification are recorded atomically. Progress diff --git a/app/api/v1/guardian-authorizations/follow-up/route.ts b/app/api/v1/guardian-authorizations/follow-up/route.ts new file mode 100644 index 00000000..728b3f33 --- /dev/null +++ b/app/api/v1/guardian-authorizations/follow-up/route.ts @@ -0,0 +1,50 @@ +import { NextResponse } from "next/server"; +import { z } from "zod"; +import { hashGuardianAuthorizationToken } from "@/lib/guardian-authorization"; +import { GuardianWithdrawalConflict } from "@/lib/guardian-withdrawal"; +import { decideGuardianFollowUp, getGuardianFollowUpDetails } from "@/lib/guardian-withdrawal-follow-up"; +import { securityFingerprint } from "@/lib/security/audit-log"; +import { enforceRateLimitRules, getClientIp } from "@/lib/security/rate-limit"; +import { parseJsonObjectRequest, REQUEST_LIMITS } from "@/lib/security/request-body"; + +const token = z.string().regex(/^[A-Za-z0-9_-]{43}$/); +const body = z.discriminatedUnion("step", [ + z.object({ step: z.literal("review"), token }).strict(), + z.object({ + step: z.literal("confirm"), token, + action: z.enum(["REAUTHORISE", "DELETE"]), + confirmsAuthority: z.literal(true), + confirmsDecision: z.literal(true), + }).strict(), +]); + +const respond = (data: object, status = 200) => + NextResponse.json(data, { status, headers: { "Cache-Control": "no-store" } }); +const invalidLink = () => respond({ + error: "INVALID_LINK", message: "This decision link is invalid, expired, or already used.", +}, 404); + +export async function POST(request: Request) { + const parsed = await parseJsonObjectRequest(request, REQUEST_LIMITS.publicFormJson); + if (!parsed.ok) return parsed.response; + const input = body.safeParse(parsed.data); + if (!input.success) return respond({ + error: "INVALID_DECISION", message: "Review the request and confirm your authority and decision.", + }, 400); + const ip = getClientIp(request.headers); + const limited = await enforceRateLimitRules([ + { scope: "guardian:follow-up:ip", identifier: ip, limit: 30, windowMs: 60 * 60_000 }, + { scope: "guardian:follow-up:token", identifier: hashGuardianAuthorizationToken(input.data.token), limit: 10, windowMs: 60 * 60_000 }, + ]); + if (limited) return limited; + if (input.data.step === "review") { + const details = await getGuardianFollowUpDetails(input.data.token); + return details ? respond(details) : invalidLink(); + } + try { + return respond(await decideGuardianFollowUp({ ...input.data, ipFingerprint: securityFingerprint(ip) })); + } catch (error) { + if (error instanceof GuardianWithdrawalConflict) return invalidLink(); + throw error; + } +} diff --git a/app/api/v1/support/guardian-withdrawals/route.ts b/app/api/v1/support/guardian-withdrawals/route.ts index e54dd71f..f50f3079 100644 --- a/app/api/v1/support/guardian-withdrawals/route.ts +++ b/app/api/v1/support/guardian-withdrawals/route.ts @@ -1,12 +1,15 @@ import { NextResponse } from "next/server"; import { z } from "zod"; import { GuardianWithdrawalConflict, requireGuardianWithdrawalOperator, withdrawGuardianAuthorisation } from "@/lib/guardian-withdrawal"; +import { cancelGuardianDeletion, startGuardianFollowUp } from "@/lib/guardian-withdrawal-follow-up"; import { parseJsonObjectRequest, REQUEST_LIMITS } from "@/lib/security/request-body"; +import { enforceRateLimitRules } from "@/lib/security/rate-limit"; const verifiedWithdrawal = z.object({ authorizationId: z.string().uuid(), caseReference: z.string().trim().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/), verified: z.literal(true), + action: z.enum(["WITHDRAW", "REAUTHORISE", "DELETE", "CANCEL_DELETION"]).default("WITHDRAW"), }).strict(); export async function POST(request: Request) { @@ -22,11 +25,20 @@ export async function POST(request: Request) { ); } try { - const notices = await withdrawGuardianAuthorisation({ ...input.data, operatorUserId: auth.dbUser.id }); - return NextResponse.json( - { restricted: true, ...notices }, - { headers: { "Cache-Control": "no-store" } }, - ); + const { action, ...reference } = input.data; + const operatorCase = { ...reference, operatorUserId: auth.dbUser.id }; + const response = (data: object) => NextResponse.json(data, { headers: { "Cache-Control": "no-store" } }); + if (action === "WITHDRAW") { + return response({ restricted: true, ...await withdrawGuardianAuthorisation(operatorCase) }); + } + const limited = await enforceRateLimitRules([ + { scope: "guardian:follow-up:staff", identifier: auth.dbUser.id, limit: 15, windowMs: 60 * 60_000 }, + ]); + if (limited) return limited; + if (action === "CANCEL_DELETION") { + return response({ restricted: true, ...await cancelGuardianDeletion(operatorCase) }); + } + return response({ restricted: true, ...await startGuardianFollowUp({ ...operatorCase, action }) }); } catch (error) { if (!(error instanceof GuardianWithdrawalConflict)) throw error; return NextResponse.json({ error: "WITHDRAWAL_CONFLICT", message: error.message }, { status: 409 }); diff --git a/app/guardian-withdrawal-decision/GuardianWithdrawalDecision.tsx b/app/guardian-withdrawal-decision/GuardianWithdrawalDecision.tsx new file mode 100644 index 00000000..f4f90e93 --- /dev/null +++ b/app/guardian-withdrawal-decision/GuardianWithdrawalDecision.tsx @@ -0,0 +1,107 @@ +"use client"; + +import { useEffect, useRef, useState, type FormEvent } from "react"; +import Button from "@/components/Button"; +import FormErrorMessage from "@/components/FormErrorMessage"; +import { readResponseError } from "@/lib/client-response-error"; +import { PRIVACY_EMAIL } from "@/lib/legal-entity"; + +type Decision = "REAUTHORISE" | "DELETE"; +type Details = { action: Decision; learnerName: string | null }; +type Result = { scheduledFor?: string; studentNotified: boolean; guardianNotified: boolean }; +const endpoint = "/api/v1/guardian-authorizations/follow-up"; + +export default function GuardianWithdrawalDecision() { + const token = useRef(""); + const [details, setDetails] = useState
(undefined); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const [result, setResult] = useState(null); + + useEffect(() => { + token.current ||= new URLSearchParams(window.location.hash.slice(1)).get("token") ?? ""; + window.history.replaceState(null, "", "/guardian-withdrawal-decision"); + if (!token.current) { + setDetails(null); + return; + } + const controller = new AbortController(); + fetch(endpoint, { + method: "POST", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ step: "review", token: token.current }), signal: controller.signal, + }).then(async (response) => { + if (!response.ok) return setDetails(null); + setDetails(await response.json()); + }).catch(() => { + if (!controller.signal.aborted) setDetails(null); + }); + return () => controller.abort(); + }, []); + + async function confirm(event: FormEvent) { + event.preventDefault(); + if (!details || !token.current || busy) return; + const data = new FormData(event.currentTarget); + setError(""); + setBusy(true); + try { + const response = await fetch(endpoint, { + method: "POST", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + step: "confirm", token: token.current, action: details.action, + confirmsAuthority: data.has("authority"), confirmsDecision: data.has("decision"), + }), + }); + if (!response.ok) { + setError(await readResponseError(response, "We could not confirm your decision.")); + return; + } + setResult(await response.json()); + token.current = ""; + } catch { + setError("We could not confirm whether your decision was recorded. Contact Study Buddy Privacy for help."); + } finally { + setBusy(false); + } + } + + const deletion = details?.action === "DELETE"; + return ( +
+

Guardian decision

+ {details === undefined &&

Checking your secure link…

} + {details === null &&

This link is invalid, expired, or already used.

} + {result ? ( +
+

Your decision was recorded.

+

{result.scheduledFor + ? `The account stays restricted. Contact Study Buddy Privacy before ${new Date(result.scheduledFor).toUTCString()} if you change your mind.` + : "Guardian approval for ordinary study was recorded. The learner can sign in. AI remains paused for under-18s."}

+ {(!result.studentNotified || !result.guardianNotified) &&

One or more confirmation emails could not be sent.

} +
+ ) : details && ( +
+ {details.learnerName &&

This request is for {details.learnerName}.

} +

{deletion + ? "Confirm permanent deletion of the learner account and its saved work. Access stays restricted. You have 15 days to contact Privacy to cancel." + : "Approve ordinary study again and keep the learner’s saved work. AI access remains paused for under-18s."}

+ + + + + + )} +

For help, email {PRIVACY_EMAIL}.

+
+ ); +} diff --git a/app/guardian-withdrawal-decision/page.tsx b/app/guardian-withdrawal-decision/page.tsx new file mode 100644 index 00000000..d52c5902 --- /dev/null +++ b/app/guardian-withdrawal-decision/page.tsx @@ -0,0 +1,12 @@ +import { createPageMetadata } from "@/lib/site-metadata"; +import GuardianWithdrawalDecision from "./GuardianWithdrawalDecision"; + +export const metadata = createPageMetadata({ + title: "Guardian Decision", + description: "Review a verified Study Buddy privacy request.", + index: false, +}); + +export default function GuardianWithdrawalDecisionPage() { + return ; +} diff --git a/app/support/guardian-withdrawals/GuardianWithdrawalForm.tsx b/app/support/guardian-withdrawals/GuardianWithdrawalForm.tsx index ae33fb8a..4c844128 100644 --- a/app/support/guardian-withdrawals/GuardianWithdrawalForm.tsx +++ b/app/support/guardian-withdrawals/GuardianWithdrawalForm.tsx @@ -6,9 +6,11 @@ import FormErrorMessage from "@/components/FormErrorMessage"; import { readResponseError } from "@/lib/client-response-error"; export default function GuardianWithdrawalForm() { + const [action, setAction] = useState("WITHDRAW"); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); - const [result, setResult] = useState<{ studentNotified: boolean; guardianNotified: boolean } | null>(null); + const [result, setResult] = useState<{ studentNotified?: boolean; guardianNotified: boolean } | null>(null); + const sendingLink = action === "REAUTHORISE" || action === "DELETE"; async function submit(event: FormEvent) { event.preventDefault(); @@ -25,6 +27,7 @@ export default function GuardianWithdrawalForm() { authorizationId: String(data.get("authorizationId") ?? "").trim(), caseReference: data.get("caseReference"), verified: data.get("verified") === "on", + action, }), }); if (!response.ok) { @@ -33,7 +36,7 @@ export default function GuardianWithdrawalForm() { } setResult(await response.json()); } catch { - setError("The result could not be confirmed. Use the same references to check or retry the notices."); + setError("The result could not be confirmed. Check the privacy case before retrying."); } finally { setBusy(false); } @@ -42,8 +45,21 @@ export default function GuardianWithdrawalForm() { return (

Guardian withdrawal

-

Use the verified request in the private privacy register. This ends the learner’s sessions and restricts access while saved work is held for a decision.

+

Use the verified request in the private privacy register. The account stays restricted while the guardian decides.

+ - {result && (
-

The account is restricted.

-

Student notice {result.studentNotified ? "accepted for sending." : "needs a retry."}

-

Guardian notice {result.guardianNotified ? "accepted for sending." : "needs a retry."}

+

{action === "CANCEL_DELETION" ? "Deletion was cancelled. The account stays restricted." : "The account is restricted."}

+ {sendingLink ? ( +

{result.guardianNotified ? "The guardian link was accepted for sending." : "The link could not be sent. Send a replacement link."}

+ ) : ( + <> +

Learner notice {result.studentNotified ? "accepted for sending." : "could not be sent."}

+

Guardian notice {result.guardianNotified ? "accepted for sending." : "could not be sent."}

+ {action === "CANCEL_DELETION" && (!result.studentNotified || !result.guardianNotified) && +

Follow up through the verified privacy case.

} + + )}
)}
diff --git a/docs/compliance/PARENTAL_AUTHORIZATION_RECORD.md b/docs/compliance/PARENTAL_AUTHORIZATION_RECORD.md index cfacef97..fb74e21c 100644 --- a/docs/compliance/PARENTAL_AUTHORIZATION_RECORD.md +++ b/docs/compliance/PARENTAL_AUTHORIZATION_RECORD.md @@ -102,6 +102,22 @@ privacy settings harder to reject than accept. permanent-deletion decision. - Escalate safeguarding conflicts to the appointed privacy/safeguarding owner. +### Decisions after withdrawal + +Match the verified guardian request to the original withdrawal in the +restricted privacy register. Keep the account restricted until the decision is +verified and recorded. Record the outcome and notify the learner and guardian. + +- **Reauthorisation.** Record a fresh guardian approval against the current + notices before restoring ordinary study access. Keep the original withdrawal + in the history and require a new sign-in. AI and WhatsApp remain unavailable + to under-18s. +- **Permanent deletion.** Record the verified confirmation and check whether + a documented retention exception applies. Keep the account restricted during + the cancellation window. If a verified guardian cancels deletion, return the + case to the withdrawal hold. Restoring study access requires a fresh approval. + Apply the [retention and deletion schedule](./DATA_RETENTION_AND_DELETION_SCHEDULE.md). + ## Access control - Students may see whether an authorisation is active and its feature scope. @@ -132,8 +148,13 @@ approved Data Retention and Deletion Schedule and legal holds. the account is restricted and existing Auth sessions are revoked. The action records each notice separately so a failed notice can be retried. Saved work is held for a decision through the verified privacy process. -- [ ] Record live acceptance and the operating evidence for verified - reauthorisation and deletion requests after a withdrawal. +- [x] Authorised operators can send a fresh decision link for a verified + reauthorisation or deletion request. Issuing a link preserves the withdrawal + hold. An older link cannot decide a replacement request. +- [x] Authorised operators can record verified deletion cancellation during the + cancellation window. The account returns to awaiting fresh guardian approval. +- [ ] Record live acceptance of both follow-up journeys in the restricted + privacy register. - [ ] Support cannot disclose child data without verifying authority. - [x] School staff cannot authorise or view learners because no school-facing account or access role is currently provided. diff --git a/lib/account-lifecycle.test.ts b/lib/account-lifecycle.test.ts index 11ffa4b9..0c68e757 100644 --- a/lib/account-lifecycle.test.ts +++ b/lib/account-lifecycle.test.ts @@ -88,7 +88,7 @@ describe("account lifecycle", () => { it("records an email confirmation request without locking the active account", async () => { vi.useFakeTimers(); vi.setSystemTime(new Date("2026-09-10T12:00:00.000Z")); - db.userFindUnique.mockResolvedValue({ accountStatus: "ACTIVE" }); + db.userUpdateMany.mockResolvedValue({ count: 1 }); db.requestUpsert.mockResolvedValue({ id: "request-1" }); const result = await preparePermanentDeletionConfirmation({ @@ -98,7 +98,10 @@ describe("account lifecycle", () => { }); expect(result).toEqual({ id: "request-1" }); - expect(db.userUpdateMany).not.toHaveBeenCalled(); + expect(db.userUpdateMany).toHaveBeenCalledWith({ + where: { id: "user-1", accountStatus: "ACTIVE" }, + data: { accountStatus: "ACTIVE" }, + }); expect(db.requestUpsert).toHaveBeenCalledWith( expect.objectContaining({ create: expect.objectContaining({ @@ -163,6 +166,13 @@ describe("account lifecycle", () => { expect(db.userUpdate).not.toHaveBeenCalled(); }); + it("cannot use the learner cancellation path for a withdrawn account", async () => { + db.userUpdateMany.mockResolvedValue({ count: 0 }); + await expect(cancelPermanentDeletion("withdrawn")).rejects.toBeInstanceOf(AccountLifecycleConflictError); + expect(db.userUpdateMany.mock.calls[0][0].where).toEqual({ id: "withdrawn", accountStatus: "DELETION_PENDING" }); + expect(db.requestUpdateMany).not.toHaveBeenCalled(); + }); + it("calculates 36 calendar months without overflowing month-end dates", () => { expect( inactiveAccountDeletionDate( diff --git a/lib/account-lifecycle.ts b/lib/account-lifecycle.ts index a7f73230..8b155298 100644 --- a/lib/account-lifecycle.ts +++ b/lib/account-lifecycle.ts @@ -16,6 +16,10 @@ const DELETION_DELAY_MS = DELETION_CANCELLATION_DAYS * 24 * 60 * 60 * 1_000; const DAY_MS = 24 * 60 * 60 * 1_000; const PROCESSING_LEASE_MS = 15 * 60 * 1_000; +export function permanentDeletionSchedule(confirmedAt: Date) { + return new Date(confirmedAt.getTime() + DELETION_DELAY_MS); +} + export class AccountLifecycleConflictError extends Error { constructor(message: string) { super(message); @@ -69,15 +73,11 @@ export async function preparePermanentDeletionConfirmation(input: { const now = new Date(); return prisma.$transaction(async (tx) => { - const current = await tx.user.findUnique({ - where: { id: input.userId }, - select: { accountStatus: true }, + const active = await tx.user.updateMany({ + where: { id: input.userId, accountStatus: AccountStatus.ACTIVE }, + data: { accountStatus: AccountStatus.ACTIVE }, }); - if (!current) { - throw new AccountLifecycleConflictError("Account not found."); - } - - if (current.accountStatus !== AccountStatus.ACTIVE) { + if (active.count !== 1) { throw new AccountLifecycleConflictError( "Only an active account can request permanent deletion." ); @@ -157,7 +157,7 @@ export async function abandonDeletionConfirmation( export async function confirmPermanentDeletion(tokenHash: string) { const now = new Date(); - const scheduledFor = new Date(now.getTime() + DELETION_DELAY_MS); + const scheduledFor = permanentDeletionSchedule(now); return prisma.$transaction(async (tx) => { const request = await tx.accountDeletionRequest.findUnique({ @@ -257,6 +257,21 @@ export async function reactivateAccount(userId: string) { export async function cancelPermanentDeletion(userId: string) { await prisma.$transaction(async (tx) => { + const user = await tx.user.updateMany({ + where: { id: userId, accountStatus: AccountStatus.DELETION_PENDING }, + data: { + accountStatus: AccountStatus.ACTIVE, + deactivatedAt: null, + inactiveDeletionAt: null, + inactiveWarning90SentAt: null, + inactiveWarning60SentAt: null, + inactiveWarning15SentAt: null, + inactiveWarning1SentAt: null, + }, + }); + if (user.count !== 1) { + throw new AccountLifecycleConflictError("This deletion request can no longer be cancelled."); + } const updated = await tx.accountDeletionRequest.updateMany({ where: { userId, @@ -281,18 +296,6 @@ export async function cancelPermanentDeletion(userId: string) { ); } - await tx.user.update({ - where: { id: userId }, - data: { - accountStatus: AccountStatus.ACTIVE, - deactivatedAt: null, - inactiveDeletionAt: null, - inactiveWarning90SentAt: null, - inactiveWarning60SentAt: null, - inactiveWarning15SentAt: null, - inactiveWarning1SentAt: null, - }, - }); }); } @@ -590,6 +593,7 @@ export async function processDueAccountDeletions(batchSize = 25) { const claimed = await prisma.accountDeletionRequest.updateMany({ where: { id: candidate.id, + scheduledFor: { lte: now }, OR: [ { status: { diff --git a/lib/guardian-withdrawal-follow-up.test.ts b/lib/guardian-withdrawal-follow-up.test.ts new file mode 100644 index 00000000..56057bed --- /dev/null +++ b/lib/guardian-withdrawal-follow-up.test.ts @@ -0,0 +1,138 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => { + const transaction = { + guardianAuthorization: { findUnique: vi.fn(), findFirst: vi.fn(), create: vi.fn() }, + guardianWithdrawalFollowUp: { findUnique: vi.fn(), upsert: vi.fn(), update: vi.fn(), updateMany: vi.fn() }, + user: { updateMany: vi.fn(), update: vi.fn() }, + accountDeletionRequest: { findUnique: vi.fn(), upsert: vi.fn(), updateMany: vi.fn() }, + guardianAuthorizationEvent: { create: vi.fn() }, + }; + return { transaction, send: vi.fn(), sync: vi.fn(), getUserById: vi.fn() }; +}); + +vi.mock("@/lib/prisma", () => ({ + prisma: { ...mocks.transaction, $transaction: async (run: (tx: typeof mocks.transaction) => unknown) => run(mocks.transaction) }, +})); +vi.mock("@/lib/guardian-authorization", async (importOriginal) => ({ + ...await importOriginal(), + syncAuthAccountStatus: mocks.sync, +})); +vi.mock("@/lib/security/timeouts", () => ({ fetchWithTimeout: mocks.send })); +vi.mock("@/lib/supabase/admin", () => ({ + getSupabaseAdminClient: () => ({ auth: { admin: { getUserById: mocks.getUserById } } }), +})); +vi.mock("@/lib/supabase/auth-redirect", () => ({ trustedAppOrigin: () => "https://studybuddy.example" })); + +import { cancelGuardianDeletion, decideGuardianFollowUp, getGuardianFollowUpDetails, startGuardianFollowUp } from "./guardian-withdrawal-follow-up"; + +const tx = mocks.transaction; +const operatorCase = { authorizationId: "withdrawn-1", caseReference: "privacy-reference-01", operatorUserId: "operator-1" }; +const grant = { + id: operatorCase.authorizationId, status: "WITHDRAWN", studentUserId: "learner-1", studentEmail: "learner@example.test", + guardianName: "Test Parent", guardianEmail: "guardian@example.test", relationship: "PARENT", + student: { deactivatedAt: null, profile: { dateOfBirth: new Date("2012-01-01") } }, +}; +const decision = { token: "test-confirmation", action: "REAUTHORISE" as const, ipFingerprint: "synthetic" }; +const pending = { + authorizationId: grant.id, action: "REAUTHORISE", status: "PENDING", caseReference: operatorCase.caseReference, + noticeVersion: "2026-11-26", termsVersion: "2026-11-26", +}; + +describe("guardian withdrawal follow-up", () => { + beforeEach(() => { + vi.resetAllMocks(); + vi.useRealTimers(); + vi.stubEnv("RESEND_API_KEY", "fake-provider"); + vi.stubEnv("TRANSACTIONAL_EMAIL_FROM", "Study Buddy "); + tx.guardianAuthorization.findUnique.mockResolvedValue(grant); + tx.guardianAuthorization.findFirst.mockResolvedValue({ id: grant.id }); + tx.user.updateMany.mockResolvedValue({ count: 1 }); + tx.guardianWithdrawalFollowUp.updateMany.mockResolvedValue({ count: 1 }); + mocks.send.mockResolvedValue(new Response(null, { status: 200 })); + mocks.getUserById.mockResolvedValue({ data: { user: { email: "learner@example.test", email_confirmed_at: "confirmed" } } }); + }); + + it("stores a replaceable invitation without granting access or queuing deletion", async () => { + const result = await startGuardianFollowUp({ ...operatorCase, action: "DELETE" }); + expect(result.guardianNotified).toBe(true); + expect(tx.guardianWithdrawalFollowUp.upsert).toHaveBeenCalledWith(expect.objectContaining({ + create: expect.objectContaining({ action: "DELETE", status: "PENDING", tokenHash: expect.stringMatching(/^[0-9a-f]{64}$/) }), + })); + expect(tx.accountDeletionRequest.upsert).not.toHaveBeenCalled(); + expect(mocks.send).toHaveBeenCalledTimes(1); + expect(JSON.parse(mocks.send.mock.calls[0][1].body)).toMatchObject({ to: ["guardian@example.test"] }); + }); + + it("cannot replace an already confirmed decision or act on an older withdrawal", async () => { + tx.guardianWithdrawalFollowUp.findUnique.mockResolvedValueOnce({ status: "CONFIRMED" }); + await expect(startGuardianFollowUp({ ...operatorCase, action: "REAUTHORISE" })).rejects.toThrow("confirmed decision"); + tx.guardianAuthorization.findFirst.mockResolvedValueOnce({ id: "other-withdrawal" }); + await expect(startGuardianFollowUp({ ...operatorCase, action: "DELETE" })).rejects.toThrow("current withdrawal"); + expect(mocks.send).not.toHaveBeenCalled(); + }); + + it("returns minimal review details while a current link remains pending", async () => { + tx.guardianWithdrawalFollowUp.findUnique.mockResolvedValue({ + action: "DELETE", status: "PENDING", expiresAt: new Date(Date.now() + 60_000), + noticeVersion: pending.noticeVersion, termsVersion: pending.termsVersion, + authorization: { status: "WITHDRAWN", student: { + accountStatus: "GUARDIAN_AUTHORIZATION_WITHDRAWN", profile: { firstName: "Test" }, + } }, + }); + expect(await getGuardianFollowUpDetails(decision.token)).toEqual({ action: "DELETE", learnerName: "Test" }); + tx.guardianWithdrawalFollowUp.findUnique.mockResolvedValueOnce({ status: "CONFIRMED" }); + expect(await getGuardianFollowUpDetails(decision.token)).toBeNull(); + }); + + it("consumes a matching link, writes a fresh grant and reports both notice outcomes", async () => { + tx.guardianWithdrawalFollowUp.findUnique.mockResolvedValue(pending); + mocks.send.mockResolvedValueOnce(new Response(null, { status: 503 })); + const result = await decideGuardianFollowUp(decision); + expect([result.studentNotified, result.guardianNotified].sort()).toEqual([false, true]); + expect(tx.user.update).toHaveBeenCalledWith({ where: { id: grant.studentUserId }, data: { + accountStatus: "ACTIVE", aiAccessAuthorized: false, inactiveDeletionAt: null, + } }); + expect(tx.guardianAuthorization.create).toHaveBeenCalledWith(expect.objectContaining({ + data: expect.objectContaining({ status: "GRANTED", aiAuthorized: false }), + })); + expect(mocks.sync).toHaveBeenCalledWith(grant.studentUserId, "ACTIVE"); + }); + + it("rejects an expired, replaced or wrongly scoped confirmation", async () => { + tx.guardianWithdrawalFollowUp.findUnique.mockResolvedValue(pending); + await expect(decideGuardianFollowUp({ ...decision, action: "DELETE" })).rejects.toThrow("invalid, expired"); + tx.guardianWithdrawalFollowUp.updateMany.mockResolvedValue({ count: 0 }); + await expect(decideGuardianFollowUp(decision)).rejects.toThrow("invalid, expired"); + expect(tx.user.update).not.toHaveBeenCalled(); + }); + + it("queues confirmed deletion with the existing window and preserves the hold", async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-11-30T12:00:00Z")); + tx.guardianWithdrawalFollowUp.findUnique.mockResolvedValue({ ...pending, action: "DELETE" }); + tx.accountDeletionRequest.upsert.mockResolvedValue({ id: "deletion-1" }); + const result = await decideGuardianFollowUp({ ...decision, action: "DELETE" }); + expect(result).toMatchObject({ scheduledFor: "2026-12-15T12:00:00.000Z", guardianNotified: true, studentNotified: true }); + expect(tx.accountDeletionRequest.upsert).toHaveBeenCalledWith(expect.objectContaining({ + create: expect.objectContaining({ scheduledFor: new Date(result.scheduledFor!), status: "PENDING" }), + })); + expect(tx.user.update).not.toHaveBeenCalled(); + expect(mocks.sync).not.toHaveBeenCalled(); + }); + + it("cancels the exact pending deletion and records the decision without restoring access", async () => { + tx.guardianWithdrawalFollowUp.findUnique.mockResolvedValue({ + ...pending, action: "DELETE", tokenHash: "original", status: "CONFIRMED", deletionRequestId: "deletion-1", + }); + tx.accountDeletionRequest.updateMany.mockResolvedValue({ count: 1 }); + expect(await cancelGuardianDeletion(operatorCase)).toEqual({ guardianNotified: true, studentNotified: true }); + expect(tx.accountDeletionRequest.updateMany).toHaveBeenCalledWith(expect.objectContaining({ + where: expect.objectContaining({ id: "deletion-1", userId: grant.studentUserId, scheduledFor: { gt: expect.any(Date) } }), + data: expect.objectContaining({ status: "CANCELLED", scheduledFor: null }), + })); + expect(tx.user.update).not.toHaveBeenCalled(); + tx.accountDeletionRequest.updateMany.mockResolvedValue({ count: 0 }); + await expect(cancelGuardianDeletion(operatorCase)).rejects.toThrow("window has closed"); + }); +}); diff --git a/lib/guardian-withdrawal-follow-up.ts b/lib/guardian-withdrawal-follow-up.ts new file mode 100644 index 00000000..25a20d36 --- /dev/null +++ b/lib/guardian-withdrawal-follow-up.ts @@ -0,0 +1,269 @@ +import type { GuardianFollowUpAction, Prisma } from "@prisma/client"; +import { ageOnDate, CHILD_PRIVACY_NOTICE_VERSION, INDEPENDENT_ACCOUNT_AGE, MINIMUM_ACCOUNT_AGE, TERMS_VERSION } from "@/lib/account-age"; +import { permanentDeletionSchedule, inactiveAccountDeletionDate } from "@/lib/account-lifecycle"; +import { createGuardianAuthorizationToken, guardianAuthorizationExpiry, hashGuardianAuthorizationToken, syncAuthAccountStatus } from "@/lib/guardian-authorization"; +import { GuardianWithdrawalConflict } from "@/lib/guardian-withdrawal"; +import { PRIVACY_EMAIL } from "@/lib/legal-entity"; +import { prisma } from "@/lib/prisma"; +import { logSecurityEvent, securityFingerprint } from "@/lib/security/audit-log"; +import { fetchWithTimeout } from "@/lib/security/timeouts"; +import { getSupabaseAdminClient } from "@/lib/supabase/admin"; +import { trustedAppOrigin } from "@/lib/supabase/auth-redirect"; + +type OperatorCase = { authorizationId: string; caseReference: string; operatorUserId: string }; + +async function lockWithdrawnAccount(tx: Prisma.TransactionClient, authorizationId: string) { + const authorization = await tx.guardianAuthorization.findUnique({ + where: { id: authorizationId }, + include: { student: { select: { deactivatedAt: true, profile: { select: { dateOfBirth: true } } } } }, + }); + if (!authorization || authorization.status !== "WITHDRAWN") { + throw new GuardianWithdrawalConflict("This authorisation is no longer eligible."); + } + const locked = await tx.user.updateMany({ + where: { id: authorization.studentUserId, accountStatus: "GUARDIAN_AUTHORIZATION_WITHDRAWN" }, + data: { accountStatus: "GUARDIAN_AUTHORIZATION_WITHDRAWN" }, + }); + const current = await tx.guardianAuthorization.findFirst({ + where: { studentUserId: authorization.studentUserId, status: "WITHDRAWN" }, + orderBy: [{ withdrawnAt: "desc" }, { id: "desc" }], + select: { id: true }, + }); + if (!locked.count || current?.id !== authorization.id) { + throw new GuardianWithdrawalConflict("This is not the current withdrawal."); + } + return authorization; +} + +function requireMinor(dateOfBirth: Date | null | undefined, now: Date) { + const age = dateOfBirth ? ageOnDate(dateOfBirth, now) : NaN; + if (!Number.isFinite(age) || age < MINIMUM_ACCOUNT_AGE || age >= INDEPENDENT_ACCOUNT_AGE) { + throw new GuardianWithdrawalConflict("This account needs a separate privacy review."); + } +} + +export async function startGuardianFollowUp(input: OperatorCase & { action: GuardianFollowUpAction }) { + const { token, tokenHash } = createGuardianAuthorizationToken(); + const expiresAt = guardianAuthorizationExpiry(); + const origin = trustedAppOrigin(); + const authorization = await prisma.$transaction(async (tx) => { + const current = await lockWithdrawnAccount(tx, input.authorizationId); + requireMinor(current.student.profile?.dateOfBirth, new Date()); + const followUp = await tx.guardianWithdrawalFollowUp.findUnique({ + where: { authorizationId: current.id }, select: { status: true }, + }); + if (followUp?.status === "CONFIRMED") { + throw new GuardianWithdrawalConflict("A confirmed decision already exists."); + } + const pending = { + action: input.action, + status: "PENDING" as const, + tokenHash, + expiresAt, + caseReference: input.caseReference, + noticeVersion: CHILD_PRIVACY_NOTICE_VERSION, + termsVersion: TERMS_VERSION, + deletionRequestId: null, + }; + await tx.guardianWithdrawalFollowUp.upsert({ + where: { authorizationId: current.id }, + create: { authorizationId: current.id, ...pending }, + update: pending, + }); + await tx.guardianAuthorizationEvent.create({ data: { + authorizationId: current.id, eventType: "FOLLOW_UP_REQUESTED", actorType: "PRIVACY_OPERATOR", + details: { caseReference: input.caseReference, operatorUserId: input.operatorUserId, action: input.action }, + } }); + return current; + }); + + const purpose = input.action === "REAUTHORISE" ? "restore study access" : "confirm permanent deletion"; + const guardianNotified = await sendNotice({ + recipient: "guardian", authorization, key: "invite-" + tokenHash, + subject: "Review your Study Buddy privacy request", + message: `We have received a verified request to ${purpose}. Review it using this one-time link before ${expiresAt.toUTCString()}:\n\n${origin}/guardian-withdrawal-decision#token=${token}\n\nThe learner account remains restricted while you decide.`, + }); + return { guardianNotified }; +} + +export async function getGuardianFollowUpDetails(token: string) { + const request = await prisma.guardianWithdrawalFollowUp.findUnique({ + where: { tokenHash: hashGuardianAuthorizationToken(token) }, + select: { + action: true, status: true, expiresAt: true, + noticeVersion: true, termsVersion: true, + authorization: { select: { + status: true, + student: { select: { accountStatus: true, profile: { select: { firstName: true } } } }, + } }, + }, + }); + if (request?.status !== "PENDING" || request.expiresAt <= new Date() || + request.noticeVersion !== CHILD_PRIVACY_NOTICE_VERSION || request.termsVersion !== TERMS_VERSION || + request.authorization.status !== "WITHDRAWN" || + request.authorization.student.accountStatus !== "GUARDIAN_AUTHORIZATION_WITHDRAWN") return null; + return { action: request.action, learnerName: request.authorization.student.profile?.firstName ?? null }; +} + +export async function decideGuardianFollowUp(input: { + token: string; + action: GuardianFollowUpAction; + ipFingerprint: string; +}) { + const tokenHash = hashGuardianAuthorizationToken(input.token); + const decision = await prisma.$transaction(async (tx) => { + const request = await tx.guardianWithdrawalFollowUp.findUnique({ where: { tokenHash } }); + if (request?.status !== "PENDING" || request.action !== input.action) throw invalidLink(); + const authorization = await lockWithdrawnAccount(tx, request.authorizationId); + const now = new Date(); + requireMinor(authorization.student.profile?.dateOfBirth, now); + if (request.noticeVersion !== CHILD_PRIVACY_NOTICE_VERSION || request.termsVersion !== TERMS_VERSION) throw invalidLink(); + const consumed = await tx.guardianWithdrawalFollowUp.updateMany({ + where: { authorizationId: authorization.id, status: "PENDING", tokenHash, expiresAt: { gt: now } }, + data: { status: "CONFIRMED" }, + }); + if (!consumed.count) throw invalidLink(); + + let nextStatus: "ACTIVE" | "DEACTIVATED" | undefined; + let scheduledFor: Date | undefined; + const userId = authorization.studentUserId; + if (input.action === "REAUTHORISE") { + const deactivatedAt = authorization.student.deactivatedAt; + nextStatus = deactivatedAt ? "DEACTIVATED" : "ACTIVE"; + await tx.user.update({ where: { id: userId }, data: { + accountStatus: nextStatus, aiAccessAuthorized: false, + inactiveDeletionAt: deactivatedAt ? inactiveAccountDeletionDate(deactivatedAt) : null, + } }); + await tx.guardianAuthorization.create({ data: { + studentUserId: userId, + studentEmail: authorization.studentEmail, + guardianName: authorization.guardianName, + guardianEmail: authorization.guardianEmail, + relationship: authorization.relationship, + tokenHash: createGuardianAuthorizationToken().tokenHash, + tokenExpiresAt: now, + status: "GRANTED", aiAuthorized: false, decidedAt: now, + noticeVersion: request.noticeVersion, termsVersion: request.termsVersion, + verificationMethod: "WITHDRAWAL_FOLLOW_UP_EMAIL", + events: { create: { + eventType: "GRANTED", actorType: "GUARDIAN", ipFingerprint: input.ipFingerprint, + details: { accountAndLearningAuthorized: true, aiAuthorized: false }, + } }, + } }); + } else { + const existing = await tx.accountDeletionRequest.findUnique({ + where: { userId }, select: { status: true }, + }); + if (existing && existing.status !== "CANCELLED") { + throw new GuardianWithdrawalConflict("A different deletion request already exists."); + } + scheduledFor = permanentDeletionSchedule(now); + const pending = { + authUserId: userId, accountFingerprint: securityFingerprint(userId), status: "PENDING" as const, + requestedAt: now, confirmedAt: now, scheduledFor, confirmationSentAt: null, + confirmationTokenHash: null, confirmationTokenExpiresAt: null, retentionTriggeredAt: null, + processingStartedAt: null, completedAt: null, cancelledAt: null, attemptCount: 0, lastFailureCode: null, + }; + const deletion = await tx.accountDeletionRequest.upsert({ + where: { userId }, create: { userId, ...pending }, update: pending, select: { id: true }, + }); + await tx.guardianWithdrawalFollowUp.update({ + where: { authorizationId: authorization.id }, data: { deletionRequestId: deletion.id }, + }); + } + await tx.guardianAuthorizationEvent.create({ data: { + authorizationId: authorization.id, + eventType: nextStatus ? "REAUTHORISED" : "DELETION_CONFIRMED", + actorType: "GUARDIAN", ipFingerprint: input.ipFingerprint, + details: { caseReference: request.caseReference, ...(scheduledFor ? { scheduledFor: scheduledFor.toISOString() } : {}) }, + } }); + return { authorization, nextStatus, scheduledFor }; + }); + + if (decision.nextStatus) await syncAuthAccountStatus(decision.authorization.studentUserId, decision.nextStatus); + const message = decision.scheduledFor + ? `A verified guardian confirmed permanent deletion. The learner account remains restricted. Contact ${PRIVACY_EMAIL} before ${decision.scheduledFor.toUTCString()} to withdraw the deletion request.` + : decision.nextStatus === "DEACTIVATED" + ? "A guardian approved ordinary study again. The learner can sign in and choose whether to reactivate their account. AI remains paused for under-18s." + : "A guardian approved ordinary study again. The learner can sign in to resume study. AI remains paused for under-18s."; + const notices = await notifyBoth(decision.authorization, "confirmed-" + tokenHash, message); + return { action: input.action, scheduledFor: decision.scheduledFor?.toISOString(), ...notices }; +} + +export async function cancelGuardianDeletion(input: OperatorCase) { + const result = await prisma.$transaction(async (tx) => { + const authorization = await lockWithdrawnAccount(tx, input.authorizationId); + const followUp = await tx.guardianWithdrawalFollowUp.findUnique({ where: { authorizationId: authorization.id } }); + if (followUp?.status !== "CONFIRMED" || followUp.action !== "DELETE" || !followUp.deletionRequestId) { + throw new GuardianWithdrawalConflict("No confirmed guardian deletion can be cancelled."); + } + const now = new Date(); + const cancelled = await tx.accountDeletionRequest.updateMany({ + where: { + id: followUp.deletionRequestId, userId: authorization.studentUserId, status: "PENDING", + scheduledFor: { gt: now }, retentionTriggeredAt: null, + }, + data: { status: "CANCELLED", cancelledAt: now, scheduledFor: null }, + }); + if (!cancelled.count) throw new GuardianWithdrawalConflict("The cancellation window has closed."); + await tx.guardianWithdrawalFollowUp.update({ + where: { authorizationId: authorization.id }, data: { status: "CANCELLED" }, + }); + await tx.guardianAuthorizationEvent.create({ data: { + authorizationId: authorization.id, eventType: "DELETION_CANCELLED", actorType: "PRIVACY_OPERATOR", + details: { caseReference: input.caseReference, operatorUserId: input.operatorUserId }, + } }); + return { authorization, tokenHash: followUp.tokenHash }; + }); + return notifyBoth(result.authorization, "cancelled-" + result.tokenHash, + "The permanent deletion request was cancelled. The learner account remains restricted until a guardian gives fresh approval."); +} + +function invalidLink() { + return new GuardianWithdrawalConflict("This decision link is invalid, expired, or already used."); +} + +type NoticeTarget = { guardianEmail: string; studentUserId: string }; + +async function notifyBoth(authorization: NoticeTarget, key: string, message: string) { + const subject = "Study Buddy guardian decision update"; + const [studentNotified, guardianNotified] = await Promise.all([ + sendNotice({ recipient: "student", authorization, key, subject, message }), + sendNotice({ recipient: "guardian", authorization, key, subject, message }), + ]); + return { studentNotified, guardianNotified }; +} + +async function sendNotice(input: { + recipient: "guardian" | "student"; authorization: NoticeTarget; key: string; subject: string; message: string; +}) { + try { + const apiKey = process.env.RESEND_API_KEY?.trim(); + const from = process.env.TRANSACTIONAL_EMAIL_FROM?.trim(); + if (!apiKey || !from) throw new Error("Email delivery unavailable."); + let email = input.authorization.guardianEmail; + if (input.recipient === "student") { + const { data, error } = await getSupabaseAdminClient().auth.admin.getUserById(input.authorization.studentUserId); + if (error || !data.user?.email || !data.user.email_confirmed_at) throw new Error("Learner email unavailable."); + email = data.user.email; + } + const response = await fetchWithTimeout("https://api.resend.com/emails", { + method: "POST", + headers: { + Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", + "Idempotency-Key": `guardian-follow-up-${input.key}-${input.recipient}`, + }, + body: JSON.stringify({ + from, to: [email], reply_to: PRIVACY_EMAIL, subject: input.subject, + text: `${input.message}\n\nQuestions? Contact ${PRIVACY_EMAIL}.`, + }), + }); + if (!response.ok) throw new Error("Email delivery unavailable."); + return true; + } catch { + logSecurityEvent("guardian_follow_up_notice_failed", "warn", { + accountFingerprint: securityFingerprint(input.authorization.studentUserId), recipient: input.recipient, + }); + return false; + } +} diff --git a/prisma/migrations/20261130120000_guardian_withdrawal_follow_up/migration.sql b/prisma/migrations/20261130120000_guardian_withdrawal_follow_up/migration.sql new file mode 100644 index 00000000..d5430639 --- /dev/null +++ b/prisma/migrations/20261130120000_guardian_withdrawal_follow_up/migration.sql @@ -0,0 +1,40 @@ +BEGIN; + +ALTER TYPE "GuardianAuthorizationEventType" ADD VALUE 'FOLLOW_UP_REQUESTED'; +ALTER TYPE "GuardianAuthorizationEventType" ADD VALUE 'REAUTHORISED'; +ALTER TYPE "GuardianAuthorizationEventType" ADD VALUE 'DELETION_CONFIRMED'; +ALTER TYPE "GuardianAuthorizationEventType" ADD VALUE 'DELETION_CANCELLED'; + +CREATE TYPE "GuardianFollowUpAction" AS ENUM ('REAUTHORISE', 'DELETE'); +CREATE TYPE "GuardianFollowUpStatus" AS ENUM ('PENDING', 'CONFIRMED', 'CANCELLED'); + +CREATE TABLE "GuardianWithdrawalFollowUp" ( + "authorizationId" TEXT NOT NULL, + "action" "GuardianFollowUpAction" NOT NULL, + "status" "GuardianFollowUpStatus" NOT NULL DEFAULT 'PENDING', + "tokenHash" VARCHAR(64) NOT NULL, + "expiresAt" TIMESTAMP(3) NOT NULL, + "caseReference" VARCHAR(80) NOT NULL, + "noticeVersion" VARCHAR(32) NOT NULL, + "termsVersion" VARCHAR(32) NOT NULL, + "deletionRequestId" TEXT, + CONSTRAINT "GuardianWithdrawalFollowUp_pkey" PRIMARY KEY ("authorizationId"), + CONSTRAINT "GuardianWithdrawalFollowUp_authorizationId_fkey" + FOREIGN KEY ("authorizationId") REFERENCES "GuardianAuthorization"("id") + ON DELETE CASCADE ON UPDATE CASCADE +); +CREATE UNIQUE INDEX "GuardianWithdrawalFollowUp_tokenHash_key" ON "GuardianWithdrawalFollowUp" ("tokenHash"); + +ALTER TABLE "GuardianWithdrawalFollowUp" ENABLE ROW LEVEL SECURITY; +REVOKE ALL PRIVILEGES ON "GuardianWithdrawalFollowUp" FROM PUBLIC, anon, authenticated; +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'studybuddy_runtime') THEN + GRANT SELECT, INSERT, UPDATE ON "GuardianWithdrawalFollowUp" TO studybuddy_runtime; + END IF; + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'railway_staging_web') THEN + GRANT SELECT, INSERT, UPDATE ON "GuardianWithdrawalFollowUp" TO railway_staging_web; + END IF; +END $$; + +COMMIT; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 672aa165..d4de3995 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -184,6 +184,21 @@ enum GuardianAuthorizationEventType { WITHDRAWN EXPIRED SUPERSEDED + FOLLOW_UP_REQUESTED + REAUTHORISED + DELETION_CONFIRMED + DELETION_CANCELLED +} + +enum GuardianFollowUpAction { + REAUTHORISE + DELETE +} + +enum GuardianFollowUpStatus { + PENDING + CONFIRMED + CANCELLED } enum PasswordResetSecurityEventType { @@ -461,12 +476,27 @@ model GuardianAuthorization { student User @relation(fields: [studentUserId], references: [id], onDelete: Cascade) events GuardianAuthorizationEvent[] + followUp GuardianWithdrawalFollowUp? @@index([studentUserId, status, createdAt], map: "GuardianAuthorization_student_status_idx") @@index([guardianEmail, status], map: "GuardianAuthorization_guardian_status_idx") @@index([tokenExpiresAt], map: "GuardianAuthorization_token_expiry_idx") } +model GuardianWithdrawalFollowUp { + authorizationId String @id + action GuardianFollowUpAction + status GuardianFollowUpStatus @default(PENDING) + tokenHash String @unique @db.VarChar(64) + expiresAt DateTime + caseReference String @db.VarChar(80) + noticeVersion String @db.VarChar(32) + termsVersion String @db.VarChar(32) + deletionRequestId String? + + authorization GuardianAuthorization @relation(fields: [authorizationId], references: [id], onDelete: Cascade) +} + model GuardianAuthorizationEvent { id String @id @default(uuid()) authorizationId String diff --git a/tests/api-route-contracts.ts b/tests/api-route-contracts.ts index 9d1a2341..80563641 100644 --- a/tests/api-route-contracts.ts +++ b/tests/api-route-contracts.ts @@ -59,6 +59,7 @@ const routes: Record>> = { "/api/v1/contact": { POST: rule("public", "Validated, bounded contact form") }, "/api/v1/dashboard/stats": { GET: rule("learner", "Current learner only") }, "/api/v1/guardian-authorizations/decision": { POST: rule("email-link", "One-time token, decision and required declarations") }, + "/api/v1/guardian-authorizations/follow-up": { POST: rule("email-link", "One-time guardian follow-up token and explicit confirmation") }, "/api/v1/guardian-authorizations/lookup": { POST: rule("email-link", "Guardian token for the requested decision") }, "/api/v1/guardian-authorizations/resend": { POST: rule("session", "Current account's pending guardian request") }, "/api/v1/login": { POST: rule("public", "Bounded credentials and CAPTCHA when required") }, diff --git a/tests/e2e/account-lifecycle.spec.ts b/tests/e2e/account-lifecycle.spec.ts index bad76f0c..b841dfe0 100644 --- a/tests/e2e/account-lifecycle.spec.ts +++ b/tests/e2e/account-lifecycle.spec.ts @@ -9,7 +9,7 @@ const PASSWORD = "Lifecycle-original-password-42!"; const NEW_PASSWORD = "Lifecycle-recovered-password-42!"; const CRON_SECRET = "e2e-account-deletion-cron-secret-only"; -type Mail = { subject: string; link?: string; html?: string }; +type Mail = { subject: string; link?: string; html?: string; text?: string }; async function mail(request: APIRequestContext, to: string, subject: RegExp, count = 1) { let matching: Mail[] = []; @@ -24,7 +24,7 @@ async function mail(request: APIRequestContext, to: string, subject: RegExp, cou } function emailLink(message: Mail, pathname: string) { - const value = message.link ?? message.html?.match(/href="(http[^"\s]+)"/)?.[1]; + const value = message.link ?? message.html?.match(/href="(http[^"\s]+)"/)?.[1] ?? message.text?.match(/https?:\/\/\S+/)?.[0]; expect(value, `Email should include a link to ${pathname}`).toBeTruthy(); const url = new URL(value!); expect(url.origin).toBe(APP_ORIGIN); @@ -294,6 +294,108 @@ test("a verified guardian withdrawal revokes sessions, holds saved work and retr } }); +test("guardian follow-up confirms fresh access or deletion without lifting the withdrawal hold early", async ({ page, browser, request, playwright }) => { + test.setTimeout(90_000); + const studentEmail = "follow-up-student@example.test"; + const guardianEmail = "follow-up-guardian@example.test"; + await verifyEmail(page, await signUp(page, request, studentEmail, guardianEmail)); + const guardian = await browser.newPage(); + const operator = await playwright.request.newContext({ baseURL: APP_ORIGIN }); + try { + const initial = emailLink(await mail(request, guardianEmail, /^Approve /), "/guardian-authorization"); + await openEmail(guardian, initial); + await guardian.getByRole("checkbox", { name: /I confirm I am this student/ }).check(); + await guardian.getByRole("checkbox", { name: /I reviewed/ }).check(); + await guardian.getByRole("button", { name: "Approve account" }).click(); + await expect(guardian.getByText(/Your decision has been recorded/)).toBeVisible(); + await login(page, studentEmail); + await expect(page).toHaveURL(/\/dashboard$/); + const studentId = await getUserId(page); + const grant = await withDatabase(async (database) => { + await database.aiChat.create({ data: { userId: studentId, title: "Saved study history" } }); + return database.guardianAuthorization.findFirstOrThrow({ where: { studentUserId: studentId, status: "GRANTED" } }); + }); + expect((await operator.post("/api/v1/login", { + headers: { Origin: APP_ORIGIN }, data: { identifier: fixtureUsers.learner.email, password: fixtureUsers.learner.password }, + })).status()).toBe(200); + const operate = (action: string, authorizationId = grant.id) => + operator.post("/api/v1/support/guardian-withdrawals", { + headers: { Origin: APP_ORIGIN }, data: { action, authorizationId, caseReference: "follow-up-case-001", verified: true }, + }); + const invite = async (count: number) => emailLink(await mail(request, guardianEmail, /^Review your Study Buddy privacy request$/, count), "/guardian-withdrawal-decision"); + expect((await operate("WITHDRAW")).status()).toBe(200); + expect(await (await operate("REAUTHORISE")).json()).toMatchObject({ restricted: true, guardianNotified: true }); + const supersededLink = await invite(1); + expect(await (await operate("DELETE")).json()).toMatchObject({ restricted: true, guardianNotified: true }); + await openEmail(guardian, supersededLink); + await expect(guardian.getByText(/This link is invalid/)).toBeVisible(); + const deletionLink = await invite(2); + await openEmail(guardian, deletionLink); + expect(await withDatabase((database) => database.accountDeletionRequest.count({ where: { userId: studentId } }))).toBe(0); + await guardian.getByRole("checkbox", { name: /I am the parent/ }).check(); + await guardian.getByRole("checkbox", { name: /I confirm permanent deletion/ }).check(); + await guardian.getByRole("button", { name: "Confirm permanent deletion" }).click(); + await expect(guardian.getByText("Your decision was recorded.")).toBeVisible(); + const scheduled = await withDatabase((database) => database.accountDeletionRequest.findUniqueOrThrow({ where: { userId: studentId } })); + expect(scheduled.status).toBe("PENDING"); + expect(scheduled.scheduledFor!.getTime() - scheduled.confirmedAt!.getTime()).toBe(15 * 24 * 60 * 60 * 1000); + expect((await page.request.post("/api/v1/account/lifecycle", { + headers: { Origin: APP_ORIGIN }, data: { action: "CANCEL_DELETION" }, + })).status()).toBe(403); + expect((await operate("REAUTHORISE")).status()).toBe(409); + expect((await operate("CANCEL_DELETION")).status()).toBe(200); + await openEmail(guardian, deletionLink); + await expect(guardian.getByText(/This link is invalid/)).toBeVisible(); + expect([401, 403]).toContain((await page.request.get("/api/v1/me")).status()); + expect(await withDatabase((database) => database.user.findUnique({ + where: { id: studentId }, select: { accountStatus: true }, + }))).toEqual({ accountStatus: "GUARDIAN_AUTHORIZATION_WITHDRAWN" }); + expect((await operate("REAUTHORISE")).status()).toBe(200); + await openEmail(guardian, await invite(3)); + await guardian.getByRole("checkbox", { name: /I am the parent/ }).check(); + await guardian.getByRole("checkbox", { name: /I approve ordinary study/ }).check(); + await guardian.getByRole("button", { name: "Restore study access" }).click(); + await expect(guardian.getByText("Your decision was recorded.")).toBeVisible(); + await page.context().clearCookies(); + await login(page, studentEmail); + await expect(page).toHaveURL(/\/dashboard$/); + expect((await page.request.get("/api/v1/ai/chats")).status()).toBe(403); + await withDatabase(async (database) => { + expect(await database.aiChat.count({ where: { userId: studentId } })).toBe(1); + expect(await database.guardianAuthorization.findUnique({ where: { id: grant.id } })).toMatchObject({ status: "WITHDRAWN" }); + expect(await database.guardianAuthorizationEvent.findMany({ where: { authorizationId: grant.id }, select: { eventType: true } })).toEqual( + expect.arrayContaining([{ eventType: "DELETION_CONFIRMED" }, { eventType: "DELETION_CANCELLED" }, { eventType: "REAUTHORISED" }]), + ); + }); + + const renewedGrant = await withDatabase((database) => database.guardianAuthorization.findFirstOrThrow({ + where: { studentUserId: studentId, status: "GRANTED" }, + })); + expect((await operate("WITHDRAW", renewedGrant.id)).status()).toBe(200); + expect((await operate("DELETE", renewedGrant.id)).status()).toBe(200); + await openEmail(guardian, await invite(4)); + await guardian.getByRole("checkbox", { name: /I am the parent/ }).check(); + await guardian.getByRole("checkbox", { name: /I confirm permanent deletion/ }).check(); + await guardian.getByRole("button", { name: "Confirm permanent deletion" }).click(); + await expect(guardian.getByText("Your decision was recorded.")).toBeVisible(); + await withDatabase((database) => database.accountDeletionRequest.update({ + where: { id: scheduled.id }, data: { scheduledFor: new Date(Date.now() - 1_000) }, + })); + const run = await request.post("/api/v1/account/deletion/cron", { headers: { "x-cron-secret": CRON_SECRET } }); + expect(run.status()).toBe(200); + expect((await run.json()).deletions).toEqual({ examined: 1, completed: 1, failed: 0 }); + await withDatabase(async (database) => { + expect(await database.user.count({ where: { id: studentId } })).toBe(0); + expect(await database.aiChat.count({ where: { userId: studentId } })).toBe(0); + expect(await database.accountDeletionRequest.findUnique({ where: { id: scheduled.id } })).toMatchObject({ + status: "COMPLETED", userId: null, authUserId: null, + }); + }); + } finally { + await Promise.all([guardian.close(), operator.dispose()]); + } +}); + test("password-reset warnings require confirmation and a locked account can recover", async ({ page, request }) => { const email = "reset-student@example.test"; await verifyEmail(page, await signUp(page, request, email)); diff --git a/tests/e2e/support/fake-supabase-auth.mjs b/tests/e2e/support/fake-supabase-auth.mjs index 5a76d518..372a62a1 100644 --- a/tests/e2e/support/fake-supabase-auth.mjs +++ b/tests/e2e/support/fake-supabase-auth.mjs @@ -78,7 +78,7 @@ async function handleRequest(request, response) { return sendJson(response, 400, { error: "Invalid synthetic email" }); } if (failedDeliveries.delete(recipient)) return sendJson(response, 503, { error: "Simulated delivery failure" }); - outbox.push({ to: recipient, subject: body.subject, html: body.html }); + outbox.push({ to: recipient, subject: body.subject, html: body.html, text: body.text }); return sendJson(response, 200, { id: randomUUID() }); } if (method === "POST" && pathname === "/openai/fail-next-completion" && typeof body.prompt === "string") {