DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(learner): complete guardian management flows
Bingxi Zhao (Frank)90351189a11f
diff --git a/deeptutor/multi_user/guardians.py b/deeptutor/multi_user/guardians.pyindex 4a327707f..4405e64cc 100644--- a/deeptutor/multi_user/guardians.py+++ b/deeptutor/multi_user/guardians.py@@ -15,7 +15,9 @@ from .identity import get_user_by_idfrom .paths import SYSTEM_ROOTGUARDIANS_FILE = SYSTEM_ROOT / "guardians.json"-GUARDIAN_PERMISSIONS = frozenset({"assign_materials", "view_reports", "reset_credentials"})+GUARDIAN_PERMISSIONS = frozenset(+ {"assign_materials", "manage_restrictions", "view_reports", "reset_credentials"}+)_GUARDIANS_WRITE_LOCK = threading.Lock()diff --git a/deeptutor/multi_user/router.py b/deeptutor/multi_user/router.pyindex ca4d59652..6d54f3a40 100644--- a/deeptutor/multi_user/router.py+++ b/deeptutor/multi_user/router.py@@ -3,9 +3,9 @@from __future__ import annotationsimport asyncio+from copy import deepcopyimport osfrom pathlib import Path-import secretsimport shutilfrom typing import Anyimport uuid@@ -25,12 +25,21 @@ from .audit import log_admin_action, log_guardian_actionfrom .book_permission import BookDefaultLevel, BookPermission, BookPermissionLevelfrom .context import get_current_userfrom .device_credentials import revoke_device_credentials_for_user-from .grants import load_grant, normalize_grant, save_grant, validate_grant+from .grants import (+ LEARNING_AGE_BANDS,+ LEARNING_SURFACES,+ learner_grant,+ load_grant,+ normalize_grant,+ save_grant,+ validate_grant,+)from .guardians import (GUARDIAN_PERMISSIONS,authorize_guardian,guardian_can_access,list_relationships,+ relationship_by_id,revoke_guardian,)from .identity import (@@ -86,6 +95,44 @@ class GuardianMaterialsPayload(BaseModel):return book_ids+class GuardianRestrictionsPayload(BaseModel):+ age_band: str+ allow_upload: StrictBool+ allowed_surfaces: list[str]+ extensions: list[str]++ @field_validator("age_band")+ @classmethod+ def age_band_valid(cls, value: str) -> str:+ if value not in LEARNING_AGE_BANDS:+ raise ValueError("Unknown learning age band")+ return value++ @field_validator("allowed_surfaces")+ @classmethod+ def surfaces_valid(cls, value: list[str]) -> list[str]:+ surfaces = list(dict.fromkeys(value))+ if not surfaces or not set(surfaces).issubset(LEARNING_SURFACES):+ raise ValueError("Unknown or empty learning surface")+ return surfaces++ @field_validator("extensions")+ @classmethod+ def extensions_valid(cls, value: list[str]) -> list[str]:+ extensions: list[str] = []+ for raw_id in value:+ extension_id = raw_id.strip()+ if not extension_id:+ raise ValueError("Reading extension ids cannot be empty")+ if extension_id not in extensions:+ extensions.append(extension_id)+ return extensions+++class GuardianCredentialResetPayload(BaseModel):+ new_password: str = Field(min_length=8, max_length=128)++class SkillInstallPayload(BaseModel):ref: strname: str | None = None@@ -253,13 +300,35 @@ def _relationship_view(def _require_guardian_access(current: object, learner_user_id: str, permission: str-) -> tuple[str, dict[str, Any], str]:- guardian_user_id = str(getattr(current, "user_id", "") or "")- _guardian_username, _guardian_record = _require_assignable_user(guardian_user_id)+) -> tuple[str, dict[str, Any], str, bool]:+ actor_user_id = str(getattr(current, "user_id", "") or "")learner_username, learner_record = _require_assignable_user(learner_user_id)- if not guardian_can_access(guardian_user_id, learner_user_id, permission):+ is_admin = str(getattr(current, "role", "") or "") == "admin"+ if is_admin:+ return learner_username, learner_record, actor_user_id, True+ _guardian_username, _guardian_record = _require_assignable_user(actor_user_id)+ if not guardian_can_access(actor_user_id, learner_user_id, permission):raise HTTPException(status_code=403, detail="Guardian authorization required")- return learner_username, learner_record, guardian_user_id+ return learner_username, learner_record, actor_user_id, False+++def _log_supervisor_action(+ action: str,+ *,+ actor_user_id: str,+ learner_user_id: str,+ is_admin: bool,+ summary: dict[str, Any] | None = None,+) -> None:+ if is_admin:+ log_admin_action(action, target_user_id=learner_user_id, summary=summary)+ return+ log_guardian_action(+ action,+ guardian_user_id=actor_user_id,+ learner_user_id=learner_user_id,+ summary=summary,+ )@router.get("/admin/resources")@@ -372,12 +441,37 @@ async def my_guardianships(return {"relationships": relationships}[email protected]("/me/guardianships/{relationship_id}")+async def revoke_my_guardianship(+ relationship_id: str,+ current: object = Depends(require_auth),+) -> dict[str, Any]:+ guardian_user_id = str(getattr(current, "user_id", "") or "")+ _require_assignable_user(guardian_user_id)+ relationship = relationship_by_id(relationship_id)+ if (+ relationship is None+ or relationship["guardian_user_id"] != guardian_user_id+ or relationship["revoked_at"] is not None+ ):+ raise HTTPException(status_code=404, detail="Active guardian relationship not found")+ revoked = revoke_guardian(relationship_id, revoked_by=guardian_user_id, reason="self_revoked")+ assert revoked is not None+ log_guardian_action(+ "guardian_self_revoke",+ guardian_user_id=guardian_user_id,+ learner_user_id=relationship["learner_user_id"],+ summary={"relationship_id": relationship_id},+ )+ return {"relationship": _relationship_view(revoked, _users_by_id()), "ok": True}++@router.get("/learners/{learner_user_id}/guardian-report")async def guardian_report(learner_user_id: str,current: object = Depends(require_auth),) -> dict[str, Any]:- learner_username, learner_record, guardian_user_id = _require_guardian_access(+ learner_username, learner_record, actor_user_id, is_admin = _require_guardian_access(current, learner_user_id, "view_reports")from .book_access import admin_book_catalog@@ -391,10 +485,11 @@ async def guardian_report(if permission.level_for(book["book_id"]) != "none"]grant = load_grant(learner_user_id)- log_guardian_action(+ _log_supervisor_action("guardian_report_view",- guardian_user_id=guardian_user_id,+ actor_user_id=actor_user_id,learner_user_id=learner_user_id,+ is_admin=is_admin,summary={"assigned_material_count": len(assigned_materials)},)return {@@ -414,55 +509,182 @@ async def guardian_report(}[email protected]("/learners/{learner_user_id}/materials")+async def guardian_material_catalog(+ learner_user_id: str,+ current: object = Depends(require_auth),+) -> dict[str, Any]:+ _learner_username, learner_record, actor_user_id, is_admin = _require_guardian_access(+ current, learner_user_id, "assign_materials"+ )+ from .book_access import admin_book_catalog+ from .book_permission import normalize_book_permission++ permission = normalize_book_permission(learner_record.get("book_permission"))+ materials = [+ {+ **book,+ "assigned": permission.level_for(book["book_id"]) != "none",+ "permission": permission.level_for(book["book_id"]),+ }+ for book in admin_book_catalog()+ ]+ _log_supervisor_action(+ "guardian_material_catalog_view",+ actor_user_id=actor_user_id,+ learner_user_id=learner_user_id,+ is_admin=is_admin,+ summary={"material_count": len(materials)},+ )+ return {"materials": materials}++@router.put("/learners/{learner_user_id}/materials")async def assign_guardian_materials(learner_user_id: str,payload: GuardianMaterialsPayload,current: object = Depends(require_auth),) -> dict[str, Any]:- learner_username, learner_record, guardian_user_id = _require_guardian_access(+ learner_username, learner_record, actor_user_id, is_admin = _require_guardian_access(current, learner_user_id, "assign_materials")- from .book_access import shared_book_exists+ from .book_access import admin_book_catalogfrom .book_permission import (BookPermission,normalize_book_permission,public_permission_dict,)- unknown = next(- (book_id for book_id in payload.book_ids if not shared_book_exists(book_id)),- None,- )+ catalog = admin_book_catalog()+ catalog_ids = {book["book_id"] for book in catalog}+ unknown = next((book_id for book_id in payload.book_ids if book_id not in catalog_ids), None)if unknown:raise HTTPException(status_code=400, detail=f"Unknown approved book id: {unknown}")# Guardians hand out the admin-approved catalogue as read-only material.# Admins remain the only source of edit/create capability.existing = normalize_book_permission(learner_record.get("book_permission"))+ selected_ids = set(payload.book_ids)permission = BookPermission(create=existing.create,default=existing.default,- books=tuple((book_id, "read") for book_id in payload.book_ids),+ books=tuple(+ (book["book_id"], "read" if book["book_id"] in selected_ids else "none")+ for book in catalog+ if (book["book_id"] in selected_ids) != (existing.default == "read")+ ),)if not set_book_permission(learner_username, permission):raise HTTPException(status_code=404, detail="User not found")result = public_permission_dict(permission)- log_guardian_action(+ _log_supervisor_action("guardian_material_assign",- guardian_user_id=guardian_user_id,+ actor_user_id=actor_user_id,learner_user_id=learner_user_id,+ is_admin=is_admin,summary={"book_ids": payload.book_ids, "read_only": True},)return {"book_permission": result}+def _guardian_restrictions(grant: dict[str, Any]) -> dict[str, Any]:+ policy = grant.get("learning_policy")+ if not isinstance(policy, dict):+ raise HTTPException(status_code=409, detail="Learner account has no learning policy")+ reading = policy.get("reading") if isinstance(policy.get("reading"), dict) else {}+ return {+ "age_band": policy.get("age_band"),+ "allow_upload": bool(reading.get("allow_upload", False)),+ "allowed_surfaces": list(policy.get("allowed_surfaces") or ["chat", "reading"]),+ "extensions": list(reading.get("extensions") or []),+ }+++def _restriction_grant(learner_user_id: str, learner_record: dict[str, Any]) -> dict[str, Any]:+ grant = load_grant(learner_user_id)+ if grant.get("learning_policy") is None and learner_record.get("preset") == "learner":+ return learner_grant(learner_user_id)+ return grant++[email protected]("/learners/{learner_user_id}/restrictions")+async def get_guardian_restrictions(+ learner_user_id: str,+ current: object = Depends(require_auth),+) -> dict[str, Any]:+ _learner_username, learner_record, actor_user_id, is_admin = _require_guardian_access(+ current, learner_user_id, "manage_restrictions"+ )+ restrictions = _guardian_restrictions(_restriction_grant(learner_user_id, learner_record))+ _log_supervisor_action(+ "guardian_restrictions_view",+ actor_user_id=actor_user_id,+ learner_user_id=learner_user_id,+ is_admin=is_admin,+ )+ return {+ "restrictions": restrictions,+ "available_extensions": [+ extension.manifest.model_dump() for extension in get_reading_extension_registry().all()+ ],+ }++[email protected]("/learners/{learner_user_id}/restrictions")+async def put_guardian_restrictions(+ learner_user_id: str,+ payload: GuardianRestrictionsPayload,+ current: object = Depends(require_auth),+) -> dict[str, Any]:+ _learner_username, learner_record, actor_user_id, is_admin = _require_guardian_access(+ current, learner_user_id, "manage_restrictions"+ )+ available_extensions = {+ extension.manifest.id for extension in get_reading_extension_registry().all()+ }+ unknown_extensions = sorted(set(payload.extensions) - available_extensions)+ if unknown_extensions:+ raise HTTPException(+ status_code=400,+ detail=f"Unknown reading extensions: {', '.join(unknown_extensions)}",+ )+ grant = deepcopy(_restriction_grant(learner_user_id, learner_record))+ policy = grant.get("learning_policy")+ if not isinstance(policy, dict):+ raise HTTPException(status_code=409, detail="Learner account has no learning policy")+ reading = policy.get("reading")+ if not isinstance(reading, dict):+ reading = {}+ policy["reading"] = reading+ policy["age_band"] = payload.age_band+ policy["allowed_surfaces"] = payload.allowed_surfaces+ reading["allow_upload"] = payload.allow_upload+ reading["extensions"] = payload.extensions+ try:+ grant = normalize_grant(learner_user_id, grant)+ validate_grant(grant)+ _validate_reading_policy(grant)+ grant = save_grant(learner_user_id, grant)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ restrictions = _guardian_restrictions(grant)+ _log_supervisor_action(+ "guardian_restrictions_set",+ actor_user_id=actor_user_id,+ learner_user_id=learner_user_id,+ is_admin=is_admin,+ summary=restrictions,+ )+ return {"restrictions": restrictions}++@router.post("/learners/{learner_user_id}/credentials/reset")async def reset_learner_credentials(learner_user_id: str,+ payload: GuardianCredentialResetPayload,current: object = Depends(require_auth),) -> dict[str, Any]:- learner_username, _learner_record, guardian_user_id = _require_guardian_access(+ learner_username, _learner_record, actor_user_id, is_admin = _require_guardian_access(current, learner_user_id, "reset_credentials")if POCKETBASE_ENABLED:@@ -470,26 +692,23 @@ async def reset_learner_credentials(status_code=400,detail="Guardian credential reset requires built-in local authentication.",)- temporary_password = secrets.token_urlsafe(18)- # Revoke device access first. If that write fails, the learner's existing- # password remains valid and no one-time replacement secret is lost in a- # failed HTTP response.revoked_devices = revoke_device_credentials_for_user(learner_user_id,- revoked_by=guardian_user_id,+ revoked_by=actor_user_id,)- if set_password(learner_username, hash_password(temporary_password)) is None:+ if set_password(learner_username, hash_password(payload.new_password)) is None:raise HTTPException(status_code=404, detail="User not found")- log_guardian_action(+ _log_supervisor_action("guardian_credential_reset",- guardian_user_id=guardian_user_id,+ actor_user_id=actor_user_id,learner_user_id=learner_user_id,+ is_admin=is_admin,summary={"credential_reset": True,"device_credentials_revoked": revoked_devices,},)- return {"temporary_password": temporary_password}+ return {"ok": True, "device_credentials_revoked": revoked_devices}@router.get("/users/{user_id}/grants")diff --git a/tests/multi_user/test_guardians.py b/tests/multi_user/test_guardians.pyindex 958b02239..d2ddfb166 100644--- a/tests/multi_user/test_guardians.py+++ b/tests/multi_user/test_guardians.py@@ -134,8 +134,27 @@ def test_admin_can_authorize_and_revoke_guardians(mu_isolated_root, monkeypatch)assert mine.status_code == 200assert mine.json()["relationships"][0]["id"] == relationship["id"]+ self_revoked = client.delete(+ f"/api/v1/multi-user/me/guardianships/{relationship['id']}",+ headers=_auth("guardian-token"),+ )+ assert self_revoked.status_code == 200+ assert self_revoked.json()["relationship"]["revocation_reason"] == "self_revoked"+ assert (+ client.get("/api/v1/multi-user/me/guardianships", headers=_auth("guardian-token")).json()[+ "relationships"+ ]+ == []+ )++ replacement = client.post(+ "/api/v1/multi-user/guardians",+ headers=_auth("root-token"),+ json={"guardian_user_id": guardian_id, "learner_user_id": learner_id},+ ).json()["relationship"]+revoked = client.delete(- f"/api/v1/multi-user/guardians/{relationship['id']}",+ f"/api/v1/multi-user/guardians/{replacement['id']}",headers=_auth("root-token"),)assert revoked.status_code == 200@@ -158,7 +177,7 @@ def test_admin_can_authorize_and_revoke_guardians(mu_isolated_root, monkeypatch)headers=_auth("root-token"),params={"include_revoked": True},).json()["relationships"]- assert len(history) == 1+ assert len(history) == 2def test_guardian_report_requires_active_relationship_and_is_audited(mu_isolated_root, monkeypatch):@@ -233,24 +252,92 @@ def test_guardian_can_assign_only_read_access_to_approved_books(mu_isolated_rootassert permission["create"] is Trueassert permission["default"] == "none"+ catalog = client.get(materials_url, headers=_auth("guardian-token"))+ assert catalog.status_code == 200+ assert {item["book_id"] for item in catalog.json()["materials"] if item["assigned"]} == {+ "bk_private",+ "bk_approved",+ }++ from deeptutor.multi_user.book_permission import BookPermission+ from deeptutor.multi_user.identity import set_book_permission++ assert set_book_permission("learner", BookPermission(create=True, default="read"))+ narrowed = client.put(+ materials_url,+ headers=_auth("guardian-token"),+ json={"book_ids": ["bk_approved"]},+ )+ assert narrowed.status_code == 200+ assert narrowed.json()["book_permission"]["default"] == "read"+ assert narrowed.json()["book_permission"]["books"] == {"bk_private": "none"}+report = client.get(f"/api/v1/multi-user/learners/{learner_id}/guardian-report",headers=_auth("guardian-token"),)assert report.status_code == 200assert {item["book_id"] for item in report.json()["assigned_materials"]} == {- "bk_private","bk_approved",}reset = client.post(f"/api/v1/multi-user/learners/{learner_id}/credentials/reset",headers=_auth("guardian-token"),+ json={"new_password": "replacement-password"},)assert reset.status_code == 403-def test_guardian_can_reset_local_credentials_once_and_audit_hides_secret(+def test_guardian_can_adjust_only_the_exposed_learning_restrictions(mu_isolated_root, monkeypatch):+ client, users = _client(mu_isolated_root, monkeypatch)+ learner_id = users["learner"]["id"]+ created = client.post(+ "/api/v1/multi-user/guardians",+ headers=_auth("root-token"),+ json={+ "guardian_user_id": users["guardian"]["id"],+ "learner_user_id": learner_id,+ "permissions": ["manage_restrictions"],+ },+ )+ assert created.status_code == 201++ url = f"/api/v1/multi-user/learners/{learner_id}/restrictions"+ assert client.get(url, headers=_auth("stranger-token")).status_code == 403+ before = client.get(url, headers=_auth("guardian-token"))+ assert before.status_code == 200+ assert before.json()["restrictions"]["age_band"] == "9-12"++ changed = client.put(+ url,+ headers=_auth("guardian-token"),+ json={+ "age_band": "13-15",+ "allow_upload": True,+ "allowed_surfaces": ["reading"],+ "extensions": [],+ },+ )+ assert changed.status_code == 200+ assert changed.json()["restrictions"] == {+ "age_band": "13-15",+ "allow_upload": True,+ "allowed_surfaces": ["reading"],+ "extensions": [],+ }++ from deeptutor.multi_user.grants import load_grant++ grant = load_grant(learner_id)+ assert grant["learning_policy"]["allowed_capabilities"] == [+ "chat",+ "immersive_reading",+ ]+ assert grant["learning_policy"]["reading"]["material_ids"] == []+++def test_guardian_can_reset_local_credentials_without_returning_or_auditing_secret(mu_isolated_root, monkeypatch):client, users = _client(mu_isolated_root, monkeypatch)@@ -278,6 +365,7 @@ def test_guardian_can_reset_local_credentials_once_and_audit_hides_secret(unsupported = client.post(f"/api/v1/multi-user/learners/{learner_id}/credentials/reset",headers=_auth("guardian-token"),+ json={"new_password": "replacement-password"},)assert unsupported.status_code == 400monkeypatch.setattr(multi_user_router, "POCKETBASE_ENABLED", False)@@ -296,20 +384,32 @@ def test_guardian_can_reset_local_credentials_once_and_audit_hides_secret(reset = client.post(f"/api/v1/multi-user/learners/{learner_id}/credentials/reset",headers=_auth("guardian-token"),+ json={"new_password": "replacement-password"},)assert reset.status_code == 200- temporary_password = reset.json()["temporary_password"]- assert len(temporary_password) >= 16+ assert reset.json()["ok"] is True+ assert "temporary_password" not in reset.json()+ assert "new_password" not in reset.json()from deeptutor.multi_user.identity import load_userslearner_hash = load_users()["learner"]["hash"]assert verify_password("learner-password", learner_hash) is False- assert verify_password(temporary_password, learner_hash) is True+ assert verify_password("replacement-password", learner_hash) is Trueassert validate_device_token(learner_id, device["id"], session_nonce) is Falseaudit_path = mu_isolated_root / "data" / "system" / "audit" / "usage.jsonl"- assert temporary_password not in audit_path.read_text()+ assert "replacement-password" not in audit_path.read_text()++ admin_reset = client.post(+ f"/api/v1/multi-user/learners/{learner_id}/credentials/reset",+ headers=_auth("root-token"),+ json={"new_password": "admin-replacement-password"},+ )+ assert admin_reset.status_code == 200+ learner_hash = load_users()["learner"]["hash"]+ assert verify_password("admin-replacement-password", learner_hash) is True+ assert "admin-replacement-password" not in audit_path.read_text()def test_user_deletion_revokes_related_guardian_records(mu_isolated_root, monkeypatch):diff --git a/web/app/(admin)/admin/users/page.tsx b/web/app/(admin)/admin/users/page.tsxindex d151c5e7c..edfd30b5b 100644--- a/web/app/(admin)/admin/users/page.tsx+++ b/web/app/(admin)/admin/users/page.tsx@@ -15,6 +15,7 @@ import {import { GrantEditor } from "@/features/multi-user/components/GrantEditor";import { BookPermissionEditor } from "@/features/multi-user/components/BookPermissionEditor";import { LearnerProfileEditor } from "@/features/multi-user/components/LearnerProfileEditor";+import { GuardianRelationshipsEditor } from "@/features/multi-user/components/GuardianRelationshipsEditor";import { UserAvatar } from "@/components/UserAvatar";import { ConfirmDialog } from "@/components/ui/ConfirmDialog";import { filterUsersByQuery } from "@/lib/admin-users";@@ -472,7 +473,14 @@ export default function AdminUsersPage() {/><BookPermissionEditor userId={user.id} />{user.preset === "learner" && (- <LearnerProfileEditor username={user.username} />+ <>+ <GuardianRelationshipsEditor+ learnerId={user.id}+ learnerUsername={user.username}+ users={users}+ />+ <LearnerProfileEditor username={user.username} />+ </>)}</td></tr>diff --git a/web/app/(utility)/settings/guardian/page.tsx b/web/app/(utility)/settings/guardian/page.tsxindex 0c39952ed..e07b271d8 100644--- a/web/app/(utility)/settings/guardian/page.tsx+++ b/web/app/(utility)/settings/guardian/page.tsx@@ -1,24 +1,44 @@"use client";import { useEffect, useState } from "react";-import { Copy, KeyRound, Library } from "lucide-react";+import {+ KeyRound,+ Library,+ Save,+ ShieldOff,+ SlidersHorizontal,+} from "lucide-react";import { useTranslation } from "react-i18next";import { ConfirmDialog } from "@/components/ui/ConfirmDialog";import {- clearGuardianMaterials,+ getGuardianMaterials,getGuardianReport,+ getGuardianRestrictions,listGuardianRelationships,resetLearnerCredentials,+ revokeMyGuardianRelationship,+ saveGuardianMaterials,+ saveGuardianRestrictions,+ type GuardianExtension,+ type GuardianMaterial,type GuardianRelationship,type GuardianReport,+ type GuardianRestrictions,} from "@/lib/guardian-api";-type BusyAction = "report" | "materials" | "credentials" | null;-type ConfirmAction = "materials" | "credentials" | null;+type BusyAction =+ | "loading"+ | "materials"+ | "restrictions"+ | "credentials"+ | "revoke"+ | null;+type ConfirmAction = "credentials" | "revoke" | null;const permissionKeys: Record<string, string> = {assign_materials: "Manage materials",+ manage_restrictions: "Manage restrictions",reset_credentials: "Reset credentials",view_reports: "View reports",};@@ -29,11 +49,15 @@ export default function GuardianSettingsPage() {const [selectedRelationship, setSelectedRelationship] =useState<GuardianRelationship | null>(null);const [report, setReport] = useState<GuardianReport | null>(null);+ const [materials, setMaterials] = useState<GuardianMaterial[]>([]);+ const [selectedMaterialIds, setSelectedMaterialIds] = useState<string[]>([]);+ const [restrictions, setRestrictions] =+ useState<GuardianRestrictions | null>(null);+ const [extensions, setExtensions] = useState<GuardianExtension[]>([]);+ const [newPassword, setNewPassword] = useState("");const [loading, setLoading] = useState(true);const [busy, setBusy] = useState<BusyAction>(null);const [confirmAction, setConfirmAction] = useState<ConfirmAction>(null);- const [temporaryPassword, setTemporaryPassword] = useState<string | null>(null);- const [copied, setCopied] = useState(false);const [message, setMessage] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);@@ -60,14 +84,84 @@ export default function GuardianSettingsPage() {const selectLearner = async (relationship: GuardianRelationship) => {setSelectedRelationship(relationship);setReport(null);- setTemporaryPassword(null);- setCopied(false);+ setMaterials([]);+ setSelectedMaterialIds([]);+ setRestrictions(null);+ setExtensions([]);+ setNewPassword("");setMessage(null);setError(null);- if (!relationship.permissions.includes("view_reports")) return;- setBusy("report");+ setBusy("loading");+ try {+ const [nextReport, nextMaterials, nextRestrictions] = await Promise.all([+ relationship.permissions.includes("view_reports")+ ? getGuardianReport(relationship.learner_user_id)+ : Promise.resolve(null),+ relationship.permissions.includes("assign_materials")+ ? getGuardianMaterials(relationship.learner_user_id)+ : Promise.resolve(null),+ relationship.permissions.includes("manage_restrictions")+ ? getGuardianRestrictions(relationship.learner_user_id)+ : Promise.resolve(null),+ ]);+ setReport(nextReport);+ if (nextMaterials) {+ setMaterials(nextMaterials);+ setSelectedMaterialIds(+ nextMaterials.filter((item) => item.assigned).map((item) => item.book_id),+ );+ }+ if (nextRestrictions) {+ setRestrictions(nextRestrictions.restrictions);+ setExtensions(nextRestrictions.available_extensions);+ }+ } catch (reason) {+ setError((reason as Error).message);+ } finally {+ setBusy(null);+ }+ };++ const saveMaterials = async () => {+ if (!selectedRelationship || !can("assign_materials")) return;+ setBusy("materials");+ setError(null);+ setMessage(null);+ try {+ await saveGuardianMaterials(+ selectedRelationship.learner_user_id,+ selectedMaterialIds,+ );+ const nextMaterials = await getGuardianMaterials(+ selectedRelationship.learner_user_id,+ );+ setMaterials(nextMaterials);+ if (can("view_reports")) {+ setReport(await getGuardianReport(selectedRelationship.learner_user_id));+ }+ setMessage(t("Approved materials saved."));+ } catch (reason) {+ setError((reason as Error).message);+ } finally {+ setBusy(null);+ }+ };++ const saveRestrictions = async () => {+ if (!selectedRelationship || !restrictions || !can("manage_restrictions")) {+ return;+ }+ setBusy("restrictions");+ setError(null);+ setMessage(null);try {- setReport(await getGuardianReport(relationship.learner_user_id));+ setRestrictions(+ await saveGuardianRestrictions(+ selectedRelationship.learner_user_id,+ restrictions,+ ),+ );+ setMessage(t("Learning restrictions saved."));} catch (reason) {setError((reason as Error).message);} finally {@@ -76,16 +170,23 @@ export default function GuardianSettingsPage() {};const resetCredentials = async () => {- if (!selectedRelationship || !can("reset_credentials")) return;+ if (+ !selectedRelationship ||+ !can("reset_credentials") ||+ newPassword.length < 8+ ) {+ return;+ }setConfirmAction(null);setBusy("credentials");setError(null);setMessage(null);- setTemporaryPassword(null);try {- setTemporaryPassword(- await resetLearnerCredentials(selectedRelationship.learner_user_id),+ await resetLearnerCredentials(+ selectedRelationship.learner_user_id,+ newPassword,);+ setNewPassword("");setMessage(t("Learner credentials were reset."));} catch (reason) {setError((reason as Error).message);@@ -94,18 +195,20 @@ export default function GuardianSettingsPage() {}};- const clearMaterials = async () => {- if (!selectedRelationship || !can("assign_materials")) return;+ const revokeRelationship = async () => {+ if (!selectedRelationship) return;setConfirmAction(null);- setBusy("materials");+ setBusy("revoke");setError(null);setMessage(null);try {- await clearGuardianMaterials(selectedRelationship.learner_user_id);- if (can("view_reports")) {- setReport(await getGuardianReport(selectedRelationship.learner_user_id));- }- setMessage(t("Approved materials removed."));+ await revokeMyGuardianRelationship(selectedRelationship.id);+ setRelationships((current) =>+ current.filter((item) => item.id !== selectedRelationship.id),+ );+ setSelectedRelationship(null);+ setReport(null);+ setMessage(t("Guardian access revoked."));} catch (reason) {setError((reason as Error).message);} finally {@@ -164,17 +267,28 @@ export default function GuardianSettingsPage() {)}{selectedRelationship && (- <section className="mt-8 border-t border-[var(--border)] pt-6">- <h2 className="font-medium">- {report?.learner.username ?? selectedRelationship.learner_username}- </h2>+ <section className="mt-8 space-y-6 border-t border-[var(--border)] pt-6">+ <div className="flex items-start justify-between gap-3">+ <h2 className="font-medium">+ {report?.learner.username ?? selectedRelationship.learner_username}+ </h2>+ <button+ type="button"+ onClick={() => setConfirmAction("revoke")}+ disabled={busy !== null}+ className="inline-flex items-center gap-1.5 rounded-md border border-red-500/40 px-3 py-1.5 text-xs text-red-600 disabled:opacity-50"+ >+ <ShieldOff className="h-3.5 w-3.5" />+ {t("Revoke access")}+ </button>+ </div>- {busy === "report" ? (- <p className="mt-3 text-sm text-[var(--muted-foreground)]">- {t("Loading learner report…")}+ {busy === "loading" ? (+ <p className="text-sm text-[var(--muted-foreground)]">+ {t("Loading learner details…")}</p>) : can("view_reports") && report ? (- <div className="mt-4 grid gap-3 sm:grid-cols-2">+ <div className="grid gap-3 sm:grid-cols-2"><div className="rounded-lg border border-[var(--border)] p-4"><Library className="mb-2 h-4 w-4 text-[var(--muted-foreground)]" /><div className="text-xs text-[var(--muted-foreground)]">@@ -196,66 +310,180 @@ export default function GuardianSettingsPage() {</div></div>) : !can("view_reports") ? (- <p className="mt-3 text-sm text-[var(--muted-foreground)]">+ <p className="text-sm text-[var(--muted-foreground)]">{t("You are not authorized to view this learner report.")}</p>) : null}- <div className="mt-5 flex flex-wrap gap-3">- {can("assign_materials") && (- <button- type="button"- onClick={() => setConfirmAction("materials")}- disabled={- busy !== null ||- (report !== null && report.assigned_materials.length === 0)- }- className="rounded-md border border-[var(--border)] px-3 py-2 text-sm disabled:opacity-50"- >- {busy === "materials"- ? t("Removing…")- : t("Remove approved materials")}- </button>- )}- {can("reset_credentials") && (+ {can("assign_materials") && (+ <div className="rounded-lg border border-[var(--border)] p-4">+ <div className="mb-3 flex items-center justify-between gap-3">+ <h3 className="text-sm font-medium">{t("Approved materials")}</h3>+ <button+ type="button"+ onClick={() => void saveMaterials()}+ disabled={busy !== null}+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1.5 text-xs text-[var(--primary-foreground)] disabled:opacity-50"+ >+ <Save className="h-3.5 w-3.5" />+ {busy === "materials" ? t("Saving…") : t("Save materials")}+ </button>+ </div>+ {materials.length === 0 ? (+ <p className="text-xs text-[var(--muted-foreground)]">+ {t("No approved materials are available.")}+ </p>+ ) : (+ <div className="grid gap-2 sm:grid-cols-2">+ {materials.map((material) => (+ <label+ key={material.book_id}+ className="flex items-center gap-2 rounded-md border border-[var(--border)] px-3 py-2 text-xs"+ >+ <input+ type="checkbox"+ checked={selectedMaterialIds.includes(material.book_id)}+ disabled={busy !== null}+ onChange={() =>+ setSelectedMaterialIds((current) =>+ current.includes(material.book_id)+ ? current.filter((id) => id !== material.book_id)+ : [...current, material.book_id],+ )+ }+ />+ <span className="truncate">+ {material.title || material.book_id}+ </span>+ </label>+ ))}+ </div>+ )}+ </div>+ )}++ {can("manage_restrictions") && restrictions && (+ <div className="rounded-lg border border-[var(--border)] p-4">+ <div className="mb-3 flex items-center justify-between gap-3">+ <h3 className="inline-flex items-center gap-2 text-sm font-medium">+ <SlidersHorizontal className="h-4 w-4" />+ {t("Learning restrictions")}+ </h3>+ <button+ type="button"+ onClick={() => void saveRestrictions()}+ disabled={busy !== null}+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1.5 text-xs text-[var(--primary-foreground)] disabled:opacity-50"+ >+ <Save className="h-3.5 w-3.5" />+ {busy === "restrictions"+ ? t("Saving…")+ : t("Save restrictions")}+ </button>+ </div>+ <div className="grid gap-3 sm:grid-cols-2">+ <label className="text-xs">+ <span className="mb-1 block text-[var(--muted-foreground)]">+ {t("Age band")}+ </span>+ <select+ value={restrictions.age_band}+ disabled={busy !== null}+ onChange={(event) =>+ setRestrictions((current) =>+ current+ ? {+ ...current,+ age_band: event.target+ .value as GuardianRestrictions["age_band"],+ }+ : current,+ )+ }+ className="h-9 w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-2"+ >+ {(["6-8", "9-12", "13-15"] as const).map((band) => (+ <option key={band} value={band}>+ {band}+ </option>+ ))}+ </select>+ </label>+ <label className="flex items-center gap-2 self-end rounded-md border border-[var(--border)] px-3 py-2 text-xs">+ <input+ type="checkbox"+ checked={restrictions.allow_upload}+ disabled={busy !== null}+ onChange={(event) =>+ setRestrictions((current) =>+ current+ ? { ...current, allow_upload: event.target.checked }+ : current,+ )+ }+ />+ {t("Allow learner uploads")}+ </label>+ </div>+ <div className="mt-3 grid gap-2 sm:grid-cols-2">+ {extensions.map((extension) => (+ <label+ key={extension.id}+ className="flex items-center gap-2 rounded-md border border-[var(--border)] px-3 py-2 text-xs"+ >+ <input+ type="checkbox"+ checked={restrictions.extensions.includes(extension.id)}+ disabled={busy !== null}+ onChange={() =>+ setRestrictions((current) =>+ current+ ? {+ ...current,+ extensions: current.extensions.includes(extension.id)+ ? current.extensions.filter(+ (id) => id !== extension.id,+ )+ : [...current.extensions, extension.id],+ }+ : current,+ )+ }+ />+ <span>{extension.name}</span>+ </label>+ ))}+ </div>+ </div>+ )}++ {can("reset_credentials") && (+ <div className="rounded-lg border border-[var(--border)] p-4">+ <label className="text-xs">+ <span className="mb-1 block text-[var(--muted-foreground)]">+ {t("New learner password")}+ </span>+ <input+ type="password"+ value={newPassword}+ minLength={8}+ autoComplete="new-password"+ disabled={busy !== null}+ onChange={(event) => setNewPassword(event.target.value)}+ className="h-9 w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-3"+ />+ </label><buttontype="button"onClick={() => setConfirmAction("credentials")}- disabled={busy !== null}- className="inline-flex items-center gap-2 rounded-md border border-red-500/40 px-3 py-2 text-sm text-red-600 disabled:opacity-50"+ disabled={busy !== null || newPassword.length < 8}+ className="mt-3 inline-flex items-center gap-2 rounded-md border border-red-500/40 px-3 py-2 text-sm text-red-600 disabled:opacity-50"><KeyRound className="h-4 w-4" />{busy === "credentials"? t("Resetting…"): t("Reset learner credentials")}</button>- )}- </div>-- {temporaryPassword && (- <div className="mt-5 rounded-lg border border-amber-500/40 bg-amber-500/10 p-4">- <div className="text-xs font-medium text-amber-800 dark:text-amber-300">- {t("Temporary password")}- </div>- <div className="mt-2 flex items-center gap-2">- <code className="min-w-0 flex-1 break-all rounded bg-[var(--background)] px-3 py-2 text-sm">- {temporaryPassword}- </code>- <button- type="button"- onClick={() => {- void navigator.clipboard.writeText(temporaryPassword);- setCopied(true);- }}- className="inline-flex items-center gap-1 rounded-md border border-[var(--border)] px-3 py-2 text-sm"- >- <Copy className="h-4 w-4" />- {copied ? t("Copied") : t("Copy")}- </button>- </div>- <p className="mt-2 text-xs text-amber-800 dark:text-amber-300">- {t("Copy this password now. It will not be shown again.")}- </p></div>)}</section>@@ -266,26 +494,26 @@ export default function GuardianSettingsPage() {title={confirmAction === "credentials"? t("Reset learner credentials")- : t("Remove approved materials")+ : t("Revoke guardian access")}confirmLabel={confirmAction === "credentials"? t("Reset credentials")- : t("Remove materials")+ : t("Revoke access")}tone="danger"busy={busy !== null}onCancel={() => setConfirmAction(null)}onConfirm={() => {if (confirmAction === "credentials") void resetCredentials();- if (confirmAction === "materials") void clearMaterials();+ if (confirmAction === "revoke") void revokeRelationship();}}>{confirmAction === "credentials"? t("This changes the learner password and revokes every learner device credential.",)- : t("This removes every approved material from the learner account.")}+ : t("This immediately removes your access to this learner account.")}</ConfirmDialog></main>);diff --git a/web/features/multi-user/components/GuardianRelationshipsEditor.tsx b/web/features/multi-user/components/GuardianRelationshipsEditor.tsxnew file mode 100644index 000000000..01966a611--- /dev/null+++ b/web/features/multi-user/components/GuardianRelationshipsEditor.tsx@@ -0,0 +1,329 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import { KeyRound, ShieldCheck, ShieldOff, UserPlus } from "lucide-react";+import { useTranslation } from "react-i18next";++import { ConfirmDialog } from "@/components/ui/ConfirmDialog";+import type { UserRecord } from "@/lib/admin-api";+import {+ authorizeGuardianRelationship,+ getGuardianReport,+ listAdminGuardianRelationships,+ resetLearnerCredentials,+ revokeGuardianRelationship,+ type GuardianRelationship,+ type GuardianReport,+} from "@/lib/guardian-api";++const PERMISSIONS = [+ "assign_materials",+ "manage_restrictions",+ "view_reports",+ "reset_credentials",+] as const;++const permissionLabels: Record<(typeof PERMISSIONS)[number], string> = {+ assign_materials: "Manage materials",+ manage_restrictions: "Manage restrictions",+ view_reports: "View reports",+ reset_credentials: "Reset credentials",+};++export function GuardianRelationshipsEditor({+ learnerId,+ learnerUsername,+ users,+}: {+ learnerId: string;+ learnerUsername: string;+ users: UserRecord[];+}) {+ const { t } = useTranslation();+ const [relationships, setRelationships] = useState<GuardianRelationship[]>([]);+ const [report, setReport] = useState<GuardianReport | null>(null);+ const [guardianId, setGuardianId] = useState("");+ const [permissions, setPermissions] = useState<string[]>([...PERMISSIONS]);+ const [newPassword, setNewPassword] = useState("");+ const [loading, setLoading] = useState(true);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState("");+ const [message, setMessage] = useState("");+ const [confirm, setConfirm] = useState<+ { kind: "revoke"; relationship: GuardianRelationship } | { kind: "reset" } | null+ >(null);++ useEffect(() => {+ let cancelled = false;+ Promise.all([+ listAdminGuardianRelationships(),+ getGuardianReport(learnerId),+ ])+ .then(([allRelationships, nextReport]) => {+ if (cancelled) return;+ setRelationships(+ allRelationships.filter(+ (relationship) => relationship.learner_user_id === learnerId,+ ),+ );+ setReport(nextReport);+ })+ .catch((reason: unknown) => {+ if (!cancelled) setError((reason as Error).message);+ })+ .finally(() => {+ if (!cancelled) setLoading(false);+ });+ return () => {+ cancelled = true;+ };+ }, [learnerId]);++ const activeGuardianIds = useMemo(+ () => new Set(relationships.map((item) => item.guardian_user_id)),+ [relationships],+ );+ const candidates = users.filter(+ (user) =>+ user.role === "user" &&+ user.id !== learnerId &&+ user.preset !== "learner" &&+ !activeGuardianIds.has(user.id),+ );++ const addRelationship = async () => {+ if (!guardianId || permissions.length === 0) return;+ setBusy(true);+ setError("");+ setMessage("");+ try {+ const relationship = await authorizeGuardianRelationship(+ guardianId,+ learnerId,+ permissions,+ );+ setRelationships((current) => [...current, relationship]);+ setGuardianId("");+ setMessage(t("Guardian relationship added."));+ } catch (reason) {+ setError((reason as Error).message);+ } finally {+ setBusy(false);+ }+ };++ const revoke = async (relationship: GuardianRelationship) => {+ setConfirm(null);+ setBusy(true);+ setError("");+ setMessage("");+ try {+ await revokeGuardianRelationship(relationship.id);+ setRelationships((current) =>+ current.filter((item) => item.id !== relationship.id),+ );+ setMessage(t("Guardian access revoked."));+ } catch (reason) {+ setError((reason as Error).message);+ } finally {+ setBusy(false);+ }+ };++ const resetCredentials = async () => {+ if (newPassword.length < 8) return;+ setConfirm(null);+ setBusy(true);+ setError("");+ setMessage("");+ try {+ await resetLearnerCredentials(learnerId, newPassword);+ setNewPassword("");+ setMessage(t("Learner credentials were reset."));+ } catch (reason) {+ setError((reason as Error).message);+ } finally {+ setBusy(false);+ }+ };++ return (+ <section className="border-t border-[var(--border)] bg-[var(--background)]/40 px-5 py-4">+ <div className="mb-3">+ <h3 className="flex items-center gap-2 text-sm font-semibold text-[var(--foreground)]">+ <ShieldCheck className="h-4 w-4" /> {t("Guardian relationships")}+ </h3>+ <p className="mt-1 text-xs text-[var(--muted-foreground)]">+ {t("Authorize ordinary accounts to supervise {{username}}.", {+ username: learnerUsername,+ })}+ </p>+ </div>++ {loading ? (+ <p className="text-xs text-[var(--muted-foreground)]">+ {t("Loading guardian relationships…")}+ </p>+ ) : (+ <>+ <div className="mb-3 grid gap-2">+ {relationships.length === 0 ? (+ <p className="rounded-lg border border-dashed border-[var(--border)] p-3 text-xs text-[var(--muted-foreground)]">+ {t("No active guardian relationships.")}+ </p>+ ) : (+ relationships.map((relationship) => (+ <div+ key={relationship.id}+ className="flex items-center justify-between gap-3 rounded-lg border border-[var(--border)] px-3 py-2"+ >+ <div className="min-w-0">+ <div className="truncate text-xs font-medium">+ {relationship.guardian_username}+ </div>+ <div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">+ {relationship.permissions+ .map((permission) =>+ t(+ permissionLabels[+ permission as (typeof PERMISSIONS)[number]+ ] ?? permission,+ ),+ )+ .join(" · ")}+ </div>+ </div>+ <button+ type="button"+ disabled={busy}+ onClick={() => setConfirm({ kind: "revoke", relationship })}+ className="rounded-md p-1.5 text-red-600 hover:bg-red-500/10 disabled:opacity-40"+ aria-label={t("Revoke access")}+ >+ <ShieldOff className="h-4 w-4" />+ </button>+ </div>+ ))+ )}+ </div>++ <div className="rounded-lg border border-[var(--border)] p-3">+ <div className="grid gap-2 sm:grid-cols-[1fr_auto]">+ <select+ value={guardianId}+ disabled={busy || candidates.length === 0}+ onChange={(event) => setGuardianId(event.target.value)}+ className="h-9 rounded-md border border-[var(--border)] bg-[var(--card)] px-2 text-xs"+ >+ <option value="">{t("Select a guardian")}</option>+ {candidates.map((user) => (+ <option key={user.id} value={user.id}>+ {user.username}+ </option>+ ))}+ </select>+ <button+ type="button"+ disabled={busy || !guardianId || permissions.length === 0}+ onClick={() => void addRelationship()}+ className="inline-flex h-9 items-center justify-center gap-1.5 rounded-md bg-[var(--primary)] px-3 text-xs text-[var(--primary-foreground)] disabled:opacity-40"+ >+ <UserPlus className="h-3.5 w-3.5" /> {t("Authorize guardian")}+ </button>+ </div>+ <div className="mt-2 grid gap-2 sm:grid-cols-2">+ {PERMISSIONS.map((permission) => (+ <label+ key={permission}+ className="flex items-center gap-2 text-[11px] text-[var(--muted-foreground)]"+ >+ <input+ type="checkbox"+ checked={permissions.includes(permission)}+ disabled={busy}+ onChange={() =>+ setPermissions((current) =>+ current.includes(permission)+ ? current.filter((item) => item !== permission)+ : [...current, permission],+ )+ }+ />+ {t(permissionLabels[permission])}+ </label>+ ))}+ </div>+ </div>++ {report && (+ <p className="mt-3 text-xs text-[var(--muted-foreground)]">+ {t("{{materials}} approved materials · {{resources}} enabled resources", {+ materials: report.assigned_materials.length,+ resources:+ report.grant_summary.model_count ++ report.grant_summary.knowledge_base_count ++ report.grant_summary.skill_count,+ })}+ </p>+ )}++ <div className="mt-3 rounded-lg border border-[var(--border)] p-3">+ <label className="text-xs">+ <span className="mb-1 block text-[var(--muted-foreground)]">+ {t("New learner password")}+ </span>+ <input+ type="password"+ value={newPassword}+ minLength={8}+ autoComplete="new-password"+ disabled={busy}+ onChange={(event) => setNewPassword(event.target.value)}+ className="h-9 w-full rounded-md border border-[var(--border)] bg-[var(--card)] px-3"+ />+ </label>+ <button+ type="button"+ disabled={busy || newPassword.length < 8}+ onClick={() => setConfirm({ kind: "reset" })}+ className="mt-2 inline-flex items-center gap-1.5 rounded-md border border-red-500/40 px-3 py-1.5 text-xs text-red-600 disabled:opacity-40"+ >+ <KeyRound className="h-3.5 w-3.5" />+ {t("Reset learner credentials")}+ </button>+ </div>+ </>+ )}++ {error ? <p className="mt-3 text-xs text-red-600">{error}</p> : null}+ {message ? (+ <p className="mt-3 text-xs text-emerald-600">{message}</p>+ ) : null}++ <ConfirmDialog+ open={confirm !== null}+ title={+ confirm?.kind === "reset"+ ? t("Reset learner credentials")+ : t("Revoke guardian access")+ }+ confirmLabel={+ confirm?.kind === "reset" ? t("Reset credentials") : t("Revoke access")+ }+ tone="danger"+ busy={busy}+ onCancel={() => setConfirm(null)}+ onConfirm={() => {+ if (confirm?.kind === "reset") void resetCredentials();+ if (confirm?.kind === "revoke") void revoke(confirm.relationship);+ }}+ >+ {confirm?.kind === "reset"+ ? t(+ "This changes the learner password and revokes every learner device credential.",+ )+ : t("This immediately removes access to this learner account.")}+ </ConfirmDialog>+ </section>+ );+}diff --git a/web/lib/guardian-api.ts b/web/lib/guardian-api.tsindex 6f4ebc76f..6cb0fc3a3 100644--- a/web/lib/guardian-api.ts+++ b/web/lib/guardian-api.ts@@ -2,9 +2,12 @@ import { apiFetch, apiUrl } from "@/lib/api";export interface GuardianRelationship {id: string;+ guardian_user_id: string;+ guardian_username: string;learner_user_id: string;learner_username: string;permissions: string[];+ revoked_at?: string | null;}export interface GuardianReport {@@ -21,6 +24,26 @@ export interface GuardianReport {};}+export interface GuardianMaterial {+ book_id: string;+ title?: string;+ assigned: boolean;+ permission: string;+}++export interface GuardianRestrictions {+ age_band: "6-8" | "9-12" | "13-15";+ allow_upload: boolean;+ allowed_surfaces: Array<"chat" | "reading">;+ extensions: string[];+}++export interface GuardianExtension {+ id: string;+ name: string;+ version: string;+}+function extractDetail(value: unknown): string | null {if (typeof value !== "object" || value === null || !("detail" in value)) {return null;@@ -43,27 +66,116 @@ export async function listGuardianRelationships(): Promise<GuardianRelationship[return data.relationships;}+export async function listAdminGuardianRelationships(): Promise<+ GuardianRelationship[]+> {+ const data = await request<{ relationships: GuardianRelationship[] }>(+ "/api/v1/multi-user/guardians",+ );+ return data.relationships;+}++export async function authorizeGuardianRelationship(+ guardianId: string,+ learnerId: string,+ permissions: string[],+): Promise<GuardianRelationship> {+ const data = await request<{ relationship: GuardianRelationship }>(+ "/api/v1/multi-user/guardians",+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ guardian_user_id: guardianId,+ learner_user_id: learnerId,+ permissions,+ }),+ },+ );+ return data.relationship;+}++export async function revokeGuardianRelationship(+ relationshipId: string,+): Promise<void> {+ await request(+ `/api/v1/multi-user/guardians/${encodeURIComponent(relationshipId)}`,+ { method: "DELETE" },+ );+}++export async function revokeMyGuardianRelationship(+ relationshipId: string,+): Promise<void> {+ await request(+ `/api/v1/multi-user/me/guardianships/${encodeURIComponent(relationshipId)}`,+ { method: "DELETE" },+ );+}+export function getGuardianReport(learnerId: string): Promise<GuardianReport> {return request<GuardianReport>(`/api/v1/multi-user/learners/${encodeURIComponent(learnerId)}/guardian-report`,);}-export async function resetLearnerCredentials(learnerId: string): Promise<string> {- const data = await request<{ temporary_password: string }>(+export async function resetLearnerCredentials(+ learnerId: string,+ newPassword: string,+): Promise<void> {+ await request(`/api/v1/multi-user/learners/${encodeURIComponent(learnerId)}/credentials/reset`,- { method: "POST" },+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ new_password: newPassword }),+ },+ );+}++export async function getGuardianMaterials(+ learnerId: string,+): Promise<GuardianMaterial[]> {+ const data = await request<{ materials: GuardianMaterial[] }>(+ `/api/v1/multi-user/learners/${encodeURIComponent(learnerId)}/materials`,);- return data.temporary_password;+ return data.materials;}-export async function clearGuardianMaterials(learnerId: string): Promise<void> {+export async function saveGuardianMaterials(+ learnerId: string,+ bookIds: string[],+): Promise<void> {await request(`/api/v1/multi-user/learners/${encodeURIComponent(learnerId)}/materials`,{method: "PUT",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ book_ids: [] }),+ body: JSON.stringify({ book_ids: bookIds }),+ },+ );+}++export async function getGuardianRestrictions(learnerId: string): Promise<{+ restrictions: GuardianRestrictions;+ available_extensions: GuardianExtension[];+}> {+ return request(+ `/api/v1/multi-user/learners/${encodeURIComponent(learnerId)}/restrictions`,+ );+}++export async function saveGuardianRestrictions(+ learnerId: string,+ restrictions: GuardianRestrictions,+): Promise<GuardianRestrictions> {+ const data = await request<{ restrictions: GuardianRestrictions }>(+ `/api/v1/multi-user/learners/${encodeURIComponent(learnerId)}/restrictions`,+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(restrictions),},);+ return data.restrictions;}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex adbe2d688..4a6338616 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -213,8 +213,29 @@"Enabled learning resources": "Enabled learning resources","You are not authorized to view this learner report.": "You are not authorized to view this learner report.","Manage materials": "Manage materials",+ "Manage restrictions": "Manage restrictions","View reports": "View reports","Reset credentials": "Reset credentials",+ "Loading learner details…": "Loading learner details…",+ "Revoke access": "Revoke access",+ "Revoke guardian access": "Revoke guardian access",+ "Guardian access revoked.": "Guardian access revoked.",+ "Approved materials saved.": "Approved materials saved.",+ "Save materials": "Save materials",+ "No approved materials are available.": "No approved materials are available.",+ "Learning restrictions": "Learning restrictions",+ "Save restrictions": "Save restrictions",+ "Learning restrictions saved.": "Learning restrictions saved.",+ "New learner password": "New learner password",+ "This immediately removes your access to this learner account.": "This immediately removes your access to this learner account.",+ "This immediately removes access to this learner account.": "This immediately removes access to this learner account.",+ "Guardian relationships": "Guardian relationships",+ "Authorize ordinary accounts to supervise {{username}}.": "Authorize ordinary accounts to supervise {{username}}.",+ "No active guardian relationships.": "No active guardian relationships.",+ "Select a guardian": "Select a guardian",+ "Authorize guardian": "Authorize guardian",+ "Guardian relationship added.": "Guardian relationship added.",+ "{{materials}} approved materials · {{resources}} enabled resources": "{{materials}} approved materials · {{resources}} enabled resources","Remove approved materials": "Remove approved materials","Remove materials": "Remove materials","Removing…": "Removing…",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex d3ff2d9d9..260dbcce1 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -213,8 +213,29 @@"Enabled learning resources": "已启用的学习资源","You are not authorized to view this learner report.": "你无权查看该学习者的报告。","Manage materials": "管理材料",+ "Manage restrictions": "管理限制","View reports": "查看报告","Reset credentials": "重置凭据",+ "Loading learner details…": "正在加载学习者详情…",+ "Revoke access": "撤销访问",+ "Revoke guardian access": "撤销监护访问",+ "Guardian access revoked.": "监护访问已撤销。",+ "Approved materials saved.": "获批材料已保存。",+ "Save materials": "保存材料",+ "No approved materials are available.": "暂无可用的获批材料。",+ "Learning restrictions": "学习限制",+ "Save restrictions": "保存限制",+ "Learning restrictions saved.": "学习限制已保存。",+ "New learner password": "学习者新密码",+ "This immediately removes your access to this learner account.": "这会立即移除你对该学习者账号的访问权限。",+ "This immediately removes access to this learner account.": "这会立即移除对该学习者账号的访问权限。",+ "Guardian relationships": "监护关系",+ "Authorize ordinary accounts to supervise {{username}}.": "授权普通账号监护 {{username}}。",+ "No active guardian relationships.": "暂无有效监护关系。",+ "Select a guardian": "选择监护人",+ "Authorize guardian": "授权监护人",+ "Guardian relationship added.": "监护关系已添加。",+ "{{materials}} approved materials · {{resources}} enabled resources": "{{materials}} 个获批材料 · {{resources}} 个已启用资源","Remove approved materials": "移除获批材料","Remove materials": "移除材料","Removing…": "正在移除…",diff --git a/web/tests/guardian-management.test.ts b/web/tests/guardian-management.test.tsindex 6a0d1f768..df4485ab5 100644--- a/web/tests/guardian-management.test.ts+++ b/web/tests/guardian-management.test.ts@@ -14,21 +14,42 @@ const page = readWebFile("guardian","page.tsx",);+const adminEditor = readWebFile(+ "features",+ "multi-user",+ "components",+ "GuardianRelationshipsEditor.tsx",+);-test("guardian credential reset returns the one-time password to the UI", () => {- assert.match(api, /Promise<string>/);- assert.match(api, /return data\.temporary_password/);- assert.match(page, /setTemporaryPassword/);- assert.match(page, /Copy this password now\. It will not be shown again\./);+test("guardian credential reset never returns or renders a plaintext credential", () => {+ assert.match(api, /JSON\.stringify\(\{ new_password: newPassword \}\)/);+ assert.doesNotMatch(api, /temporary_password/);+ assert.doesNotMatch(page, /Temporary password|setTemporaryPassword|clipboard/);+ assert.doesNotMatch(adminEditor, /Temporary password|setTemporaryPassword|clipboard/);+ assert.match(page, /type="password"/);+ assert.match(adminEditor, /type="password"/);});test("guardian actions follow each relationship permission", () => {assert.match(page, /can\("view_reports"\)/);assert.match(page, /can\("assign_materials"\)/);+ assert.match(page, /can\("manage_restrictions"\)/);assert.match(page, /can\("reset_credentials"\)/);+ assert.match(page, /revokeMyGuardianRelationship/);+ assert.match(page, /saveGuardianMaterials/);+ assert.match(page, /saveGuardianRestrictions/);assert.match(page, /<ConfirmDialog/);});+test("administrators can create, review, revoke, and reset guardian access", () => {+ assert.match(adminEditor, /listAdminGuardianRelationships/);+ assert.match(adminEditor, /authorizeGuardianRelationship/);+ assert.match(adminEditor, /revokeGuardianRelationship/);+ assert.match(adminEditor, /getGuardianReport/);+ assert.match(adminEditor, /resetLearnerCredentials/);+ assert.match(adminEditor, /PERMISSIONS/);+});+test("settings visibility uses the account preset rather than policy presence", () => {const nav = readWebFile("components", "settings", "SettingsNav.tsx");assert.match(nav, /showLearnerOnly: authStatus\.preset === "learner"/);@@ -48,8 +69,12 @@ test("guardian management copy is localized", () => {for (const key of ["Guardian management","Approved materials",+ "Manage restrictions",+ "Revoke guardian access",+ "Save materials",+ "Learning restrictions",+ "Guardian relationships","Reset learner credentials",- "Temporary password","This changes the learner password and revokes every learner device credential.",]) {assert.ok(en[key], `missing English key: ${key}`);