forge
Explore
Log in

Don't you dare go Hollow

Multi-school model in the README, builder seed in compose

Browse files at this commit

78fe8c7245b69dab3536a2d56cbc2880759a70e2Ahmet Kaan GümüşParent: 933e1e3
  • docs
    • multi-school model in the README, builder seed in compose
Show full message
📝 docs: multi-school model in the README, builder seed in compose

New `## Multi-school (SaaS)` section; the auth prose, quick tour, first-admin
bootstrap and layout follow the per-school databases and the builder API.
README.mdmodified+98 -23
@@ -271,11 +271,63 @@ podman build -t hezarfen-backend .
271271 podman run -d --name hezarfen -p 8080:8080 -v hezarfen-data:/data hezarfen-backend
272272 ```
273273
274+## Multi-school (SaaS)
275+
276+One deployment serves many schools. Every school gets a SurrealDB **database**
277+of its own inside the one namespace (`DB_NAMESPACE`, default `hezarfen`),
278+named by its slug, next to a **control** database (`DB_DATABASE`, default
279+`control`) that holds the school registry, the builder accounts and the shared
280+rate-limit window. Isolation is the store's, not the handlers': a school
281+database sees only its own rows, so no query carries a `WHERE school = ...`
282+somebody could forget.
283+
284+**Slugs.** 2-32 characters of `a-z`, `0-9` and `-`, starting with a letter or
285+digit (`MIN_SLUG_LEN`/`MAX_SLUG_LEN`); `builder` and `control` are reserved and
286+refused. A slug names the school's database, its blob directory and its cookie
287+prefix, so it is immutable once taken — a rename changes the display name only.
288+
289+**Cookies.** A school session is `session=<slug>.<token>`, the vendor's is
290+`session=builder.<token>`, split at the *first* dot so a token can never be
291+read as a slug. Neither cookie is accepted on the other's surface (`401` both
292+ways), and a cookie with no dot names no school and is refused everywhere.
293+
294+**How a request finds its school.** Every school-scoped handler takes the
295+tenancy `State` (`web::tenant_state`), which reads the cookie's prefix, looks
296+the school up in the registry, and hands the handler a connection pinned to
297+that database plus `FILES_PATH/<slug>/` as its blob directory. The AI bridge is
298+the one caller with no cookie: it injects the school as a request extension
299+instead, which nothing outside the process can forge. In-process state is keyed
300+by school too — the exam presence map and the whiteboard hub — so two schools
301+never share a room.
302+
303+**Suspension is immediate and total** for a school's own users: the registry
304+row is read on every request, so the next call after the switch answers `403`,
305+live session or not, `POST /auth/login` included. The builder surface keeps
306+working on a suspended school — that is how it comes back — except
307+`POST /schools/{slug}/enter`, which is one of the school's own doors.
308+
309+**The builder lifecycle.** `BUILDER_USERNAME` + `BUILDER_PASSWORD` seed the
310+operator account at boot (both or neither; half a pair aborts startup, and an
311+existing account is never rewritten). From there: `POST /builder/login` →
312+`POST /schools` (registry row, database, schema and the school's first admin —
313+one call or none of it) → that admin logs in at `POST /auth/login` naming the
314+school → `PATCH /schools/{slug}` renames, suspends or resumes →
315+`POST /schools/{slug}/admin-password` re-keys a locked-out admin and revokes
316+every session it held → `POST /schools/{slug}/enter` mints an ordinary school
317+session for one of its admins (support access, no builder power inside) →
318+`DELETE /schools/{slug}` destroys the school's database, its registry row and
319+its uploaded files. Irreversible on purpose: suspension is the reversible door.
320+
321+**AI frames name the school.** One AI service serves the whole deployment, so
322+every `hab/2` frame carries a `school` field — see "AI bridge (QUIC)".
323+
274324 ## Auth model
275325
276326 Login sets an `HttpOnly`, `SameSite=Lax` `session` cookie (7-day expiry, stored
277-server-side). Send it back on later requests. Every endpoint below whose `Auth`
278-column names a role requires a valid session; the ones marked `no` (`/health`,
327+server-side); its value is `<school-slug>.<token>`, so `POST /auth/login` and
328+`POST /auth/register` name the school alongside the username (see
329+"Multi-school (SaaS)"). Send the cookie back on later requests. Every endpoint
330+below whose `Auth` column names a role requires a valid session; the ones marked `no` (`/health`,
279331 the docs pages, `register` / `login` / `logout`) don't (`logout` is idempotent —
280332 it clears the session if one is present). Set `COOKIE_SECURE=true` when serving
281333 behind TLS to add the cookie's `Secure` attribute.
@@ -705,19 +757,22 @@ still left exactly as they stand.
705757 ### Bootstrapping the first admin
706758
707759 There is no self-service path to `admin` — registration always creates a
708-`student`. The first admin comes from the startup seed: set both
760+`student`. A school's first admin is created *with* the school: the builder
761+posts `POST /schools` with `{slug, name, admin_username, admin_password}` and
762+that account lands inside the new school's database holding `admin`. The
763+builder itself comes from the startup seed: set both
709764
710765 ```sh
711-ADMIN_USERNAME=admin
712-ADMIN_PASSWORD=admin123 # local-dev default used by compose.yaml; change it
766+BUILDER_USERNAME=builder
767+BUILDER_PASSWORD=builder123 # local-dev default used by compose.yaml; change it
713768 ```
714769
715-and on boot the account is created with the `admin` role **if the username
716-doesn't exist yet**. The seed is idempotent and deliberately conservative: it
717-never promotes or rewrites an existing account (if the name is taken by a
718-non-admin it logs a warning and leaves it alone — promoting someone else's
719-account would be an escalation). Setting only one of the two variables aborts
720-startup. `compose.yaml` ships with the credentials above for local dev.
770+and on boot the builder account is created in the control database **if the
771+username doesn't exist yet**. The seed is idempotent and deliberately
772+conservative: it never rewrites an existing account, so changing the password
773+here does not re-key a live builder. Setting only one of the two aborts
774+startup. `compose.yaml` ships with the credentials above for local dev. See
775+"Multi-school (SaaS)" for the rest of the lifecycle.
721776
722777 That admin can then promote everyone else through `PATCH /users/{id}/role`.
723778
@@ -727,15 +782,17 @@ answers `409` — including when two admins demote each other at the same
727782 instant, since that guard is serialized school-wide rather than left to the
728783 database (which conflict-checks neither a cross-record count nor a read).
729784
730-Manual fallback (the recovery path if the seeded name was squatted, or if an
731-older build already emptied the admin set): run
785+A locked-out school is the builder's `POST /schools/{slug}/admin-password`,
786+which re-keys an admin that still exists. Manual fallback (the recovery path
787+if an older build already emptied a school's admin set): run
732788
733789 ```surql
734790 UPDATE user SET role = 'admin' WHERE username = 'ada';
735791 ```
736792
737-against the SurrealDB server — e.g.
738-`surreal sql --conn ws://127.0.0.1:8000 --user root --pass root --ns hezarfen --db hezarfen`
793+against the SurrealDB server, with `--db` naming the **school's** database (its
794+slug), not the control one — e.g.
795+`surreal sql --conn ws://127.0.0.1:8000 --user root --pass root --ns hezarfen --db demo`
739796 (in the container setup, `podman exec -it hezarfen-surrealdb /surreal sql ...`).
740797
741798 ## Endpoints
@@ -1221,8 +1278,8 @@ future. Names allow unicode; usernames are strict: lowercase letters and
12211278 digits plus non-consecutive interior `.`, `_`, `-` separators, starting and
12221279 ending with a letter or digit (3–32 chars). Staff-looking names (`admin`,
12231280 `administrator`, `root`, `support`, `system`, `moderator`, `staff`) are
1224-rejected at `/auth/register` only — the `ADMIN_USERNAME` bootstrap may still
1225-seed them. `display_name` (≤ 50) and `bio` (≤ 500) ride the same two patches
1281+rejected at `/auth/register` only — the admin account a builder names when
1282+creating a school may still take one. `display_name` (≤ 50) and `bio` (≤ 500) ride the same two patches
12261283 under the same rules, `""` clearing either (see "User profiles & avatars").
12271284 UI preferences (`theme`: `light`/`dark`, `language`: `tr`/`en`,
12281285 `palette_color`: an accent color as `#` plus exactly 6 hex digits) ride on the
@@ -1888,9 +1945,10 @@ in the same instant is an accepted race; see `## Concurrency model`.
18881945 What stays fixed is deliberate too: the four roles, the `0`–`100` mark scale,
18891946 validation bounds, and the UTC time policy are invariants, not preferences
18901947 (rename role labels in the frontend if a school says "principal" instead of
1891-"manager"). Deployment knobs (ports, rate limits, admin seed, CORS) remain
1892-environment variables — the model is **one school per deployment**, which
1893-keeps every school's data physically isolated.
1948+"manager"). Deployment knobs (ports, rate limits, the builder seed, CORS) remain
1949+environment variables — they belong to the deployment, not to a school. One
1950+deployment serves many schools, each in its own database (see "Multi-school
1951+(SaaS)"), which keeps every school's data physically isolated.
18941952
18951953 ## Food program: menus, dishes, bookings, attendance & the ledger
18961954
@@ -3426,11 +3484,14 @@ non-empty and contain none of `/ \ ? # %`.
34263484 BASE=http://127.0.0.1:8080
34273485 JAR=/tmp/hz.cookies
34283486
3487+# SCHOOL is the slug a builder gave this school (see "Multi-school (SaaS)").
3488+SCHOOL=demo
3489+
34293490 curl -s $BASE/auth/register -H 'content-type: application/json' \
3430- -d '{"username":"ali","password":"secret1"}'
3491+ -d '{"school":"'$SCHOOL'","username":"ali","password":"secret1"}'
34313492
34323493 curl -s -c $JAR $BASE/auth/login -H 'content-type: application/json' \
3433- -d '{"username":"ali","password":"secret1"}'
3494+ -d '{"school":"'$SCHOOL'","username":"ali","password":"secret1"}'
34343495
34353496 # notes
34363497 curl -s -b $JAR $BASE/notes -H 'content-type: application/json' \
@@ -4452,6 +4513,10 @@ src/
44524513 tls.rs listener certificate (PEM or self-signed) + fingerprint
44534514 error.rs AiError
44544515 chat.rs the `chat.reply` payload contract (ChatRequestPayload/ChatReplyPayload)
4516+ rag.rs the `rag.index` payload contract + spawn_index: a course note
4517+ changed, so its stored output is refreshed in a background task
4518+ api.rs AI_API_ALLOWLIST: the exact REST paths an AI service may read
4519+ (deny-by-default, segment-for-segment, no wildcard tail)
44554520 domain/ validated newtypes + entities (derive SurrealValue),
44564521 each owning its persistence
44574522 user.rs UserId · Username · Password · PasswordHash · User (has role)
@@ -4470,6 +4535,8 @@ src/
44704535 one transaction, for children with a deterministic id
44714536 text_fold.rs case- and diacritic-insensitive folding for search, shared by
44724537 the Rust needle and the SurrealQL column (Turkish İ/ı, ü, ö…)
4538+ page.rs PagedList: one paged SELECT — the window and its `total`, both
4539+ done by the database rather than by slicing a full scan
44734540 session.rs SessionId · SessionToken · Session (7-day expiry)
44744541 builder.rs BuilderId · Builder · BuilderSession: the deployment operator
44754542 who creates and suspends schools, in the control database
@@ -4483,6 +4550,8 @@ src/
44834550 course_note.rs CourseNoteId · CourseNoteTitle · CourseNoteContent · CourseNote
44844551 course_note_file.rs CourseNoteFileId · CourseNoteFile (metadata row; blob on
44854552 disk under FILES_PATH; FileName/FileContentType shared with note_file.rs)
4553+ rag_output.rs RagOutputId · RagOutput (what an AI service produced for a
4554+ course note; derived, disposable, cascaded from note and file)
44864555 course_session.rs CourseSessionId · SessionTopic · CourseSession (a course's lesson)
44874556 session_attendance.rs SessionAttendanceId · SessionAttendance (roll call; one row per session+user)
44884557 work_entry.rs WorkEntryId · WorkEntry (staff stint; one open per user by construction)
@@ -4592,6 +4661,10 @@ src/
45924661 caller's school from the `<slug>.<token>` cookie, so every
45934662 handler that imports it is school-scoped by construction
45944663 (TenantExt · SchoolSlug · split_cookie)
4664+ builder.rs the vendor surface: /builder/login|logout|me and /schools/*
4665+ (create · list · rename/suspend · delete · admin-password · enter)
4666+ image.rs the halves every image upload shares: the `file` part under the
4667+ raster allowlist and the school's size cap, and the blob-first write
45954668 extractor.rs CurrentUser · RequireTeacher · RequireManager · RequireAdmin
45964669 · RequireBuilder (the control-database principal)
45974670 dto.rs shared UserResponse · CourseResponse · ExamResponse · SessionResponse schemas
@@ -4605,7 +4678,9 @@ src/
46054678 etag.rs conditional-GET middleware: ETag over a 200 JSON body,
46064679 If-None-Match → 304 (GET only; SSE and blobs pass through)
46074680 auth.rs users.rs notes.rs messages.rs events.rs appointments.rs
4608- courses.rs course_notes.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs
4681+ courses.rs course_notes.rs subjects.rs sessions.rs homework.rs questions.rs
4682+ exams/ mod.rs (exam CRUD + grading) · questions.rs · attempts.rs ·
4683+ images.rs · review.rs (prior sittings)
46094684 bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs
46104685 settings.rs terms.rs meals.rs payments.rs ai.rs chatbot.rs
46114686 boards.rs classes.rs
compose.yamlmodified+8 -5
@@ -42,13 +42,16 @@ services:
4242 DB_USER: root
4343 DB_PASS: root
4444 DB_NAMESPACE: hezarfen
45- DB_DATABASE: hezarfen
45+ # The control database: the school registry + the builder accounts. Each
46+ # school lives in a database of its own, named by its slug.
47+ DB_DATABASE: control
4648 FILES_PATH: /data/files
4749 RUST_LOG: info,hezarfen_backend=debug
48- # First-boot admin seed: created once if the username doesn't exist yet.
49- # Local-dev credentials — change or remove before exposing this anywhere.
50- ADMIN_USERNAME: admin
51- ADMIN_PASSWORD: admin123
50+ # First-boot builder seed: the operator who creates and suspends schools,
51+ # created once if the username doesn't exist yet. Local-dev credentials —
52+ # change or remove before exposing this anywhere.
53+ BUILDER_USERNAME: builder
54+ BUILDER_PASSWORD: builder123
5255 # Production knobs — uncomment as needed (see .env.example for docs):
5356 # COOKIE_SECURE: "true"
5457 # CORS_ALLOWED_ORIGINS: https://app.example.com
src/lib.rsmodified+1 -1
@@ -44,7 +44,7 @@ use crate::state::AppState;
4444 (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /limits` publishes every fixed bound the API enforces — field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) — so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. Two refusals split that contract: every JSON-bodied operation answers `422` when the request never became the type the handler asked for (a wrong-typed field, a missing required one), and that one is a plain-text deserializer diagnostic rather than the `{error}` envelope, so it is read by a human and not parsed by a client; `400` carries the usual `{error}` and means either non-JSON bytes or a well-typed value that broke a rule published here. Multipart upload routes have no JSON body and so answer `400`, never `422`. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off). Those tiers are per client; a server whose client table is saturated by a flood meters otherwise-unknown callers against one shared budget instead, so an unfamiliar client can briefly see a `429` it did not itself earn — always with a `Retry-After`, never longer than the window"),
4545 (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/2`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Every frame in either direction names the school it belongs to (`school`, the slug), so one fleet of services serves every school on the deployment and a read is answered out of that school's own database — an unknown slug is `unknown_school`, a suspended one `school_suspended`. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"),
4646 (name = "builder", description = "The vendor surface: one deployment, many schools. A **builder** is the operator who owns the deployment — not a user of any school, and holding no role in one. It logs in at `POST /builder/login` and gets a `session` cookie prefixed `builder.` instead of a school slug; that cookie works here and is `401` everywhere else, exactly as a school cookie is `401` here. `POST /schools` creates a school's database, schema and first admin in one call; `PATCH /schools/{slug}` renames it or flips it between `active` and `suspended` (a suspension is immediate and total for that school's users — every request including login answers `403`, live session or not); `DELETE /schools/{slug}` destroys its data and its uploaded files for good. `POST /schools/{slug}/admin-password` is the lockout fix: it re-keys a named admin of that school and revokes every session that account held. `POST /schools/{slug}/enter` mints an ordinary school session for one of its admins (support access) — the only route here refused on a suspended school, so a suspension really does close every door into it."),
47- (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"),
47+ (name = "auth", description = "Registration, login, session lifecycle. Both bodies name the **school**: `{school, username, password}`, since one deployment serves many schools and a username identifies an account only inside one of them; login sets a `session` cookie valued `<slug>.<token>` (see the `builder` tag). `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"),
4848 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),
4949 (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),
5050 (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`). Every authenticated role keeps notes, `parent` included: a note is private own-scoped data with no other reader, and the routes carry **no role bar at all** — ownership is the whole authorization, so nobody but the owner ever reaches a note or its files (a stranger's id is a `404`, never a `403`). That is deliberate and it is the fix for a real defect: while these routes required `student`, a demotion to `parent` locked the owner out of their own notes for good, and since nothing else in the crate reads a note and no route cascades one, the rows and their on-disk blobs became unreachable and undeletable by everybody. Own-scoped personal data is not confiscated by a role change"),