Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

Merge pull request #1129 from evan188199-tech/codex/feat-guardian-account-ui

Bingxi Zhao (Frank)58271301b401
diff --cc deeptutor/api/routers/auth.py
index c7044c897,50295deae..a9bab6d7d
--- a/deeptutor/api/routers/auth.py
+++ b/deeptutor/api/routers/auth.py
@@@ -184,7 -143,6 +184,8 @@@ class AuthStatusResponse(BaseModel)
role: str | None = None
is_admin: bool = False
avatar: str = ""
++ preset: AccountPreset | None = None
+ learning_policy: dict | None = None
class UserInfo(BaseModel):
@@@ -492,20 -413,15 +493,29 @@@ async def auth_status
username="local",
role="admin",
is_admin=True,
++ preset="standard",
)
token = _extract_token(authorization, dt_token)
payload = decode_token(token) if token else None
avatar = ""
++ preset: AccountPreset | None = None
+ learning_policy = None
if payload is not None:
info = get_user_info(payload.username)
if info:
avatar = str(info.get("avatar") or "")
++ raw_preset = str(info.get("preset") or "standard")
++ if raw_preset == "learner":
++ preset = "learner"
++ elif raw_preset == "custom":
++ preset = "custom"
++ else:
++ preset = "standard"
+ learning_policy = learning_policy_for_user(
+ payload.user_id,
+ is_admin=payload.role == "admin",
+ )
return AuthStatusResponse(
enabled=True,
authenticated=payload is not None,
@@@ -514,7 -430,6 +524,8 @@@
role=payload.role if payload else None,
is_admin=payload.role == "admin" if payload else False,
avatar=avatar,
++ preset=preset,
+ learning_policy=learning_policy,
)
diff --cc deeptutor/multi_user/device_credentials.py
index 8749a18e7,000000000..f006614d2
mode 100644,000000..100644
--- a/deeptutor/multi_user/device_credentials.py
+++ b/deeptutor/multi_user/device_credentials.py
@@@ -1,419 -1,0 +1,441 @@@
+"""Revocable device credentials for local learner accounts."""
+
+from __future__ import annotations
+
+from copy import deepcopy
+from datetime import datetime, timedelta, timezone
+import hashlib
+import json
+import secrets
+import threading
+from typing import Any
+from uuid import uuid4
+
+from deeptutor.services.file_io import atomic_write_text
+
+from .identity import get_user_by_id
+from .paths import SYSTEM_ROOT
+
+DEVICE_CREDENTIALS_FILE = SYSTEM_ROOT / "auth" / "device_credentials.json"
+HEARTBEAT_TIMEOUT_SECONDS = 5 * 60
+MAX_PIN_ATTEMPTS = 5
+PIN_LOCKOUT_SECONDS = 15 * 60
+MIN_DAILY_LIMIT_MINUTES = 5
+MAX_DAILY_LIMIT_MINUTES = 24 * 60
+
+_DEVICE_WRITE_LOCK = threading.Lock()
+
+
+def utc_now() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+def _iso(value: datetime) -> str:
+ return value.isoformat()
+
+
+def _parse_iso(value: Any) -> datetime | None:
+ if not isinstance(value, str) or not value:
+ return None
+ try:
+ parsed = datetime.fromisoformat(value)
+ except ValueError:
+ return None
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return parsed.astimezone(timezone.utc)
+
+
+def _hash_pairing_code(code: str) -> str:
+ return hashlib.sha256(code.encode("utf-8")).hexdigest()
+
+
+def _hash_session_nonce(nonce: str) -> str:
+ return hashlib.sha256(nonce.encode("utf-8")).hexdigest()
+
+
+def _canonical_record(value: Any) -> dict[str, Any] | None:
+ if not isinstance(value, dict):
+ return None
+ credential_id = str(value.get("id") or f"dc_{uuid4().hex}")
+ user_id = str(value.get("user_id") or "")
+ pairing_hash = str(value.get("pairing_code_hash") or "")
+ pin_hash = str(value.get("pin_hash") or "")
+ expires_at = _parse_iso(value.get("expires_at"))
+ daily_limit = value.get("daily_limit_minutes")
+ if not user_id or not pairing_hash or not pin_hash or expires_at is None:
+ return None
+ if not isinstance(daily_limit, int) or not (
+ MIN_DAILY_LIMIT_MINUTES <= daily_limit <= MAX_DAILY_LIMIT_MINUTES
+ ):
+ return None
+ revoked_at = _parse_iso(value.get("revoked_at"))
+ last_heartbeat = _parse_iso(value.get("last_heartbeat_at"))
+ used_seconds = value.get("used_seconds", 0)
+ if not isinstance(used_seconds, int) or used_seconds < 0:
+ used_seconds = 0
+ usage_day = str(value.get("usage_day") or "")
+ if usage_day and not _valid_usage_day(usage_day):
+ usage_day = ""
+ failed_pin_attempts = value.get("failed_pin_attempts", 0)
+ if not isinstance(failed_pin_attempts, int) or failed_pin_attempts < 0:
+ failed_pin_attempts = 0
+ pin_locked_until = _parse_iso(value.get("pin_locked_until"))
+ return {
+ "id": credential_id,
+ "user_id": user_id,
+ "device_name": str(value.get("device_name") or "Device")[:80],
+ "pairing_code_hash": pairing_hash,
+ "pin_hash": pin_hash,
+ "created_at": str(value.get("created_at") or ""),
+ "expires_at": _iso(expires_at),
+ "daily_limit_minutes": daily_limit,
+ "last_login_at": str(value.get("last_login_at") or ""),
+ "last_heartbeat_at": _iso(last_heartbeat) if last_heartbeat else "",
+ "usage_day": usage_day,
+ "used_seconds": min(used_seconds, daily_limit * 60),
+ "session_nonce_hash": str(value.get("session_nonce_hash") or ""),
+ "failed_pin_attempts": min(failed_pin_attempts, MAX_PIN_ATTEMPTS),
+ "pin_locked_until": _iso(pin_locked_until) if pin_locked_until else "",
+ "revoked_at": _iso(revoked_at) if revoked_at else None,
+ "revoked_by": str(value.get("revoked_by") or "") if revoked_at else "",
+ }
+
+
+def _valid_usage_day(value: str) -> bool:
+ try:
+ datetime.strptime(value, "%Y-%m-%d")
+ except ValueError:
+ return False
+ return True
+
+
+def _load_records() -> list[dict[str, Any]]:
+ try:
+ loaded = json.loads(DEVICE_CREDENTIALS_FILE.read_text(encoding="utf-8"))
+ except Exception:
+ return []
+ if not isinstance(loaded, list):
+ return []
+ records: list[dict[str, Any]] = []
+ seen: set[str] = set()
+ for value in loaded:
+ record = _canonical_record(value)
+ if record is None or record["id"] in seen:
+ continue
+ seen.add(record["id"])
+ records.append(record)
+ return records
+
+
+def _write_records(records: list[dict[str, Any]]) -> None:
+ DEVICE_CREDENTIALS_FILE.parent.mkdir(parents=True, exist_ok=True)
+ atomic_write_text(
+ DEVICE_CREDENTIALS_FILE,
+ json.dumps(records, indent=2, ensure_ascii=False),
+ )
+
+
+def _public_record(record: dict[str, Any]) -> dict[str, Any]:
+ return {
+ key: deepcopy(value)
+ for key, value in record.items()
+ if key
+ not in {
+ "pairing_code_hash",
+ "pin_hash",
+ "session_nonce_hash",
+ "failed_pin_attempts",
+ "pin_locked_until",
+ }
+ }
+
+
+def _active_account(user_id: str) -> tuple[str, dict[str, Any]] | None:
+ account = get_user_by_id(user_id)
+ if account is None:
+ return None
+ username, record = account
+ if str(record.get("role") or "user") != "user" or bool(record.get("disabled")):
+ return None
+ if str(record.get("preset") or "standard") != "learner":
+ return None
+ return username, record
+
+
+def _usage_for(record: dict[str, Any], now: datetime) -> tuple[str, int]:
+ current_day = now.date().isoformat()
+ if record["usage_day"] != current_day:
+ return current_day, 0
+ return current_day, int(record["used_seconds"])
+
+
+def _is_usable(record: dict[str, Any], now: datetime) -> bool:
+ if record["revoked_at"] is not None:
+ return False
+ expires_at = _parse_iso(record["expires_at"])
+ if expires_at is None or expires_at <= now:
+ return False
+ if _active_account(record["user_id"]) is None:
+ return False
+ _usage_day, used_seconds = _usage_for(record, now)
+ if used_seconds >= record["daily_limit_minutes"] * 60:
+ return False
+ last_heartbeat = _parse_iso(record["last_heartbeat_at"])
+ if last_heartbeat is None:
+ return False
+ elapsed = (now - last_heartbeat).total_seconds()
+ return 0 <= elapsed <= HEARTBEAT_TIMEOUT_SECONDS
+
+
+def _charge_previous_lease(record: dict[str, Any], now: datetime) -> None:
+ """Account for an active lease before a same-day re-login rotates it."""
+ usage_day, used_seconds = _usage_for(record, now)
+ last_heartbeat = _parse_iso(record["last_heartbeat_at"])
+ elapsed = 0
+ if last_heartbeat is not None and last_heartbeat.date() == now.date():
+ elapsed = min(
+ max(int((now - last_heartbeat).total_seconds()), 0),
+ HEARTBEAT_TIMEOUT_SECONDS,
+ )
+ record["usage_day"] = usage_day
+ record["used_seconds"] = min(
+ used_seconds + elapsed,
+ record["daily_limit_minutes"] * 60,
+ )
+
+
+def issue_device_credential(
+ *,
+ user_id: str,
+ device_name: str,
+ expires_at: datetime,
+ daily_limit_minutes: int,
+ now: datetime | None = None,
+) -> tuple[dict[str, Any], str, str]:
+ """Create a credential and return its public view, code, and one-time PIN."""
+
+ current = now or utc_now()
+ if _active_account(user_id) is None:
+ raise ValueError("Device credentials require an active learner account.")
+ if expires_at <= current:
+ raise ValueError("Device credential expiry must be in the future.")
+ if expires_at - current > timedelta(days=365):
+ raise ValueError("Device credential expiry cannot exceed 365 days.")
+ if not (MIN_DAILY_LIMIT_MINUTES <= daily_limit_minutes <= MAX_DAILY_LIMIT_MINUTES):
+ raise ValueError("Daily limit must be between 5 and 1440 minutes.")
+ device = device_name.strip() or "Device"
+ if len(device) > 80:
+ raise ValueError("Device name cannot exceed 80 characters.")
+
+ from deeptutor.services.auth import hash_password
+
+ pairing_code = f"dc_{secrets.token_urlsafe(24)}"
+ pin = f"{secrets.randbelow(1_000_000):06d}"
+ record = {
+ "id": f"dc_{uuid4().hex}",
+ "user_id": user_id,
+ "device_name": device,
+ "pairing_code_hash": _hash_pairing_code(pairing_code),
+ "pin_hash": hash_password(pin),
+ "created_at": _iso(current),
+ "expires_at": _iso(expires_at),
+ "daily_limit_minutes": daily_limit_minutes,
+ "last_login_at": "",
+ "last_heartbeat_at": "",
+ "usage_day": "",
+ "used_seconds": 0,
+ "session_nonce_hash": "",
+ "failed_pin_attempts": 0,
+ "pin_locked_until": "",
+ "revoked_at": None,
+ "revoked_by": "",
+ }
+ with _DEVICE_WRITE_LOCK:
+ records = _load_records()
+ records.append(record)
+ _write_records(records)
+ return _public_record(record), pairing_code, pin
+
+
+def list_device_credentials(
+ *, user_id: str | None = None, include_revoked: bool = False
+) -> list[dict[str, Any]]:
+ return [
+ _public_record(record)
+ for record in _load_records()
+ if (include_revoked or record["revoked_at"] is None)
+ and (user_id is None or record["user_id"] == user_id)
+ ]
+
+
+def begin_device_session(
+ pairing_code: str, pin: str, now: datetime | None = None
+) -> tuple[dict[str, Any], str, str, str, str] | None:
+ """Verify a code and PIN, then start a bounded heartbeat session."""
+
+ current = now or utc_now()
+ pairing_hash = _hash_pairing_code(pairing_code)
+ from deeptutor.services.auth import verify_password
+
+ with _DEVICE_WRITE_LOCK:
+ records = _load_records()
+ record = next(
+ (item for item in records if item["pairing_code_hash"] == pairing_hash),
+ None,
+ )
+ if record is None or not secrets.compare_digest(record["pairing_code_hash"], pairing_hash):
+ return None
+ account = _active_account(record["user_id"])
+ if account is None:
+ return None
+ if record["revoked_at"] is not None:
+ return None
+ expires_at = _parse_iso(record["expires_at"])
+ if expires_at is None or expires_at <= current:
+ return None
+ locked_until = _parse_iso(record["pin_locked_until"])
+ if locked_until is not None and locked_until > current:
+ return None
+ if not verify_password(pin, record["pin_hash"]):
+ record["failed_pin_attempts"] += 1
+ if record["failed_pin_attempts"] >= MAX_PIN_ATTEMPTS:
+ record["pin_locked_until"] = _iso(current + timedelta(seconds=PIN_LOCKOUT_SECONDS))
+ _write_records(records)
+ return None
+ record["failed_pin_attempts"] = 0
+ record["pin_locked_until"] = ""
+ _charge_previous_lease(record, current)
+ if record["used_seconds"] >= record["daily_limit_minutes"] * 60:
+ _write_records(records)
+ return None
+ session_nonce = secrets.token_urlsafe(32)
+ record["session_nonce_hash"] = _hash_session_nonce(session_nonce)
+ record["last_login_at"] = _iso(current)
+ record["last_heartbeat_at"] = _iso(current)
+ _write_records(records)
+ username, user_record = account
+ return (
+ _public_record(record),
+ username,
+ str(user_record.get("role") or "user"),
+ record["user_id"],
+ session_nonce,
+ )
+
+
+def validate_device_token(user_id: str, credential_id: str, session_nonce: str) -> bool:
+ record = next(
+ (item for item in _load_records() if item["id"] == credential_id),
+ None,
+ )
+ return (
+ record is not None
+ and record["user_id"] == user_id
+ and bool(session_nonce)
+ and secrets.compare_digest(
+ record["session_nonce_hash"],
+ _hash_session_nonce(session_nonce),
+ )
+ and _is_usable(record, utc_now())
+ )
+
+
+def heartbeat_device_credential(
+ credential_id: str,
+ *,
+ user_id: str,
+ session_nonce: str,
+ now: datetime | None = None,
+) -> dict[str, Any]:
+ """Advance daily usage and refresh the server heartbeat lease."""
+
+ current = now or utc_now()
+ with _DEVICE_WRITE_LOCK:
+ records = _load_records()
+ record = next(
+ (item for item in records if item["id"] == credential_id),
+ None,
+ )
+ nonce_matches = bool(record and session_nonce) and secrets.compare_digest(
+ record["session_nonce_hash"],
+ _hash_session_nonce(session_nonce),
+ )
+ if (
+ record is None
+ or record["user_id"] != user_id
+ or not nonce_matches
+ or not _is_usable(record, current)
+ ):
+ raise ValueError("Device credential is not active.")
+
+ last_heartbeat = _parse_iso(record["last_heartbeat_at"])
+ if last_heartbeat is None:
+ raise ValueError("Device credential is not active.")
+ elapsed = int((current - last_heartbeat).total_seconds())
+ usage_day, used_seconds = _usage_for(record, current)
+ record["usage_day"] = usage_day
+ record["used_seconds"] = min(
+ used_seconds + max(elapsed, 0),
+ record["daily_limit_minutes"] * 60,
+ )
+ record["last_heartbeat_at"] = _iso(current)
+ _write_records(records)
+ limit_seconds = record["daily_limit_minutes"] * 60
+ view = _public_record(record)
+ view["remaining_seconds"] = max(limit_seconds - record["used_seconds"], 0)
+ view["limit_reached"] = record["used_seconds"] >= limit_seconds
+ return view
+
+
+def revoke_device_credential(
+ credential_id: str, *, revoked_by: str, now: datetime | None = None
+) -> dict[str, Any] | None:
+ current = now or utc_now()
+ with _DEVICE_WRITE_LOCK:
+ records = _load_records()
+ for record in records:
+ if record["id"] != credential_id:
+ continue
+ if record["revoked_at"] is None:
+ record["revoked_at"] = _iso(current)
+ record["revoked_by"] = revoked_by
+ _write_records(records)
+ return _public_record(record)
+ return None
+
+
++def revoke_device_credentials_for_user(
++ user_id: str, *, revoked_by: str, now: datetime | None = None
++) -> int:
++ """Revoke every active device credential and session for one learner."""
++
++ current = now or utc_now()
++ with _DEVICE_WRITE_LOCK:
++ records = _load_records()
++ changed = 0
++ for record in records:
++ if record["user_id"] != user_id or record["revoked_at"] is not None:
++ continue
++ record["revoked_at"] = _iso(current)
++ record["revoked_by"] = revoked_by
++ record["session_nonce_hash"] = ""
++ changed += 1
++ if changed:
++ _write_records(records)
++ return changed
++
++
+__all__ = [
+ "DEVICE_CREDENTIALS_FILE",
+ "HEARTBEAT_TIMEOUT_SECONDS",
+ "MAX_PIN_ATTEMPTS",
+ "PIN_LOCKOUT_SECONDS",
+ "begin_device_session",
+ "heartbeat_device_credential",
+ "issue_device_credential",
+ "list_device_credentials",
+ "revoke_device_credential",
++ "revoke_device_credentials_for_user",
+ "validate_device_token",
+]
diff --cc deeptutor/multi_user/router.py
index 70f7dbe30,ef63d785d..ca4d59652
--- a/deeptutor/multi_user/router.py
+++ b/deeptutor/multi_user/router.py
@@@ -24,7 -18,7 +24,8 @@@ from deeptutor.services.skill.service i
from .audit import log_admin_action, log_guardian_action
from .book_permission import BookDefaultLevel, BookPermission, BookPermissionLevel
from .context import get_current_user
-from .grants import load_grant, save_grant
++from .device_credentials import revoke_device_credentials_for_user
+from .grants import load_grant, normalize_grant, save_grant, validate_grant
from .guardians import (
GUARDIAN_PERMISSIONS,
authorize_guardian,
@@@ -470,13 -406,13 +471,23 @@@ async def reset_learner_credentials
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,
++ )
if set_password(learner_username, hash_password(temporary_password)) is None:
raise HTTPException(status_code=404, detail="User not found")
log_guardian_action(
"guardian_credential_reset",
guardian_user_id=guardian_user_id,
learner_user_id=learner_user_id,
-- summary={"credential_reset": True},
++ summary={
++ "credential_reset": True,
++ "device_credentials_revoked": revoked_devices,
++ },
)
return {"temporary_password": temporary_password}
diff --cc tests/multi_user/test_account_presets.py
index e6bf95b9d,000000000..b732f8400
mode 100644,000000..100644
--- a/tests/multi_user/test_account_presets.py
+++ b/tests/multi_user/test_account_presets.py
@@@ -1,239 -1,0 +1,240 @@@
+"""Account preset persistence, expansion, and admin HTTP behavior."""
+
+from __future__ import annotations
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+import pytest
+
+
+def preset_client(mu_isolated_root, monkeypatch, as_user):
+ import deeptutor.api.routers.auth as auth_router
+ from deeptutor.api.routers.auth import require_admin
+ from deeptutor.multi_user import router as multi_user_router
+ from deeptutor.multi_user.identity import save_user
+ from deeptutor.services.auth import TokenPayload
+
+ admin = save_user("admin", "$2b$12$placeholder", role="admin")
+ tokens = {"admin-token": TokenPayload(username="admin", role="admin", user_id=admin["id"])}
+ monkeypatch.setattr(auth_router, "AUTH_ENABLED", True)
+ monkeypatch.setattr(auth_router, "decode_token", lambda token: tokens.get(token))
+
+ app = FastAPI()
+ app.include_router(auth_router.router, prefix="/api/v1/auth")
+ app.include_router(multi_user_router.router, prefix="/api/v1/multi-user")
+ app.dependency_overrides[require_admin] = lambda: tokens["admin-token"]
+ return TestClient(app), admin, tokens
+
+
+def test_legacy_and_new_standard_users_default_to_standard(seed_user):
+ user = seed_user("legacy")
+ assert user["preset"] == "standard"
+
+
+def test_learning_surface_routing_matches_complete_path_segments():
+ from deeptutor.api.routers.auth import _learning_surface_for_path
+
+ assert _learning_surface_for_path("/api/v1/reading/materials") == "reading"
+ assert _learning_surface_for_path("/api/v1/question-notebook/entries") == "chat"
+ assert _learning_surface_for_path("/api/v1/reading-private") == ""
+ assert _learning_surface_for_path("/api/v1/questions") == ""
+
+
[email protected]("preset", ["standard", "custom"])
+def test_non_learner_presets_do_not_install_a_learning_grant(preset_client, preset):
+ client, _admin, _tokens = preset_client
+
+ response = client.post(
+ "/api/v1/auth/users",
+ headers={"Authorization": "Bearer admin-token"},
+ json={
+ "username": f"{preset}-user",
+ "password": "reading-password-1",
+ "preset": preset,
+ },
+ )
+
+ assert response.status_code == 201, response.text
+ body = response.json()
+ assert body["preset"] == preset
+ from deeptutor.multi_user.grants import load_grant
+
+ assert load_grant(body["user_id"])["learning_policy"] is None
+
+
+def test_learner_preset_expands_to_a_conservative_grant(preset_client):
+ from deeptutor.multi_user.grants import load_grant
+
+ client, _admin, _tokens = preset_client
+
+ response = client.post(
+ "/api/v1/auth/users",
+ headers={"Authorization": "Bearer admin-token"},
+ json={
+ "username": "student",
+ "password": "reading-password-1",
+ "preset": "learner",
+ },
+ )
+
+ assert response.status_code == 201, response.text
+ body = response.json()
+ assert body["role"] == "user"
+ assert body["preset"] == "learner"
+
+ grant = load_grant(body["user_id"])
+ assert grant["enabled_tools"] == []
+ assert grant["mcp_tools"] == []
+ assert grant["cli_apps"] == []
+ assert grant["exec_enabled"] is False
+ assert grant["learning_policy"] == {
+ "age_band": "9-12",
+ "locked_persona": "teacher",
+ "allowed_capabilities": ["chat", "immersive_reading"],
+ "default_capability": "immersive_reading",
+ "allowed_surfaces": ["chat", "reading"],
+ "reading": {
+ "allow_upload": False,
+ "material_ids": [],
+ "extensions": [],
+ },
+ }
+
+
+def test_learner_creation_rolls_back_when_grant_initialization_fails(preset_client, monkeypatch):
+ from deeptutor.multi_user import grants
+ from deeptutor.multi_user.identity import get_user
+
+ client, _admin, _tokens = preset_client
+
+ def fail_save_grant(*args, **kwargs):
+ raise RuntimeError("grant store unavailable")
+
+ monkeypatch.setattr(grants, "save_grant", fail_save_grant)
+ response = client.post(
+ "/api/v1/auth/users",
+ headers={"Authorization": "Bearer admin-token"},
+ json={
+ "username": "student",
+ "password": "reading-password-1",
+ "preset": "learner",
+ },
+ )
+
+ assert response.status_code == 500
+ assert response.json()["detail"] == "The learner preset could not be initialized."
+ assert get_user("student") is None
+
+
+def test_learner_accounts_cannot_disable_the_learning_policy(preset_client):
+ client, _admin, _tokens = preset_client
+ created = client.post(
+ "/api/v1/auth/users",
+ headers={"Authorization": "Bearer admin-token"},
+ json={
+ "username": "student",
+ "password": "reading-password-1",
+ "preset": "learner",
+ },
+ ).json()
+
+ response = client.put(
+ f"/api/v1/multi-user/users/{created['user_id']}/grants",
+ headers={"Authorization": "Bearer admin-token"},
+ json={"grant": {"learning_policy": None}},
+ )
+
+ assert response.status_code == 400
+ assert response.json()["detail"] == "Learner accounts must retain a learning policy."
+
+
[email protected]("preset", ["learner", "custom"])
+def test_pocketbase_rejects_presets_it_cannot_enforce(preset_client, monkeypatch, preset):
+ import deeptutor.api.routers.auth as auth_router
+
+ client, _admin, _tokens = preset_client
+ monkeypatch.setattr(auth_router, "POCKETBASE_ENABLED", True)
+ response = client.post(
+ "/api/v1/auth/users",
+ headers={"Authorization": "Bearer admin-token"},
+ json={
+ "username": "remote-student",
+ "password": "reading-password-1",
+ "preset": preset,
+ },
+ )
+
+ assert response.status_code == 400
+ assert "standard preset" in response.json()["detail"]
+
+
+def test_auth_status_returns_the_effective_learning_policy(preset_client):
+ client, _admin, tokens = preset_client
+ created = client.post(
+ "/api/v1/auth/users",
+ headers={"Authorization": "Bearer admin-token"},
+ json={
+ "username": "student",
+ "password": "reading-password-1",
+ "preset": "learner",
+ },
+ ).json()
+ from deeptutor.services.auth import TokenPayload
+
+ tokens["learner-token"] = TokenPayload(
+ username="student", role="user", user_id=created["user_id"]
+ )
+ response = client.get(
+ "/api/v1/auth/status",
+ headers={"Authorization": "Bearer learner-token"},
+ )
+
+ assert response.status_code == 200
++ assert response.json()["preset"] == "learner"
+ assert response.json()["learning_policy"]["default_capability"] == ("immersive_reading")
+
+
+def test_assigning_a_material_copies_the_admin_material_once(
+ preset_client, as_user, seed_user, tmp_path
+):
+ from deeptutor.multi_user.paths import get_path_service_for_scope, scope_for_user
+ from deeptutor.reading import ReadingStore
+
+ client, admin, _tokens = preset_client
+ learner = seed_user("student")
+ source = tmp_path / "lesson.txt"
+ source.write_text("Assigned reading passage.", encoding="utf-8")
+ with as_user(admin["id"], role="admin", username="admin"):
+ material = ReadingStore().ingest(source)
+
+ grant = {
+ "enabled_tools": [],
+ "mcp_tools": [],
+ "cli_apps": [],
+ "exec_enabled": False,
+ "learning_policy": {
+ "age_band": "9-12",
+ "locked_persona": "teacher",
+ "allowed_capabilities": ["chat", "immersive_reading"],
+ "default_capability": "immersive_reading",
+ "allowed_surfaces": ["chat", "reading"],
+ "reading": {
+ "allow_upload": False,
+ "material_ids": [material.material_id],
+ "extensions": [],
+ },
+ },
+ }
+ response = client.put(
+ f"/api/v1/multi-user/users/{learner['id']}/grants",
+ headers={"Authorization": "Bearer admin-token"},
+ json={"grant": grant},
+ )
+
+ assert response.status_code == 200, response.text
+ user_root = get_path_service_for_scope(
+ scope_for_user(learner["id"], is_admin=False)
+ ).get_workspace_feature_dir("reading")
+ staged = user_root / material.material_id
+ assert staged.is_dir()
diff --cc tests/multi_user/test_guardians.py
index 940ccd0a4,c3877ef5c..958b02239
--- a/tests/multi_user/test_guardians.py
+++ b/tests/multi_user/test_guardians.py
@@@ -1,5 -1,5 +1,6 @@@
from __future__ import annotations
++from datetime import datetime, timedelta, timezone
import json
from fastapi import FastAPI
@@@ -266,6 -242,6 +267,11 @@@ def test_guardian_can_reset_local_crede
assert created.status_code == 201
from deeptutor.multi_user import router as multi_user_router
++ from deeptutor.multi_user.device_credentials import (
++ begin_device_session,
++ issue_device_credential,
++ validate_device_token,
++ )
from deeptutor.services.auth import verify_password
monkeypatch.setattr(multi_user_router, "POCKETBASE_ENABLED", True)
@@@ -276,6 -252,6 +282,17 @@@
assert unsupported.status_code == 400
monkeypatch.setattr(multi_user_router, "POCKETBASE_ENABLED", False)
++ _device, pairing_code, pin = issue_device_credential(
++ user_id=learner_id,
++ device_name="Learner tablet",
++ expires_at=datetime.now(timezone.utc) + timedelta(days=7),
++ daily_limit_minutes=30,
++ )
++ session = begin_device_session(pairing_code, pin)
++ assert session is not None
++ device, _username, _role, _user_id, session_nonce = session
++ assert validate_device_token(learner_id, device["id"], session_nonce) is True
++
reset = client.post(
f"/api/v1/multi-user/learners/{learner_id}/credentials/reset",
headers=_auth("guardian-token"),
@@@ -289,6 -265,6 +306,7 @@@
learner_hash = load_users()["learner"]["hash"]
assert verify_password("learner-password", learner_hash) is False
assert verify_password(temporary_password, learner_hash) is True
++ assert validate_device_token(learner_id, device["id"], session_nonce) is False
audit_path = mu_isolated_root / "data" / "system" / "audit" / "usage.jsonl"
assert temporary_password not in audit_path.read_text()
diff --cc web/app/(utility)/settings/guardian/page.tsx
index 000000000,1ce877a52..0c39952ed
mode 000000,100644..100644
--- a/web/app/(utility)/settings/guardian/page.tsx
+++ b/web/app/(utility)/settings/guardian/page.tsx
@@@ -1,0 -1,21 +1,292 @@@
+ "use client";
+
+ import { useEffect, useState } from "react";
++import { Copy, KeyRound, Library } from "lucide-react";
+ import { useTranslation } from "react-i18next";
+
-import { clearGuardianMaterials, getGuardianReport, listGuardianRelationships, resetLearnerCredentials, type GuardianRelationship, type GuardianReport } from "@/lib/guardian-api";
++import { ConfirmDialog } from "@/components/ui/ConfirmDialog";
++import {
++ clearGuardianMaterials,
++ getGuardianReport,
++ listGuardianRelationships,
++ resetLearnerCredentials,
++ type GuardianRelationship,
++ type GuardianReport,
++} from "@/lib/guardian-api";
++
++type BusyAction = "report" | "materials" | "credentials" | null;
++type ConfirmAction = "materials" | "credentials" | null;
++
++const permissionKeys: Record<string, string> = {
++ assign_materials: "Manage materials",
++ reset_credentials: "Reset credentials",
++ view_reports: "View reports",
++};
+
+ export default function GuardianSettingsPage() {
+ const { t } = useTranslation();
+ const [relationships, setRelationships] = useState<GuardianRelationship[]>([]);
- const [selected, setSelected] = useState<GuardianReport | null>(null);
++ const [selectedRelationship, setSelectedRelationship] =
++ useState<GuardianRelationship | null>(null);
++ const [report, setReport] = useState<GuardianReport | null>(null);
++ 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);
+
- useEffect(() => { void listGuardianRelationships().then(setRelationships).catch((err: Error) => setError(err.message)); }, []);
- const selectLearner = async (relationship: GuardianRelationship) => { setError(null); try { setSelected(await getGuardianReport(relationship.learner_user_id)); } catch (err) { setError((err as Error).message); } };
- const resetCredentials = async () => { if (!selected) return; setError(null); try { await resetLearnerCredentials(selected.learner.id); setMessage(t("Learner credentials were reset.")); } catch (err) { setError((err as Error).message); } };
- const clearMaterials = async () => { if (!selected) return; setError(null); try { await clearGuardianMaterials(selected.learner.id); setSelected(await getGuardianReport(selected.learner.id)); setMessage(t("Approved materials removed.")); } catch (err) { setError((err as Error).message); } };
++ useEffect(() => {
++ let cancelled = false;
++ void listGuardianRelationships()
++ .then((value) => {
++ if (!cancelled) setRelationships(value);
++ })
++ .catch((reason: unknown) => {
++ if (!cancelled) setError((reason as Error).message);
++ })
++ .finally(() => {
++ if (!cancelled) setLoading(false);
++ });
++ return () => {
++ cancelled = true;
++ };
++ }, []);
++
++ const can = (permission: string) =>
++ selectedRelationship?.permissions.includes(permission) ?? false;
++
++ const selectLearner = async (relationship: GuardianRelationship) => {
++ setSelectedRelationship(relationship);
++ setReport(null);
++ setTemporaryPassword(null);
++ setCopied(false);
++ setMessage(null);
++ setError(null);
++ if (!relationship.permissions.includes("view_reports")) return;
++ setBusy("report");
++ try {
++ setReport(await getGuardianReport(relationship.learner_user_id));
++ } catch (reason) {
++ setError((reason as Error).message);
++ } finally {
++ setBusy(null);
++ }
++ };
++
++ const resetCredentials = async () => {
++ if (!selectedRelationship || !can("reset_credentials")) return;
++ setConfirmAction(null);
++ setBusy("credentials");
++ setError(null);
++ setMessage(null);
++ setTemporaryPassword(null);
++ try {
++ setTemporaryPassword(
++ await resetLearnerCredentials(selectedRelationship.learner_user_id),
++ );
++ setMessage(t("Learner credentials were reset."));
++ } catch (reason) {
++ setError((reason as Error).message);
++ } finally {
++ setBusy(null);
++ }
++ };
++
++ const clearMaterials = async () => {
++ if (!selectedRelationship || !can("assign_materials")) return;
++ setConfirmAction(null);
++ setBusy("materials");
++ 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."));
++ } catch (reason) {
++ setError((reason as Error).message);
++ } finally {
++ setBusy(null);
++ }
++ };
++
++ return (
++ <main className="mx-auto max-w-3xl px-6 py-8">
++ <h1 className="text-xl font-semibold">{t("Guardian management")}</h1>
++ <p className="mt-1 text-sm text-[var(--muted-foreground)]">
++ {t("Review authorized learners and their approved learning materials.")}
++ </p>
++
++ {error && (
++ <p className="mt-4 rounded-lg bg-red-500/10 px-3 py-2 text-sm text-red-600">
++ {error}
++ </p>
++ )}
++ {message && (
++ <p className="mt-4 rounded-lg bg-emerald-500/10 px-3 py-2 text-sm text-emerald-700 dark:text-emerald-400">
++ {message}
++ </p>
++ )}
++
++ {loading ? (
++ <p className="mt-8 text-sm text-[var(--muted-foreground)]">
++ {t("Loading guardian relationships…")}
++ </p>
++ ) : relationships.length === 0 ? (
++ <p className="mt-8 text-sm text-[var(--muted-foreground)]">
++ {t("No active learner relationships.")}
++ </p>
++ ) : (
++ <div className="mt-6 grid gap-3 sm:grid-cols-2">
++ {relationships.map((relationship) => (
++ <button
++ key={relationship.id}
++ type="button"
++ onClick={() => void selectLearner(relationship)}
++ className={`rounded-lg border p-4 text-left transition-colors hover:bg-[var(--muted)] ${
++ selectedRelationship?.id === relationship.id
++ ? "border-[var(--primary)] bg-[var(--muted)]"
++ : "border-[var(--border)]"
++ }`}
++ >
++ <strong>{relationship.learner_username}</strong>
++ <span className="mt-1 block text-xs text-[var(--muted-foreground)]">
++ {relationship.permissions
++ .map((permission) => t(permissionKeys[permission] ?? permission))
++ .join(" · ")}
++ </span>
++ </button>
++ ))}
++ </div>
++ )}
++
++ {selectedRelationship && (
++ <section className="mt-8 border-t border-[var(--border)] pt-6">
++ <h2 className="font-medium">
++ {report?.learner.username ?? selectedRelationship.learner_username}
++ </h2>
++
++ {busy === "report" ? (
++ <p className="mt-3 text-sm text-[var(--muted-foreground)]">
++ {t("Loading learner report…")}
++ </p>
++ ) : can("view_reports") && report ? (
++ <div className="mt-4 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)]">
++ {t("Approved materials")}
++ </div>
++ <div className="mt-1 text-lg font-semibold">
++ {report.assigned_materials.length}
++ </div>
++ </div>
++ <div className="rounded-lg border border-[var(--border)] p-4">
++ <div className="text-xs text-[var(--muted-foreground)]">
++ {t("Enabled learning resources")}
++ </div>
++ <div className="mt-1 text-lg font-semibold">
++ {report.grant_summary.model_count +
++ report.grant_summary.knowledge_base_count +
++ report.grant_summary.skill_count}
++ </div>
++ </div>
++ </div>
++ ) : !can("view_reports") ? (
++ <p className="mt-3 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") && (
++ <button
++ type="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"
++ >
++ <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>
++ )}
+
- return <main className="mx-auto max-w-3xl px-6 py-8"><h1 className="text-xl font-semibold">{t("Guardian management")}</h1><p className="mt-1 text-sm text-[var(--muted-foreground)]">{t("Review authorized learners and their approved learning materials.")}</p>{error && <p className="mt-4 text-sm text-red-600">{error}</p>}{message && <p className="mt-4 text-sm text-green-700">{message}</p>}{relationships.length === 0 ? <p className="mt-8 text-sm text-[var(--muted-foreground)]">{t("No active learner relationships.")}</p> : <div className="mt-6 grid gap-3">{relationships.map((relationship) => <button key={relationship.id} type="button" onClick={() => void selectLearner(relationship)} className="rounded-md border border-[var(--border)] p-4 text-left hover:bg-[var(--muted)]"><strong>{relationship.learner_username}</strong><span className="mt-1 block text-xs text-[var(--muted-foreground)]">{relationship.permissions.join(", ")}</span></button>)}</div>}{selected && <section className="mt-8 border-t border-[var(--border)] pt-6"><h2 className="font-medium">{selected.learner.username}</h2><p className="mt-2 text-sm">{t("Approved materials")}: {selected.assigned_materials.length}</p><button type="button" onClick={() => void clearMaterials()} disabled={!selected.assigned_materials.length} className="mt-3 rounded-md border border-[var(--border)] px-3 py-2 text-sm disabled:opacity-50">{t("Remove approved materials")}</button><p className="mt-3 text-sm">{t("Enabled learning resources")}: {selected.grant_summary.model_count + selected.grant_summary.knowledge_base_count + selected.grant_summary.skill_count}</p><button type="button" onClick={() => void resetCredentials()} className="mt-4 rounded-md border border-[var(--border)] px-3 py-2 text-sm">{t("Reset learner credentials")}</button></section>}</main>;
++ <ConfirmDialog
++ open={confirmAction !== null}
++ title={
++ confirmAction === "credentials"
++ ? t("Reset learner credentials")
++ : t("Remove approved materials")
++ }
++ confirmLabel={
++ confirmAction === "credentials"
++ ? t("Reset credentials")
++ : t("Remove materials")
++ }
++ tone="danger"
++ busy={busy !== null}
++ onCancel={() => setConfirmAction(null)}
++ onConfirm={() => {
++ if (confirmAction === "credentials") void resetCredentials();
++ if (confirmAction === "materials") void clearMaterials();
++ }}
++ >
++ {confirmAction === "credentials"
++ ? t(
++ "This changes the learner password and revokes every learner device credential.",
++ )
++ : t("This removes every approved material from the learner account.")}
++ </ConfirmDialog>
++ </main>
++ );
+ }
diff --cc web/components/settings/SettingsNav.tsx
index 208c1c885,28cf807b7..c205ec1ce
--- a/web/components/settings/SettingsNav.tsx
+++ b/web/components/settings/SettingsNav.tsx
@@@ -89,12 -89,10 +89,18 @@@ type Group =
* leaves; one without is itself a row, so a single-page category never costs
* an extra level of nesting.
*/
- function useGroups(hideAdminOnly: boolean, showLearnerOnly: boolean): Group[] {
-function useGroups(hideAdminOnly: boolean): Group[] {
++function useGroups(
++ hideAdminOnly: boolean,
++ showLearnerOnly: boolean,
++ showGuardianOnly: boolean,
++): Group[] {
return useMemo(
() =>
- SETTINGS_CATEGORIES.map((category) => ({
+ SETTINGS_CATEGORIES.filter(
- (category) => !category.learnerOnly || showLearnerOnly,
++ (category) =>
++ (!category.learnerOnly || showLearnerOnly) &&
++ (!category.guardianOnly || showGuardianOnly),
+ ).map((category) => ({
key: category.key,
label: category.label,
href: category.href,
@@@ -115,26 -113,17 +121,34 @@@
.map((leaf) => ({ leaf, category: category.label }) satisfies Row),
standalone: !category.children,
})),
- [hideAdminOnly, showLearnerOnly],
- [hideAdminOnly],
++ [hideAdminOnly, showGuardianOnly, showLearnerOnly],
);
}
-function useHideAdminOnly(): boolean {
- const [hideAdminOnly, setHideAdminOnly] = useState(false);
+function useSettingsVisibility(): {
+ hideAdminOnly: boolean;
+ showLearnerOnly: boolean;
++ showGuardianOnly: boolean;
+} {
+ const [visibility, setVisibility] = useState({
+ hideAdminOnly: false,
+ showLearnerOnly: false,
++ showGuardianOnly: false,
+ });
useEffect(() => {
let cancelled = false;
fetchAuthStatus().then((authStatus) => {
if (cancelled || !authStatus) return;
- setHideAdminOnly(Boolean(authStatus.enabled) && !authStatus.is_admin);
+ setVisibility({
+ hideAdminOnly: Boolean(authStatus.enabled) && !authStatus.is_admin,
- showLearnerOnly: Boolean(authStatus.learning_policy),
++ showLearnerOnly: authStatus.preset === "learner",
++ showGuardianOnly: Boolean(
++ authStatus.enabled &&
++ authStatus.authenticated &&
++ !authStatus.is_admin &&
++ (authStatus.preset === "standard" || authStatus.preset === "custom"),
++ ),
+ });
});
return () => {
cancelled = true;
@@@ -157,8 -146,7 +171,12 @@@ export function SettingsNavCompact()
const { t, i18n } = useTranslation();
const zh = i18n.language?.toLowerCase().startsWith("zh");
const tr = (value: Lang) => (zh ? value.zh : value.en);
- const groups = useGroups(useHideAdminOnly());
+ const visibility = useSettingsVisibility();
- const groups = useGroups(visibility.hideAdminOnly, visibility.showLearnerOnly);
++ const groups = useGroups(
++ visibility.hideAdminOnly,
++ visibility.showLearnerOnly,
++ visibility.showGuardianOnly,
++ );
const { activeSection, setActiveSection } = useSettings();
const currentValue =
pathname === SETTINGS_HUB_HREF
@@@ -215,8 -203,7 +233,12 @@@ export default function SettingsNav()
} = useSettings();
const [query, setQuery] = useState("");
- const groups = useGroups(useHideAdminOnly());
+ const visibility = useSettingsVisibility();
- const groups = useGroups(visibility.hideAdminOnly, visibility.showLearnerOnly);
++ const groups = useGroups(
++ visibility.hideAdminOnly,
++ visibility.showLearnerOnly,
++ visibility.showGuardianOnly,
++ );
const needle = query.trim().toLowerCase();
const matches = useCallback(
diff --cc web/lib/auth.ts
index 4828417d1,a779c746c..97cbe8be6
--- a/web/lib/auth.ts
+++ b/web/lib/auth.ts
@@@ -14,20 -14,8 +14,22 @@@ export interface AuthStatus
username?: string;
role?: string;
is_admin?: boolean;
++ /** Server-side account preset; null for identities without a local account. */
++ preset?: "standard" | "learner" | "custom" | null;
/** Avatar marker: "", "icon:<name>:<color>", or "img:<version>". */
avatar?: string;
+ learning_policy?: {
+ age_band: string;
+ locked_persona: string;
+ allowed_capabilities: string[];
+ default_capability: string;
+ allowed_surfaces?: string[];
+ reading?: {
+ allow_upload: boolean;
+ material_ids: string[];
+ extensions: string[];
+ };
+ } | null;
}
/**
diff --cc web/lib/guardian-api.ts
index 000000000,1bcdda48d..6f4ebc76f
mode 000000,100644..100644
--- a/web/lib/guardian-api.ts
+++ b/web/lib/guardian-api.ts
@@@ -1,0 -1,41 +1,69 @@@
+ import { apiFetch, apiUrl } from "@/lib/api";
+
+ export interface GuardianRelationship {
+ id: string;
+ learner_user_id: string;
+ learner_username: string;
+ permissions: string[];
+ }
+
+ export interface GuardianReport {
+ learner: { id: string; username: string; disabled: boolean };
- assigned_materials: Array<{ book_id: string; title?: string; permission: string }>;
- grant_summary: { model_count: number; knowledge_base_count: number; skill_count: number };
++ assigned_materials: Array<{
++ book_id: string;
++ title?: string;
++ permission: string;
++ }>;
++ grant_summary: {
++ model_count: number;
++ knowledge_base_count: number;
++ skill_count: number;
++ };
++}
++
++function extractDetail(value: unknown): string | null {
++ if (typeof value !== "object" || value === null || !("detail" in value)) {
++ return null;
++ }
++ const detail = (value as { detail: unknown }).detail;
++ return typeof detail === "string" ? detail : null;
+ }
+
+ async function request<T>(path: string, init?: RequestInit): Promise<T> {
+ const res = await apiFetch(apiUrl(path), init);
- if (!res.ok) throw new Error((await res.json().catch(() => ({}))).detail ?? "Request failed");
- return res.json() as Promise<T>;
++ const data: unknown = await res.json().catch(() => null);
++ if (!res.ok) throw new Error(extractDetail(data) ?? "Request failed");
++ return data as T;
+ }
+
+ export async function listGuardianRelationships(): Promise<GuardianRelationship[]> {
- const data = await request<{ relationships: GuardianRelationship[] }>("/api/v1/multi-user/me/guardianships");
++ const data = await request<{ relationships: GuardianRelationship[] }>(
++ "/api/v1/multi-user/me/guardianships",
++ );
+ return data.relationships;
+ }
+
+ export function getGuardianReport(learnerId: string): Promise<GuardianReport> {
- return request<GuardianReport>(`/api/v1/multi-user/learners/${encodeURIComponent(learnerId)}/guardian-report`);
++ return request<GuardianReport>(
++ `/api/v1/multi-user/learners/${encodeURIComponent(learnerId)}/guardian-report`,
++ );
+ }
+
-export function resetLearnerCredentials(learnerId: string): Promise<void> {
- return request(`/api/v1/multi-user/learners/${encodeURIComponent(learnerId)}/credentials/reset`, { method: "POST" }).then(() => undefined);
++export async function resetLearnerCredentials(learnerId: string): Promise<string> {
++ const data = await request<{ temporary_password: string }>(
++ `/api/v1/multi-user/learners/${encodeURIComponent(learnerId)}/credentials/reset`,
++ { method: "POST" },
++ );
++ return data.temporary_password;
+ }
+
-export function clearGuardianMaterials(learnerId: string): Promise<void> {
- return request(`/api/v1/multi-user/learners/${encodeURIComponent(learnerId)}/materials`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ book_ids: [] }),
- }).then(() => undefined);
++export async function clearGuardianMaterials(learnerId: 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: [] }),
++ },
++ );
+ }
diff --cc web/lib/settings-nav.ts
index e5b5c0b30,99f4c40df..874b5a5b5
--- a/web/lib/settings-nav.ts
+++ b/web/lib/settings-nav.ts
@@@ -20,9 -20,9 +20,10 @@@ import
Palette,
Paperclip,
Search,
++ ShieldCheck,
SlidersHorizontal,
Sparkles,
- ShieldCheck,
+ UserRound,
Wrench,
type LucideIcon,
} from "lucide-react";
@@@ -80,8 -80,6 +81,10 @@@ export interface SettingsCategory
href: string;
/** Leaves listed on the sub-hub page (omitted for direct-leaf categories). */
children?: SettingsLeaf[];
+ /** Shown only when the backend reports an active learner policy. */
+ learnerOnly?: boolean;
++ /** Shown only to authenticated standard users who may act as guardians. */
++ guardianOnly?: boolean;
}
const MODEL_CHILDREN: SettingsLeaf[] = [
@@@ -421,17 -419,16 +424,28 @@@ export const SETTINGS_CATEGORIES: Setti
href: "/settings/agents",
children: AGENT_CHILDREN,
},
+ {
+ key: "learner-profile",
+ learnerOnly: true,
+ label: { zh: "学习档案", en: "Learner profile" },
+ blurb: {
+ zh: "调整年龄、年级与讲解偏好。",
+ en: "Adjust age, grade, and explanation preferences.",
+ },
+ icon: UserRound,
+ href: "/settings/learner-profile",
+ },
+ {
+ key: "guardian",
++ guardianOnly: true,
+ label: { zh: "监护管理", en: "Guardian" },
+ blurb: {
+ zh: "查看已授权学习者与学习材料。",
+ en: "Review authorized learners and learning materials.",
+ },
+ icon: ShieldCheck,
+ href: "/settings/guardian",
+ },
{
key: "memory",
label: { zh: "记忆", en: "Memory" },
diff --cc web/locales/en/app.json
index 5a8161784,125449c60..af93dc06b
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@@ -197,19 -193,6 +197,41 @@@
"Loading conversation": "Loading conversation…",
"Still loading…": "Still loading…",
"Save": "Save",
+ "Learner Profile": "Learner Profile",
+ "Adapt explanations to this learner": "Adapt explanations to this learner",
+ "Failed to load learner profile": "Failed to load learner profile",
+ "Failed to save learner profile": "Failed to save learner profile",
+ "Learner profile": "Learner profile",
+ "Personalize explanations and reading support for your account.": "Personalize explanations and reading support for your account.",
+ "Unable to save profile": "Unable to save profile",
++ "Guardian management": "Guardian management",
++ "Review authorized learners and their approved learning materials.": "Review authorized learners and their approved learning materials.",
++ "Loading guardian relationships…": "Loading guardian relationships…",
++ "No active learner relationships.": "No active learner relationships.",
++ "Loading learner report…": "Loading learner report…",
++ "Approved materials": "Approved materials",
++ "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",
++ "View reports": "View reports",
++ "Reset credentials": "Reset credentials",
++ "Remove approved materials": "Remove approved materials",
++ "Remove materials": "Remove materials",
++ "Removing…": "Removing…",
++ "Reset learner credentials": "Reset learner credentials",
++ "Resetting…": "Resetting…",
++ "Learner credentials were reset.": "Learner credentials were reset.",
++ "Approved materials removed.": "Approved materials removed.",
++ "Temporary password": "Temporary password",
++ "Copy this password now. It will not be shown again.": "Copy this password now. It will not be shown again.",
++ "This changes the learner password and revokes every learner device credential.": "This changes the learner password and revokes every learner device credential.",
++ "This removes every approved material from the learner account.": "This removes every approved material from the learner account.",
+ "Age": "Age",
+ "Grade level": "Grade level",
+ "Curriculum": "Curriculum",
+ "Preferred language": "Preferred language",
+ "Reading level": "Reading level",
+ "Explanation style": "Explanation style",
"Cancel": "Cancel",
"Error": "Error",
"Success": "Success",
diff --cc web/locales/zh/app.json
index 076cced04,d3171771f..616fa90cf
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@@ -197,19 -193,6 +197,41 @@@
"Loading conversation": "加载对话中…",
"Still loading…": "仍在加载中…",
"Save": "保存",
+ "Learner Profile": "学习者档案",
+ "Adapt explanations to this learner": "根据该学习者调整讲解",
+ "Failed to load learner profile": "加载学习者档案失败",
+ "Failed to save learner profile": "保存学习者档案失败",
+ "Learner profile": "学习档案",
+ "Personalize explanations and reading support for your account.": "为当前账号定制讲解与阅读支持。",
+ "Unable to save profile": "无法保存学习档案",
++ "Guardian management": "监护管理",
++ "Review authorized learners and their approved learning materials.": "查看已授权的学习者及其获批学习材料。",
++ "Loading guardian relationships…": "正在加载监护关系…",
++ "No active learner relationships.": "暂无有效的学习者监护关系。",
++ "Loading learner report…": "正在加载学习者报告…",
++ "Approved materials": "获批材料",
++ "Enabled learning resources": "已启用的学习资源",
++ "You are not authorized to view this learner report.": "你无权查看该学习者的报告。",
++ "Manage materials": "管理材料",
++ "View reports": "查看报告",
++ "Reset credentials": "重置凭据",
++ "Remove approved materials": "移除获批材料",
++ "Remove materials": "移除材料",
++ "Removing…": "正在移除…",
++ "Reset learner credentials": "重置学习者凭据",
++ "Resetting…": "正在重置…",
++ "Learner credentials were reset.": "学习者凭据已重置。",
++ "Approved materials removed.": "获批材料已移除。",
++ "Temporary password": "临时密码",
++ "Copy this password now. It will not be shown again.": "请立即复制此密码,之后将不再显示。",
++ "This changes the learner password and revokes every learner device credential.": "这会更改学习者密码,并撤销该学习者的全部设备凭据。",
++ "This removes every approved material from the learner account.": "这会从学习者账号中移除全部获批材料。",
+ "Age": "年龄",
+ "Grade level": "年级",
+ "Curriculum": "课程体系",
+ "Preferred language": "偏好语言",
+ "Reading level": "阅读水平",
+ "Explanation style": "讲解风格",
"Cancel": "取消",
"Error": "错误",
"Success": "成功",
diff --cc web/tests/guardian-management.test.ts
index 000000000,000000000..6a0d1f768
new file mode 100644
--- /dev/null
+++ b/web/tests/guardian-management.test.ts
@@@ -1,0 -1,0 +1,58 @@@
++import assert from "node:assert/strict";
++import { readFileSync } from "node:fs";
++import path from "node:path";
++import test from "node:test";
++
++const readWebFile = (...parts: string[]) =>
++ readFileSync(path.join(process.cwd(), ...parts), "utf8");
++
++const api = readWebFile("lib", "guardian-api.ts");
++const page = readWebFile(
++ "app",
++ "(utility)",
++ "settings",
++ "guardian",
++ "page.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 actions follow each relationship permission", () => {
++ assert.match(page, /can\("view_reports"\)/);
++ assert.match(page, /can\("assign_materials"\)/);
++ assert.match(page, /can\("reset_credentials"\)/);
++ assert.match(page, /<ConfirmDialog/);
++});
++
++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"/);
++ assert.match(nav, /authStatus\.preset === "standard"/);
++ assert.match(nav, /authStatus\.preset === "custom"/);
++});
++
++test("guardian management copy is localized", () => {
++ const en = JSON.parse(readWebFile("locales", "en", "app.json")) as Record<
++ string,
++ string
++ >;
++ const zh = JSON.parse(readWebFile("locales", "zh", "app.json")) as Record<
++ string,
++ string
++ >;
++ for (const key of [
++ "Guardian management",
++ "Approved materials",
++ "Reset learner credentials",
++ "Temporary password",
++ "This changes the learner password and revokes every learner device credential.",
++ ]) {
++ assert.ok(en[key], `missing English key: ${key}`);
++ assert.ok(zh[key], `missing Chinese key: ${key}`);
++ }
++});