Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
07e8e49
docs(readme): add deferred production checks section
VictoriousWealth Nov 30, 2026
2268ea7
docs(api): update guardian follow-up process
VictoriousWealth Nov 30, 2026
2b62307
feat(api): add guardian follow-up route
VictoriousWealth Nov 30, 2026
beb84ef
feat(withdrawals): enhance withdrawal handling
VictoriousWealth Nov 30, 2026
937b241
feat(guardian-withdrawal-decision): add guardian withdrawal decision …
VictoriousWealth Nov 30, 2026
2387834
feat(guardian-withdrawal-decision): add guardian withdrawal decision …
VictoriousWealth Nov 30, 2026
47937bb
feat(guardian-withdrawals): enhance withdrawal form functionality
VictoriousWealth Nov 30, 2026
734dc79
docs(compliance): update parental authorization process
VictoriousWealth Nov 30, 2026
098c994
test(account-lifecycle): update email confirmation request test
VictoriousWealth Nov 30, 2026
aed0df2
feat(account-lifecycle): add permanent deletion schedule
VictoriousWealth Nov 30, 2026
135ffda
test(guardian-withdrawal-follow-up): add unit tests for follow-up logic
VictoriousWealth Nov 30, 2026
049c1c0
feat(guardian-withdrawal): implement email follow-up for withdrawn ac…
VictoriousWealth Nov 30, 2026
81b45a8
feat(migrations): add guardian withdrawal follow up migration
VictoriousWealth Nov 30, 2026
e035ca9
feat(prisma): add follow-up models and enums
VictoriousWealth Nov 30, 2026
247b4a5
feat(tests): add follow-up route for guardian authorizations
VictoriousWealth Nov 30, 2026
afa0c40
test(account-lifecycle): add guardian follow-up email confirmation
VictoriousWealth Nov 30, 2026
7edd649
fix(tests): add text field to outbox message
VictoriousWealth Nov 30, 2026
2929d22
test(account-lifecycle): enhance deletion cancellation tests
VictoriousWealth Nov 30, 2026
274fa72
test(account-lifecycle): improve guardian follow-up checks
VictoriousWealth Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
3 changes: 3 additions & 0 deletions app/api/v1/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
50 changes: 50 additions & 0 deletions app/api/v1/guardian-authorizations/follow-up/route.ts
Original file line number Diff line number Diff line change
@@ -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;
}
}
22 changes: 17 additions & 5 deletions app/api/v1/support/guardian-withdrawals/route.ts
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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 });
Expand Down
107 changes: 107 additions & 0 deletions app/guardian-withdrawal-decision/GuardianWithdrawalDecision.tsx
Original file line number Diff line number Diff line change
@@ -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<Details | null | undefined>(undefined);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [result, setResult] = useState<Result | null>(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<HTMLFormElement>) {
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 (
<section className="mx-auto my-10 w-full max-w-xl space-y-4 rounded-xl border border-gray-200 bg-white p-6">
<h1 className="text-2xl font-bold text-gray-900">Guardian decision</h1>
{details === undefined && <p role="status">Checking your secure link…</p>}
{details === null && <p>This link is invalid, expired, or already used.</p>}
{result ? (
<div role="status" className="space-y-2">
<p>Your decision was recorded.</p>
<p>{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."}</p>
{(!result.studentNotified || !result.guardianNotified) && <p>One or more confirmation emails could not be sent.</p>}
</div>
) : details && (
<form onSubmit={confirm} className="space-y-4">
{details.learnerName && <p>This request is for <strong>{details.learnerName}</strong>.</p>}
<p>{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."}</p>
<label className="flex items-start gap-2">
<input name="authority" type="checkbox" required className="mt-1" />
<span>I am the parent or legal guardian and have authority to make this decision.</span>
</label>
<label className="flex items-start gap-2">
<input name="decision" type="checkbox" required className="mt-1" />
<span>{deletion ? "I confirm permanent deletion." : (
<>I approve ordinary study and have reviewed the <a className="underline" href="/parent-student-privacy" target="_blank" rel="noreferrer">Parent and Student Privacy Notice</a>, <a className="underline" href="/privacy-policy" target="_blank" rel="noreferrer">Privacy Policy</a>, and <a className="underline" href="/terms-of-service" target="_blank" rel="noreferrer">Terms of Service</a>.</>
)}</span>
</label>
<Button type="submit" variant={deletion ? "destructive" : "primary"} loading={busy}>
{deletion ? "Confirm permanent deletion" : "Restore study access"}
</Button>
<FormErrorMessage id="guardian-follow-up-error" message={error} />
</form>
)}
<p className="text-sm">For help, email <a className="underline" href={`mailto:${PRIVACY_EMAIL}`}>{PRIVACY_EMAIL}</a>.</p>
</section>
);
}
12 changes: 12 additions & 0 deletions app/guardian-withdrawal-decision/page.tsx
Original file line number Diff line number Diff line change
@@ -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 <GuardianWithdrawalDecision />;
}
46 changes: 36 additions & 10 deletions app/support/guardian-withdrawals/GuardianWithdrawalForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLFormElement>) {
event.preventDefault();
Expand All @@ -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) {
Expand All @@ -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);
}
Expand All @@ -42,8 +45,21 @@ export default function GuardianWithdrawalForm() {
return (
<section className="mx-auto my-8 w-full max-w-xl space-y-5 rounded-xl border border-gray-200 bg-white p-6">
<h1 className="text-2xl font-bold text-gray-900">Guardian withdrawal</h1>
<p className="text-sm text-gray-700">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.</p>
<p className="text-sm text-gray-700">Use the verified request in the private privacy register. The account stays restricted while the guardian decides.</p>
<form className="space-y-4" onSubmit={submit}>
<label className="block text-sm font-semibold text-gray-900">
Action
<select value={action} disabled={busy} onChange={(event) => {
setAction(event.target.value);
setResult(null);
setError("");
}} className="mt-1 block w-full rounded-lg border border-gray-400 p-3">
<option value="WITHDRAW">Record a withdrawal</option>
<option value="REAUTHORISE">Send a fresh approval link</option>
<option value="DELETE">Send a permanent deletion confirmation link</option>
<option value="CANCEL_DELETION">Record a verified deletion cancellation</option>
</select>
</label>
<label className="block text-sm font-semibold text-gray-900">
Guardian authorisation ID
<input name="authorizationId" autoComplete="off" required maxLength={36} className="mt-1 block w-full rounded-lg border border-gray-400 p-3" />
Expand All @@ -53,19 +69,29 @@ export default function GuardianWithdrawalForm() {
<input name="caseReference" autoComplete="off" required minLength={8} maxLength={80} className="mt-1 block w-full rounded-lg border border-gray-400 p-3" />
</label>
<label className="flex items-start gap-2 text-sm text-gray-900">
<input type="checkbox" name="verified" required className="mt-1" />
<span>I verified the requester’s authority and matched the case to this authorisation.</span>
<input key={action} type="checkbox" name="verified" required className="mt-1" />
<span>I verified the requester’s authority and matched the case to this authorisation.{action === "DELETE" ? " I also reviewed applicable retention requirements." : ""}</span>
</label>
<Button type="submit" variant="destructive" loading={busy}>
{result && (!result.studentNotified || !result.guardianNotified) ? "Retry notices" : "Restrict the account"}
<Button type="submit" variant={action === "WITHDRAW" ? "destructive" : "primary"} loading={busy}>
{sendingLink ? (result ? "Send a replacement link" : "Send verification link") :
action === "CANCEL_DELETION" ? "Cancel scheduled deletion" :
result && (!result.studentNotified || !result.guardianNotified) ? "Retry notices" : "Restrict the account"}
</Button>
<FormErrorMessage id="guardian-withdrawal-error" message={error} />
</form>
{result && (
<div role="status" className="space-y-2 text-sm text-gray-900">
<p>The account is restricted.</p>
<p>Student notice {result.studentNotified ? "accepted for sending." : "needs a retry."}</p>
<p>Guardian notice {result.guardianNotified ? "accepted for sending." : "needs a retry."}</p>
<p>{action === "CANCEL_DELETION" ? "Deletion was cancelled. The account stays restricted." : "The account is restricted."}</p>
{sendingLink ? (
<p>{result.guardianNotified ? "The guardian link was accepted for sending." : "The link could not be sent. Send a replacement link."}</p>
) : (
<>
<p>Learner notice {result.studentNotified ? "accepted for sending." : "could not be sent."}</p>
<p>Guardian notice {result.guardianNotified ? "accepted for sending." : "could not be sent."}</p>
{action === "CANCEL_DELETION" && (!result.studentNotified || !result.guardianNotified) &&
<p>Follow up through the verified privacy case.</p>}
</>
)}
</div>
)}
</section>
Expand Down
Loading
Loading