Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
355f21b
Passwords also refuse a distinctive word of an institute's name, not …
omerFixesBugs Nov 16, 2026
7016eff
Sprint 1 P1-J plan (docs/plans/sprint-1-p1j-password-hash.md): the ap…
omerFixesBugs Nov 16, 2026
25da8a3
Sprint 1 P2 plan (docs/plans/sprint-1-p2-files.md): institute profile…
omerFixesBugs Nov 16, 2026
995e61e
Test users get phone numbers no other test user of the same database …
omerFixesBugs Nov 16, 2026
356c448
The app login can no longer read users.password_hash (P1-J): SELECT o…
omerFixesBugs Nov 16, 2026
3ca69eb
Every Prisma client leaves users.password_hash out of its reads (P1-J…
omerFixesBugs Nov 16, 2026
30e85f6
Files and the institute profile in the database (P2 task 1): stored_f…
omerFixesBugs Nov 16, 2026
687a83b
CORS_ORIGINS is normalised in env.ts as browsers send Origin (lower-c…
omerFixesBugs Nov 16, 2026
ff8981c
Shared file caps, types and the institute profile schema (P2 task 2):…
omerFixesBugs Nov 16, 2026
917d5eb
The start-up login check also refuses a login with REPLICATION (a rep…
omerFixesBugs Nov 16, 2026
bc6644b
Password login without the hash (P1-J): the API hashes the typed pass…
omerFixesBugs Nov 16, 2026
b0e6315
GET /me/password reads hasPassword from auth_my_password_is_set() (P1…
omerFixesBugs Nov 16, 2026
47fb357
Docs for P1-J: database.md (password_hash not readable by the app, a …
omerFixesBugs Nov 16, 2026
20b29e9
Redis is pinned to one exact version, redis:7.4.11-alpine (the versio…
omerFixesBugs Nov 16, 2026
81bfc26
Docs for the follow-ups: decisions-pending gets the section "Small fo…
omerFixesBugs Nov 16, 2026
9cc9d54
Image processing for uploads (P2 task 3): sharp 0.35.5 (already in th…
omerFixesBugs Nov 16, 2026
b0e010b
FileStore and the per-institute cap (P2 task 4): PostgresFileStore is…
omerFixesBugs Nov 16, 2026
caec9f7
Photo and profile routes (P2 task 5): GET/PUT/DELETE /students/:id/ph…
omerFixesBugs Nov 16, 2026
57cf79f
Web (P2 task 6): Settings → Institute profile (names, EIIN, contact, …
omerFixesBugs Nov 16, 2026
4e4cbb2
Docs for P2 (task 7): docs/files.md, database.md (the three tables an…
omerFixesBugs Nov 16, 2026
724ffb0
The photo dialog's preview URL is made when a file is chosen, not in …
omerFixesBugs Nov 16, 2026
110857d
files.spec: the profile fields by id ("নাম (বাংলা)" is also part of t…
omerFixesBugs Nov 16, 2026
8c3a4f9
After the review (P1-J7): a dedicated login for the password login. j…
omerFixesBugs Nov 16, 2026
72b714b
The password login looks the hash up on its own database login (Login…
omerFixesBugs Nov 16, 2026
06f3236
Docs after the P1-J review: what an injection in an ordinary request …
omerFixesBugs Nov 16, 2026
82f6600
Test phones never wrap and their lock survives races (review of PR #1…
omerFixesBugs Nov 16, 2026
27403c3
The institute-name rule compares passwords and names like the phone r…
omerFixesBugs Nov 16, 2026
7aa31c5
An origin setting with a login, a path, a query or a fragment is no o…
omerFixesBugs Nov 16, 2026
fd6430e
Docs after the review of PR #17: P1-I's title line says it is built h…
omerFixesBugs Nov 16, 2026
9dbee45
P1-J migration after the second review: it first checks that jantrik_…
omerFixesBugs Nov 16, 2026
a980a60
The password login's database login must reach the same database, por…
omerFixesBugs Nov 16, 2026
ff673b8
Docs after the second P1-J review: the server upgrade creates the rol…
omerFixesBugs Nov 16, 2026
13deed2
A file reference is tied to its kind (review R6): UNIQUE (tenant_id, …
omerFixesBugs Nov 16, 2026
cb86722
Uploads hold no database connection while they arrive (review R1): th…
omerFixesBugs Nov 16, 2026
459bcf7
Web after the review: a chosen image is shrunk in the browser to 1600…
omerFixesBugs Nov 16, 2026
944e840
Docs after the review: auth.md (the request pipeline and @OwnTransact…
omerFixesBugs Nov 16, 2026
282c8b6
Review round 2, API: uploads in flight bounded before multer (16 per …
omerFixesBugs Nov 16, 2026
cfd4506
Review round 2, web: the browser asks for the EXIF orientation explic…
omerFixesBugs Nov 16, 2026
73eb83b
Docs for review round 2: auth.md (the upload routes' re-checks, Uploa…
omerFixesBugs Nov 16, 2026
e622e52
The interceptor opens its transaction through an unchecked entry (aro…
omerFixesBugs Nov 16, 2026
3d2c5d5
Review round 3: no upload slot leaks when the client left before Uplo…
omerFixesBugs Nov 16, 2026
de19108
The two new origin tests' development settings also name DATABASE_LOG…
omerFixesBugs Nov 16, 2026
aa0105b
Merge P1-J (#16) into the small follow-ups (#17): the ready resolutio…
omerFixesBugs Nov 16, 2026
b1efceb
Merge remote-tracking branch 'origin/feature/sprint-1-p1j-password-ha…
omerFixesBugs Nov 16, 2026
b5d3697
Merge remote-tracking branch 'origin/feature/sprint-1-p2-files' into …
omerFixesBugs Nov 16, 2026
c857102
Merge remote-tracking branch 'origin/feature/small-followups-after-p1…
omerFixesBugs Nov 16, 2026
9309fa8
Work in progress: a staff guide draft and draft legal texts (terms of…
omerFixesBugs Nov 19, 2026
ed5d56c
Docs only: a plain staff guide draft (signing in, setup, students, gu…
omerFixesBugs Nov 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Docs after the review: auth.md (the request pipeline and @OwnTransact…
…ion), files.md, database.md (kind-bound references), the plan (F1 corrected, Changed after the review R1-R10) and decisions-pending (the same, and the CSV imports as a backlog item)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
omerFixesBugs and claude committed Nov 16, 2026
commit 944e84071ef282e6627df2c42a76aa47c8ae87ae
18 changes: 17 additions & 1 deletion docs/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,8 @@ JwtAuthGuard @Public() skips; verify JWT + session not revoked →
RateLimitGuard per user (authenticated) or per IP
RolesGuard @Roles(...) → current roles from Redis (tenant:{tid}:user:{uid}:roles:v{n})
ModuleGuard @RequireModule(…) → enabled modules from Redis (tenant:{tid}:modules)
TenantContextInterceptor withContext({ tenantId: tid, userId: sub }) around the handler:
TenantContextInterceptor withContext({ tenantId: tid, userId: sub }) around the handler
(RequestTransaction.run; @OwnTransaction routes call it themselves):
- re-checks tenant ACTIVE/TRIAL + active membership (immediate suspension)
- handler runs inside the transaction (services use Db.tx)
- error → rollback; success → commit → afterCommit callbacks
Expand All @@ -284,6 +285,21 @@ TenantContextInterceptor withContext({ tenantId: tid, userId: sub }) around the
- **`@UserScoped()`** runs a route with the user context only. Used by `/auth/*`, so account
routes such as logout work even when the selected tenant is suspended.
- **`@Public()`** routes get no request transaction.
- **`@OwnTransaction()`** routes (sprint 1 P2: the image uploads `PUT /students/:id/photo` and
`PUT /institute/profile/:slot`) get no transaction from `TenantContextInterceptor`, which runs
before a route's own interceptors. Otherwise the transaction, and one of the pool's 10
connections, would be held while multer reads a slow upload and sharp decodes it: on slow 4G a
5 MB photo outlives the 15 s transaction (a 500 every time), and ten of them would hold every
connection and fail all other institutes' requests after the 5 s `maxWait`.
- The guards above still run first (token, rate limits, roles, module).
- The handler reads the body, applies the upload limit and decodes the image without the
database, then calls `RequestTransaction.run(fn)`: the same transaction the interceptor opens
(`withContext` with the same tenant and user, the tenant and membership re-check, `Db.tx`,
rollback on error, afterCommit after commit), just later and short.
- Everything that touches the database goes inside `run`. Nothing outside it may use `Db.tx`
(it throws: no request transaction).
- The CSV imports (student import, device people) still read their uploads inside the request
transaction; they are small (≤ 1–5 MB) and in the backlog to move the same way.

### Writing a service

Expand Down
9 changes: 6 additions & 3 deletions docs/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -525,9 +525,12 @@ Images live in the database ([files.md](files.md), decision S7):
lengths, a 6-digit EIIN, a 5–15 digit phone (optional `+`), e-mail and website shapes, a year
1800–2100, and the three images being different files.
- **`students.photo_file_id`** replaces the never-written `photo_url`.
- **Every reference to a file is a composite foreign key** (`(tenant_id, x) → stored_files
(tenant_id, id)`, `ON DELETE RESTRICT ON UPDATE RESTRICT`) and unique, so a row can only point at
its own institute's file, a file is used in one place, and a file still in use cannot be deleted.
- **Every reference to a file is a composite foreign key with the kind**
(`(tenant_id, x, x_kind) → stored_files (tenant_id, id, kind)`, `ON DELETE RESTRICT ON UPDATE
RESTRICT`) and unique. The kind column is fixed by a CHECK (`students.photo_file_kind` =
`STUDENT_PHOTO`; `institute_profiles.logo_file_kind`, `head_signature_file_kind`,
`seal_file_kind` = `LOGO`, `SIGNATURE`, `SEAL`). So a row can only point at its own institute's
file of the right kind, a file is used in one place, and a file still in use cannot be deleted.
- Isolation, grants, CHECKs and keys: `packages/db/test/files-rls.test.ts`.

## Querying: `withContext`, `withTenant`, `tenantClient`
Expand Down
39 changes: 39 additions & 0 deletions docs/decisions-pending.md
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,45 @@ F11. **The per-institute total is counted, not recomputed**, under the institute

F12. **No institute header or logo on the report card yet.** The profile and images exist for P3 (the admission slip), P8 and P9 (documents); the report card gains only the student photo, as the sprint plan says.

Changed after the review (each code fix with a test that failed first; R3 is checked by Playwright
in CI; R9 and R10 are docs and tests only; details in the plan → "Changed after the review"):

- **R1. Uploads no longer run inside the request transaction** (must-fix). `TenantContextInterceptor`
(a global interceptor) opened the 15 s transaction and took a pool connection before multer read
the body: a 2–5 MB photo on slow 4G took longer than 15 s (a 500 every time), and ten slow
uploads could hold all 10 connections (every other institute failing). The two upload routes
are now `@OwnTransaction()`: the body is read, the upload limit applied and the image decoded
with no connection; then `RequestTransaction.run` (the interceptor's own logic, moved into a
service) opens the same tenant transaction for the short store. The image queue is bounded (8
waiting; more get 503 `IMAGE_BUSY`), and the browser shrinks a chosen image to 1600 px on the
long side (JPEG 0.85 for photos, PNG for the others) before sending, so a phone sends about
300 KB. Test: while a slow body arrives, no session of the app login is idle in a transaction.
- **R2. The code scan also catches Prisma relation fields** (`photoFile`, `logoFile`,
`signatureFile`, `sealFile`, `storedFiles`, `storedFileUsage`, `storedFilesCreated`, the
`profile*` back-relations).
- **R3. The guardian's report card shows the photo** through `/me/children/:id/photo`
(`ReportCardsPrint as="guardian"`); Playwright checks it in the exams spec.
- **R4. The web address's scheme is stored in lower case** (`HTTPS://x` → `https://x`), as the
database CHECK is case-sensitive; it was a 500.
- **R5. The image queue hands a freed slot straight to the next waiter**, so it can never run
three at once.
- **R6. A file reference is tied to its kind in the database.** `stored_files` has
`UNIQUE (tenant_id, id, kind)`; `students.photo_file_kind` (always `STUDENT_PHOTO`) and
`institute_profiles.logo_file_kind`, `head_signature_file_kind`, `seal_file_kind` (always
`LOGO`, `SIGNATURE`, `SEAL`, by CHECK) are part of each foreign key, so a photo column can only
hold a photo, a logo column a logo, and so on.
- **R7. Replacing an image near the cap is allowed** when the total would not grow: `put` takes the
id it replaces (read under the file lock) and counts it.
- **R8. The first image and the first save cannot collide:** the row an image creates is inserted
with `ON CONFLICT DO NOTHING`.
- **R9.** F1 above now says what the code does (a teacher sees photos of their own sections only).
- **R10.** The database tests name the rule that refuses each write; a PNG `eXIf` GPS case was
added to the image tests.

- **For the owner (backlog): the CSV imports read their uploads inside the request transaction
too** (student import up to 5 MB, device people up to 1 MB). Smaller and rarer than photos, so
not changed here; they can move to `@OwnTransaction()` the same way.

Also decided while building:

- The migrations were written by hand (no development database is used in this run) and checked with `prisma migrate diff` against a scratch database: empty.
Expand Down
25 changes: 19 additions & 6 deletions docs/files.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,15 @@ Never the uploaded file. `ImageService` (`apps/api/src/files/image.service.ts`,
into the kind's box, and re-encodes it until it fits the kind's cap;
4. never copies metadata: EXIF (with GPS), ICC, XMP and comments are gone.

At most two images are processed at once per API process.
At most two images are processed at once per API process; at most 8 more wait (more get 503
`IMAGE_BUSY`), and a freed slot goes straight to the next one.

**No database connection while an upload arrives.** The upload routes are `@OwnTransaction()`
([auth.md](auth.md) → Request pipeline): multer reads the body and `ImageService` decodes it
before any transaction is opened; then one short request transaction stores the file and changes
the row. The browser also shrinks a chosen image to 1600 px on the long side before sending
(`apps/web/src/lib/image-shrink.ts`: JPEG 0.85 for photos, PNG otherwise; the original when the
browser cannot decode it or the copy is not smaller), so a phone photo is about 300 KB.

| Kind | Stored as | Cap | Box | Used by |
| ----------------- | --------------------------------- | ------ | --------- | ---------------------------------------- |
Expand All @@ -49,9 +57,13 @@ The caps are in `packages/shared/src/files.ts` (`FILE_LIMITS`) and again in the
so the total always equals the sum of the rows, even with uploads at the same moment.
- Over `FILE_STORAGE_PER_TENANT_MB` (default 1024): 413 `STORAGE_FULL` with `bytesUsed` and
`capBytes`. A per-institute limit set by the platform can come later.
- Code that replaces or clears an image calls `lock()` (or `put`, which takes it) **before**
reading which file a row points at, so two changes of one image cannot both delete or keep the
same old file.
- Code that replaces or clears an image calls `lock()` **before** reading which file a row points
at, so two changes of one image cannot both delete or keep the same old file. A replacement
passes the old id to `put(file, { replaces })`, which counts it: a same-size replacement is
never refused near the cap.
- **Each reference is tied to its kind:** `UNIQUE (tenant_id, id, kind)` on `stored_files`, and a
fixed kind column in each foreign key (`students.photo_file_kind` is always `STUDENT_PHOTO`,
`institute_profiles.logo_file_kind` `LOGO`, and so on), so a logo can never be used as a photo.

## Routes

Expand All @@ -72,7 +84,7 @@ Entity routes only; there is no `/files/:id`.
- Uploads are `multipart/form-data` with one field, `file`, at most 5 MB (`UPLOAD_MAX_BYTES`;
bigger: 413), at most 60 per person per 10 minutes (429).
- Errors: 400 `FILE_REQUIRED`, 422 `IMAGE_INVALID`, 422 `IMAGE_TOO_BIG`, 422 `IMAGE_CANNOT_SHRINK`,
413 `STORAGE_FULL`, 409 `DEACTIVATED`.
413 `STORAGE_FULL`, 409 `DEACTIVATED`, 503 `IMAGE_BUSY`.
- Answers carry a strong `ETag` (the SHA-256 of the stored bytes) and
`Cache-Control: private, no-cache`; a matching `If-None-Match` gets 304 without the bytes being
read.
Expand All @@ -84,7 +96,8 @@ Entity routes only; there is no `/files/:id`.
- Images need the bearer token, so `<img src>` cannot load them: `useAuthedImage(path, fileId)`
(`apps/web/src/lib/authed-image.ts`) fetches with `AuthClient.download` and returns an object
URL, shared by every component and cached per path and file id (a replaced image has a new id).
- `StudentAvatar` / `StudentPhoto` (`components/student-photo.tsx`) show a student's photo. Lists
- `StudentAvatar` / `StudentPhoto` (`components/student-photo.tsx`) show a student's photo, from
the staff route or, with `as="guardian"`, the guardian's own (the guardian's report card). Lists
keep initials (decision F2): fifty photos would not fit the 3 s budget on slow 4G.
- API types carry `photoId` (the stored file's id or null), never a URL.

Expand Down
41 changes: 38 additions & 3 deletions docs/plans/sprint-1-p2-files.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,10 @@ this branch's migrations are `20261116100000_*` and later, so the order holds ei

## Decisions taken during the run (F1–F12, the owner reviews them with the PR)

- **F1. Who sees what.** Student photo: the roles that may read students (`OWNER`, `ADMIN`,
`TEACHER`), for every student, like name and code (a teacher sees basics of every student).
Guardians: their own children only. Logo: every member of the institute (guardians too).
- **F1. Who sees what.** A student's photo is part of the full record, as on the student's page
(the basic view for a teacher of another section already left it out): `OWNER` and `ADMIN` for
every student, a `TEACHER` for the students of their current sections, guardians for their own
children only; anyone else gets 404. Logo: every member of the institute (guardians too).
Head's signature and seal: `OWNER` and `ADMIN` only (they can be misused on forged papers;
printing roles widen in P8/P9). Profile fields: `OWNER` and `ADMIN` (the settings page).
- **F2. Lists keep initials.** The student list, the board and the other lists do not load photos
Expand Down Expand Up @@ -363,6 +364,40 @@ services and shared types (F3).
- Gates: lint, typecheck, format, tests package by package, build, size budget; Playwright in CI.
- Review subagent (database, uploads), fixes, PR.

## Changed after the review (2026-11-16)

- **R1. Uploads no longer run inside the request transaction** (must-fix). `TenantContextInterceptor`
(a global interceptor) opened the 15 s transaction and took a pool connection before multer read
the body: a 2–5 MB photo on slow 4G took longer than 15 s (a 500 every time), and ten slow
uploads could hold all 10 connections (every other institute failing). The two upload routes
are now `@OwnTransaction()`: the body is read, the upload limit applied and the image decoded
with no connection; then `RequestTransaction.run` (the interceptor's own logic, moved into a
service) opens the same tenant transaction for the short store. The image queue is bounded (8
waiting; more get 503 `IMAGE_BUSY`), and the browser shrinks a chosen image to 1600 px on the
long side (JPEG 0.85 for photos, PNG for the others) before sending, so a phone sends about
300 KB. Test: while a slow body arrives, no session of the app login is idle in a transaction.
- **R2. The code scan also catches Prisma relation fields** (`photoFile`, `logoFile`,
`signatureFile`, `sealFile`, `storedFiles`, `storedFileUsage`, `storedFilesCreated`, the
`profile*` back-relations).
- **R3. The guardian's report card shows the photo** through `/me/children/:id/photo`
(`ReportCardsPrint as="guardian"`); Playwright checks it in the exams spec.
- **R4. The web address's scheme is stored in lower case** (`HTTPS://x` → `https://x`), as the
database CHECK is case-sensitive; it was a 500.
- **R5. The image queue hands a freed slot straight to the next waiter**, so it can never run
three at once.
- **R6. A file reference is tied to its kind in the database.** `stored_files` has
`UNIQUE (tenant_id, id, kind)`; `students.photo_file_kind` (always `STUDENT_PHOTO`) and
`institute_profiles.logo_file_kind`, `head_signature_file_kind`, `seal_file_kind` (always
`LOGO`, `SIGNATURE`, `SEAL`, by CHECK) are part of each foreign key, so a photo column can only
hold a photo, a logo column a logo, and so on.
- **R7. Replacing an image near the cap is allowed** when the total would not grow: `put` takes the
id it replaces (read under the file lock) and counts it.
- **R8. The first image and the first save cannot collide:** the row an image creates is inserted
with `ON CONFLICT DO NOTHING`.
- **R9.** F1 above now says what the code does (a teacher sees photos of their own sections only).
- **R10.** The database tests name the rule that refuses each write; a PNG `eXIf` GPS case was
added to the image tests.

## Risks

- **Backups grow** (about 100 MB per 2 000 photos). `pg_dump` custom format does not compress
Expand Down