Profile Management — Technical Documentation
Feature Owner: clydetims (Clyde Ador)
Module: User Profile Management (Identity)
Date: 2026-10-09
Branch set covered: PR #890 — feat/profile-management-01 (commits 8dae2fb0 → 59d23f57, incl. a90a3cfe "fix(profile): address profile management blockers, race conditions, and typing errors")
EXECUTIVE SUMMARY
What is this feature?
Self-service profile management. A signed-in user can edit the three attributes they own — full name, profile image (avatar), and password — from a single reusable ProfileModal, and sees email, role and status read-only.
Every change is durably written to both stores the app renders from and is reflected immediately in the header/user menu without a page reload.
The feature replaces dead or placeholder account settings: previously the name/avatar came from OAuth metadata the user could not correct, the Settings page rendered controls that recorded nothing, and there was no supported in-app way to rotate a password.
Why does it matter?
Users can fix their own identity (a misspelt name, an outdated avatar) instead of contacting support or accepting a wrong one forever.
Password rotation is a first-class, protected flow; a stolen session token alone is no longer enough to take over an account (current password required).
Cross-store consistency is enforced:
app_users(what the forum, groups, admin and analytics read) andauth.usersmetadata (whatuseUser()/the header render) can no longer drift the way a "removed" avatar used to reappear in the header.
What's the MVP scope?
Included:
components/auth/ProfileModal.tsx— reusable modal (avatar, full name, email read-only, password), mounted inUserButtonand/learner/settings.GET /api/user/profile— the caller's own durable profile details.PATCH /api/user/profile— updatefullNameand/orremoveImage.POST /api/user/profile/avatar— multipart avatar upload (three-layer validation).POST /api/user/password— password change verified against the current password, with explicit re-auth and cross-device sign-out.lib/schemas/profile.schema.ts— single source of truth for client + server validation.lib/user/profile.server.ts— dual-store read/write service with compensation rollback.SessionProvider.refreshUser— republishes freshauth.usersmetadata touseUser()consumers after a save.app/learner/settings/page.tsx— working, persisted theme/language/notification controls plus the Profile entry point.
Excluded:
Changing email, role, status, or agency membership (deliberately read-only — they require email confirmation or an admin action); account deletion (Danger Zone placeholder only); app-wide application of theme/language choices (recorded and persisted, applied later).
USER PAIN POINT & SOLUTION
Current State (Without Feature)
Identity is imported from the OAuth provider/Supabase Auth metadata with no application surface to correct it.
The header avatar and name read user_metadata; the durable app_users row is synced by DB triggers that mirror (but cannot author) values.
A "removed" avatar cleared from metadata could resurrect in the header because the mirror trigger uses COALESCE(v_image, profile_image_url), and the persisted session cookie carried pre-save claims that clobbered fresh reads on reload.
The Settings page had switches/selects with no handler, so nothing was saved; the "Change Password" action had no implementation and the password-reset flow needed a recovery code.
Pain Point
Emotional:
Users feel locked out of their own identity — their name and photo belong to whoever synced them, and mistakes are permanent.
Functional:
A user cannot fix a typo in their name, set their own avatar, or change/rotate their password in-app. Controls that look interactive silently do nothing. A password breach therefore cannot be remediated in-product, and a hijacked session grants password change (and permanent lockout) to the attacker.
Business Impact:
Stale/mistaken identities degrade community trust and personalization; the inability to rotate a password is a standing security gap; each correction becomes a support ticket.
Future State (With Feature)
Users manage their own identity.
One modal reads the durable app_users values and writes both stores in a safe order, then calls refreshUser() so the header name/avatar update instantly.
Password changes verify the current password, reestablish the caller's own session with the new password, and sign other devices out — with an explicit sign-out fallback if re-auth fails.
Marketing Hook
"Your identity, your control — your name, your photo, your password, in your hands."
4D FRAMEWORK MAPPING
Diagnose
Identified that profile identity had two sources of truth (app_users vs auth.users metadata) whose mirroring could not author values, that the stored session could republish stale claims after a metadata write, and that the settings surface was non-functional.
Each blocker was reproduced (removed avatar "reappearing", race on reload, typing errors) before being fixed.
Design
A single reusable modal fed by one read route; one schema module shared by client and server so an inline error can never disagree with the API; a deliberate two-write order (metadata first, then the authoritative app_users row) with best-effort compensation rollback; a three-layer avatar validation chain plus a Content-Length pre-check on a public bucket.
Develop
Implemented the routes, the profile.server.ts service, the shared Zod schemas, the SessionProvider.refreshUser reconcile, and hardened the avatar upload URL path.
Locked the security claims with route-level and component-level Jest suites covering auth-before-read, owner-scoped writes, read-only-column injection, metadata merge semantics, multi-device password behavior, and stale-response races.
Deliver
Three authenticated write routes + one read route, a reusable modal mounted in the header and Settings, immediate header propagation after saves, and regression suites:
tests/api/user-profile.test.tstests/components/ProfileModal.test.tsxtests/components/UserButtonProfile.test.tsxtests/unit/profile.schema.test.ts
USER FLOWS
Entry Point
Global header
UserButtondrop-down → Profile (components/auth/UserButton.tsx:93).Settings page → Profile Settings card → Manage Profile (
app/learner/settings/page.tsx:121).Settings → Privacy & Security → Change Password opens the same modal (
app/learner/settings/page.tsx:234).
Success Criteria
The modal shows the durable
app_usersvalues, not the cookie's possibly-stale claims.Saving a name updates the header name immediately (no reload).
Uploading/removing an avatar updates the header immediately and never leaves the user without an avatar on failure.
A password change requires the current password, revokes other sessions, and keeps this device signed in (or signs it out explicitly).
No user-supplied identifier can address another account, and no payload can smuggle a read-only column.
Main Flow (Happy Path)
Load Profile
User opens the modal →
loadProfilerunsGET /api/user/profilewithcache: "no-store".Route authenticates, resolves the auth id from the session cookie, reads the row by
.eq("clerk_id", id), maps toProfileDetails.Modal fills the avatar and name field; email, role and status are shown read-only.
Edit Full Name
User edits the name → client validates with the same
profileNameSchemathe route uses.Submit
PATCH /api/user/profile { fullName }.Route writes name to
auth.usersmetadata first (fires the mirror trigger where it exists), then writesapp_users.nameas the authoritative value.Modal stores the refreshed profile, toasts "Profile updated", calls
refreshUser()→ header re-resolves the user from the network.
Change / Remove Avatar
User picks a file (PNG/JPG/GIF/WEBP, ≤5 MB) →
POST /api/user/profile/avatar(multipart fieldavatar).Route validates declared metadata, then
validateRasterImageUpload(SVG rejected), then magic-byte sniff; uploads topublic-assets/avatars/{authUserId}/avatar_<timestamp>.<ext>.applyProfileChangescommits the new URL to metadata +app_users; only then is the previous managed object deleted.Modal toasts and calls
refreshUser(). Remove image follows the same path viaPATCH { removeImage: true }, sendingavatar_url: nullso GoTrue actually clears the key.
Change Password
User fills current/new/confirm and submits
POST /api/user/password.Route authenticates and rejects provider-managed accounts; schema rejects weak/mismatched/reused passwords.
Current password is verified with a throwaway anon client (
persistSession: false) so the live session cookies are untouched.admin.updateUserByIdwrites the new password (revokes every session).Modal re-authenticates this device with the new password → keeps the session; on re-auth failure it signs the user out explicitly.
Edge Cases
Scenario | Behavior |
|---|---|
Profile row missing (auth user provisioned before triggers) |
|
Suspended account |
|
Reopening the modal quickly / stale load response |
|
Double-click / Enter twice in one tick | In-flight guard refs ( |
Removed avatar "reappearing" in header | Metadata patch sends |
|
|
New avatar saved but metadata/row commit fails | Route deletes the freshly uploaded object; the previous avatar stays |
Removing a third-party (OAuth) avatar / foreign object |
|
OAuth account trying to change password | Returned 400 "This account signs in through a third-party provider…" (email presence is NOT the test — identities are) |
Wrong current password | 400 "Your current password is incorrect." — new password never written |
| Explicit |
Oversized avatar / oversized | 400 with |
Avatar bytes are not really an image | 400 "That file does not contain a valid image." |
Decision Points
IF the route cannot authenticate (missing/invalid session) THEN 401 before any query.ELSE IF the account is suspended THEN 403 `ACCOUNT_SUSPENDED`.ELSE IF schema validation fails THEN 400 `VALIDATION_ERROR` with field-level `details`.ELSE IF this is a password change AND the account is provider-managed THEN 400 third-party message.ELSE IF the current password does not verify THEN 400 — no write.ELSE apply metadata first; IF the metadata write fails THEN return the mapped error (nothing durable was written).ELSE write `app_users`; IF the row write fails THEN compensate the metadata write (best-effort) and return the error.ELSE delete managed-origin stale avatar objects (best-effort) and return the refreshed profile.
INFORMATION ARCHITECTURE
Primary Information (Always Visible)
Current avatar (or initials fallback), editable full name, read-only email with "contact an administrator" hint, and the change-password form.
Secondary Information
Read-only role/status context (returned by ProfileDetails, shown so users understand why they are not editable); password complexity requirements inline.
Tertiary Information (Hidden Until Needed)
Load error state with a "Try again" retry button ("hidden" unless the initial GET fails); the raw file-input control (visually hidden, triggered by "Change photo").
Actions
Primary CTA
"Save changes" (name form), "Change photo" (avatar), and "Change password" (password form).
Secondary Actions
"Remove" (clears the avatar when one exists), "Try again" (after a load failure), and signing out (handled by the surrounding UserButton).
WIREFRAMES
Key Screens
Profile Modal
ProfileModal — opened over any page.
Purpose: Manage profile image, name and password in one place.
Components: Dialog, Avatar, Button, PasswordField, PasswordRequirements, FormError, Separator, Input.
┌────────────────────────────────────────────────┐│ Profile ││ Manage your profile image, name and password. ││ ││ (Avatar 64px) [Change photo] [Remove] ││ PNG, JPG, GIF or WebP. ≤5MB ││ ────────────────────────────────────────────── ││ Full name ││ [________________________ Ada Lovelace ______] ││ Email ││ [ada@example.com ] (read-only) ││ Contact an administrator to change the email… ││ [Save changes] ││ ────────────────────────────────────────────── ││ Change password ││ You'll need your current password to confirm. ││ Current password [________________] ││ New password [________________] ││ ✓ At least 8 characters … ││ Confirm new pass [________________] ││ [Change password]│└────────────────────────────────────────────────┘
Settings Page (learner)
/learner/settings
Purpose: Central account settings hub (profile, notifications, privacy, appearance).
Components: Card, ProfileModal, Switch, Select.
┌──────────────────┬──────────────────────────┐│ Profile Settings │ Notifications ││ Update your image│ Quest Updates [on] ││ name and password│ Achievement Notif. [on] ││ [Manage Profile] │ Achievement Emails [on] ││ │ Leaderboard Updates[on] ││ │ Learning Reminders [on] │├──────────────────┼──────────────────────────┤│ Privacy & Security ││ Public Profile [off] Data Collection [off]││ [Change Password] │├──────────────────┼──────────────────────────┤│ Appearance ││ Theme [Light ▼] Language [English ▼] ││ Animations [on] Sound Effects [on] │└──────────────────┴──────────────────────────┘│ Danger Zone (Delete Account — placeholder) │
Modal / Detail Views
The modal is a single scrollable dialog (max-h-[90vh] overflow-y-auto). Avatar/file controls are inline. No separate detail views.
Empty State
No profile row → "We couldn't find your profile." (Route 404).
Name fallback is "User"; initials fallback renders "U". Upload/Remove is hidden when there is no image.
Loading State
Loader2 spinner + "Loading your profile…" while the initial GET is in flight.
Submit buttons swap label to "Saving…", "Uploading…", "Updating…" and are disabled while any write is in flight (isBusy).
Error State
Inline FormError for load failures (with "Try again") and for profile/password form errors.
Field-level errors render under the field with role="alert"; client-side schema validation mirrors the server so no JSON round-trip is needed for a common mistake.
Network failures surface a generic "We couldn't save your profile." fallback via toast.
Annotations
Email is
readOnly, notdisabled, so it stays in the tab order and remains copyable.Password flow intentionally lives in this modal (shared by header and Settings) rather than a separate page.
WIREFLOWS
Primary Profile Management Flow
Header avatar / Settings → "Manage Profile" | vGET /api/user/profile --[401/403/404/500/503]--> Inline FormError + "Try again" | v[Editable name + avatar + email(read-only)] | |-- Save changes --> PATCH /api/user/profile --[400: fieldErrors]--> inline errors | | | | v v | [200: ProfileDetails] nothing written | | | v | refreshUser() → header updates | |-- Change photo --> POST /api/user/profile/avatar --[400/500/503]--> toast error | | | v | [200] → refreshUser() | |-- Remove --> PATCH { removeImage: true } --> refreshUser()
Change Password Flow
Profile modal → "Change password" | vPOST /api/user/password --[400: wrong current / provider-managed / weak]--> inline error | v[200: { changed: true }] | vsupabase.auth.signInWithPassword(new) --[fails]--> explicit signOut() + message | v[ok] refreshUser() → "Signed out on all other devices"
PROTOTYPE
Figma Prototype Link: Not specified.
Other design references: Reuses existing UI primitives (ui/dialog, ui/avatar, ui/button, PasswordField, PasswordRequirements) and the established app shell.
How to Test (Manual)
Sign in → open Profile from the header avatar drop-down → confirm name, email, avatar match the account.
Rename yourself (with an invalid name first, e.g. "A" or
<img>) → confirm the inline validation and that nothing is saved.Save a valid name → confirm the header name updates immediately, no reload.
Upload a small PNG/JPG/WebP → confirm the avatar updates everywhere; upload an SVG/oversized file → confirm a clean 400 toast.
Remove the avatar → confirm the header falls back to initials and the object is gone from the bucket.
Change password with the wrong current password → error, no write; then with the correct one → confirm "signed out on all other devices" and this device stays signed in.
As a Google/SSO account, attempt a password change → confirm the provider-managed message.
Reopen the modal rapidly while it is loading → confirm no stale data overwrites a newer load.
BACKEND SCHEMA
Database Tables
app_users — Identity Bridge
Purpose: The durable user row everything else references (forum, groups, admin, analytics).
This feature reads id, email, name, profile_image_url, role, status and writes only name / profile_image_url.
It never writes role, status, email, clerk_id or agency_id.
Source: Created out-of-band (predates supabase/migrations/). Touched by:
20260430_add_profile_image_url_to_app_users.sql20260909_create_auth_users_triggers.sql20260922_export_core_table_rls.sql
-- Relevant columns (full table predates the migrations directory)id uuid PRIMARY KEYclerk_id text -- auth.users.id (auth UUID), session-derivedemail text UNIQUE -- app_users_email_key (live schema)name textprofile_image_url text -- added by 20260430 (ADD COLUMN IF NOT EXISTS)role text -- display-only, never writable herestatus text -- display-only, never writable here
Relationships: clerk_id ↔ auth.users.id; used as the owner key by RLS and by every profile route.
auth.users — GoTrue-managed
Purpose: Authentication store.
raw_user_meta_data mirrors name/avatar; useUser()/header consumers read it.
The profile write path uses admin.updateUserById (merge semantics: a key is removed only with an explicit null).
Source: Supabase/Supabase Auth (GoTrue). Observed by triggers in 20260909_create_auth_users_triggers.sql.
-- Conceptual shape (managed by GoTrue, not by repo migrations)raw_user_meta_data jsonb -- name keys: full_name / name / preferred_username -- image keys: avatar_url / picture / image_urlidentities jsonb -- provider list: 'email' present ⇒ password-capableapp_metadata jsonb -- provider fallback for accounts without identities
Relationships: All app_users access by platform admin / owner-scoped routes dereferences through clerk_id.
storage.objects — Bucket public-assets
Purpose: Avatar objects live at:
avatars/{authUserId}/avatar_<timestamp>.<ext>
The extension/content type is derived server-side from validated bytes; SVG/HTML/JS MIME types are excluded at the bucket layer.
Source: 20260923_set_public_assets_allowed_mime_types.sql.
-- storage.buckets (public-assets)allowed_mime_types = array['image/jpeg','image/png','image/gif','image/webp', 'image/bmp','image/jpg', ...video/audio/doc/archive...]-- image/svg+xml, text/html and JS types deliberately absent
Indexes
Index | Table | Purpose |
|---|---|---|
|
| Every profile query filters by |
|
| Prevents duplicate profile rows by email; the trigger conflict-adoption path depends on it |
Constraints
app_users: email is UNIQUE (app_users_email_key, live schema — not enforced by any checked-in migration).
app_users: no self-service UPDATE/INSERT/DELETE policy — role escalation through the anon path is impossible by construction; all writes go through service-role routes that hard-code the writable columns.
RLS / Database Security
Table | Select | Insert/update/delete |
|---|---|---|
| Authenticated: own row ( | None for |
| Public read of stored assets | Bucket-level |
Helper Functions
Function | Purpose |
|---|---|
| AFTER INSERT on |
| AFTER UPDATE on |
| SECURITY DEFINER admin predicate used by RLS policies |
RPC / Stored Procedures
Function | Parameters | Returns | Security | Purpose/important logic |
|---|---|---|---|---|
(none introduced by this feature) | — | — | — | Profile reads/writes use direct table access, not RPC |
API ENDPOINTS
GET /api/user/profile
Purpose: Return the caller's own durable profile (ProfileDetails).
Auth: Session cookie; authenticateUser() first (rejects suspended). Auth id resolved by getCurrentSupabaseUser() — never from request input.
Query Params: None.
Path Params: None.
Request Body: None.
Response:
{ "success": true, "message": null, "data": { "id": "ff2846ea-d4c2-…", "email": "ada@example.com", "fullName": "Ada Lovelace", "firstName": "Ada", "imageUrl": "https://cdn…/avatars/…/avatar_1.png", "role": "LEARNER", "status": "Active" }, "error": null}
Error Responses: 401 unauthenticated; 403 suspended; 404 no profile row ("No profile found…"); 500 non-fatal read failure; 503 DB unavailable.
PATCH /api/user/profile
Purpose: Edit the caller's own fullName and/or clear the avatar (removeImage: true).
imageUrl is deliberately NOT accepted — only POST /api/user/profile/avatar may set an avatar.
Auth: Session cookie (as above).
Request Body:
{ "fullName": "string", "removeImage": true}
Zod strictObject — unknown keys rejected.
Response: The refreshed ProfileDetails (200) with message "Profile updated successfully".
Error Responses: 400 VALIDATION_ERROR with fieldErrors (bad name, empty payload, unknown key, removeImage: false, smuggled role/status/email/agency_id/imageUrl); 404 no profile row; 500 write/compensation failure; 503 DB unavailable.
POST /api/user/profile/avatar
Purpose: Multipart upload (field avatar) replacing the caller's image; returns refreshed ProfileDetails.
Auth: Session cookie.
Request Body: multipart/form-data, part avatar (File).
Validated in three layers:
Declared metadata (size/type/name)
validateRasterImageUpload(SVG hard-reject, stored content type derived from validated extension)Magic-byte sniff (
looksLikeRasterImage)
A declared Content-Length > 5MB + 64KB is rejected before the body is buffered.
Response: Refreshed ProfileDetails (200), "Profile image updated successfully".
Error Responses: 400 validation (oversized, unsupported format, non-image bytes, missing part); 401/403 auth; 500 storage failure; 503 DB/storage unavailable.
On commit failure the freshly uploaded object is deleted so no orphan remains.
POST /api/user/password
Purpose: Change the caller's password after proving the current one.
Auth: Session cookie; the target auth id comes from the session, never the body.
Request Body:
{ "currentPassword": "string", "newPassword": "string", "confirmPassword": "string"}
Zod strictObject; password policy shared with reset flows.
Response: { changed: true } (200), "Password changed successfully".
Error Responses: 400 (wrong current password, weak/mismatched/reused password, provider-managed account, invalid body/unknown key); 401/403; 503 DB unavailable.
DATA REQUIREMENTS
Frontend Needs
Shared client + server contract in lib/schemas/profile.schema.ts (ProfileModal.tsx imports the schema and ProfileDetails type directly).
export interface ProfileDetails { id: string; // internal app_users.id — NOT the auth UUID email: string | null; fullName: string | null; firstName: string; imageUrl: string | null; role: string | null; status: string | null;} export type UpdateProfileInput = z.infer<typeof updateProfileSchema>; // { fullName?, removeImage? }export type ChangePasswordInput = z.infer<typeof changePasswordSchema>; // current/new/confirmexport type AvatarUploadMeta = z.infer<typeof avatarUploadMetaSchema>; // name/type/size
Required fields:
fullName— 2–100 chars, letters/numbers/apostrophe/period/hyphen/space for a name save.avatar— multipart part for an upload.All three password fields, with
newPasswordmatchingconfirmPassword, differing fromcurrentPassword, and meeting the shared strength policy (≥8 chars, upper+lower+digit+special).
API Calls Frontend Will Make
Call | Trigger |
|---|---|
| Profile modal opens ( |
| "Save changes" or "Remove" image |
| File selected in the picker |
| "Change password" submit |
Caching Strategy
Client-side: Profile load uses fetch(..., { cache: "no-store" }); modal state lives in useState. The header renders from SessionProvider's user (source of truth for useUser() consumers).
Refetch: Modal refetches on every open; after any successful write it calls refreshUser() → loadUser() re-resolves the user from GoTrue over the network.
Invalidation: SessionProvider ignores the INITIAL_SESSION cookie snapshot (which can carry pre-save claims) and reconciles with auth.getUser() on mount and after refreshUser(). Per-request loadSeqRef drops superseded profile loads.
Debouncing: None — submissions are one-shot, guarded by in-flight refs against duplicate dispatches in the same tick.
Deduplication: getCurrentSupabaseUser() is request-memoized (React cache()); in-memory auth caches TTL the role/status lookups (userIdCache 5 min, roleCache 30 s).
Stale-data handling: Sequence-numbered loads; a response that resolves after the modal closed or after a newer load started is discarded.
Server-side caching: None for profile reads (always fresh); only the generic auth caches above apply.
PERFORMANCE CONSIDERATIONS
Database Optimization
Every query is keyed on the indexed app_users.clerk_id and reads a single row with a fixed column list:
id, email, name, profile_image_url, role, status
Profile writes are two narrow updates (metadata merge + one row update), never a bulk scan.
Caching Strategy
Profile data is intentionally uncached so the modal always shows durable values.
getCurrentSupabaseUser is memoized per request; authenticateUser/authenticateUserWithRole use TTL'd in-memory caches to avoid repeated DB reads on hot paths.
API Response Time
Performance targets: p95 < 200 ms for read and write routes in the normal case.
Expected response time: dominated by the two Supabase round-trips (GoTrue metadata write + PostgREST row read); typically tens of ms in the region where this app is deployed.
Known bottlenecks: POST /api/user/profile/avatar buffers the full multipart body (≤ ~5.1 MB) in Node memory before validation; avatar uploads are synchronous and un-thumbnailed.
Potential future optimizations:
Stream/offload avatar processing.
Generate a downscaled/resized variant for the header.
Re-add the sign-up welcome email as the Supabase trigger path does (a known non-goal for the MVP).
SECURITY & AUTHORIZATION
Access Matrix
Self-service — every leading-edge row is "for one's own account", available to every authenticated role:
Action | OWNER | ADMIN | CREATOR | REVIEWER | LEARNER |
|---|---|---|---|---|---|
View own profile | ✓ | ✓ | ✓ | ✓ | ✓ |
Edit own full name | ✓ | ✓ | ✓ | ✓ | ✓ |
Upload/remove own avatar | ✓ | ✓ | ✓ | ✓ | ✓ |
Change own password | ✓ | ✓ | ✓ | ✓ | ✓ |
Change email / role / status | ✗ | ✗ | ✗ | ✗ | ✗ |
Notes: Authorization here is self-ownership, not role-based.
The matrix is uniform because the profile API only ever addresses the session's own account. Read-only fields (email, role, status, agency membership) require a different flow for every role.
Authorization Logic
Authentication: authenticateUser() on every route (validates the session cookie and rejects suspended accounts) + getCurrentSupabaseUser() (request-memoized auth.getUser()).
Role checks: None required — the feature is available to all authenticated users.
Permission checks: None beyond authentication; there are no admin-editing endpoints.
Resource ownership: The auth id is derived exclusively from the session cookie.
Every app_users query is filtered by:
.eq("clerk_id", <that id>)
The fake app_users double in the route tests enforces this: a query that forgets the filter returns null and fails.
No id is read from body, query string or path.
updateProfileSchema/changePasswordSchema are strictObject, so read-only columns (role, status, agency_id, email, clerk_id, id, imageUrl) cannot ride along in the payload.
Tenant/agency scoping: Not applicable — the surface is the caller's own account, cross-tenant access is structurally impossible (no user-supplied identifier).
Server-side authorization: The service-role client bypasses RLS, so the route-level checks above are the backstop — matched by the deliberate absence of any app_users UPDATE RLS policy.
Avatar storage paths are derived from the auth id and validated server-side; removeManagedAvatar only deletes objects under avatars/{authUserId}/ in public-assets.
Frontend permission visibility: The modal is shown to every signed-in user from UserButton and Settings.
A provider-managed (SSO) account sees a clear "change your password at the provider" message instead of a dead form.
Data Validation
Validation library: Zod (lib/schemas/profile.schema.ts, shared client/server).
Input limits:
Name: 2–100 chars.
Password: 8–128 chars (upper, lower, digit, special).
Avatar: ≤ 5 MB (
PROFILE_IMAGE_MAX_BYTES) with a 5 MB + 64 KBContent-Lengthpre-check.
Required fields:
fullNamefor name saves.avatarpart for uploads.All three password fields for password changes.
UUID validation: The auth UUID is never client-supplied; it is resolved server-side from the session. Supabase validates UUID bindings on the app_users.id path used by auth helpers.
Enum validation: None user-supplied (role/status never accepted as input).
File validation: Three layers — declared metadata (avatarUploadMetaSchema), validateRasterImageUpload (SVG hard-reject; stored content type derived from validated extension, never from File.type), and magic-byte sniffing (looksLikeRasterImage: PNG/JPEG/GIF/WEBP/BMP).
Server-side validation: All four routes re-validate on the server with the same schemas; the avatar route additionally checks Content-Length before buffering and sniffs bytes before storage.
Cross-tenant validation: No query is ever keyed by a user-supplied id; the row and storage prefix are both bound to the session auth id, so a caller cannot address or overwrite another account even through the RLS-bypassing service-role client.
ERROR HANDLING
Error | Response |
|---|---|
Missing/invalid session | 401 |
Suspended account | 403 |
No | 404 |
Invalid name / weak PATCH payload / unknown key / | 400 |
Invalid/mismatched/reused password | 400 |
Wrong current password | 400 |
Provider-managed account | 400 |
Non-image/oversized avatar | 400 |
Metadata write fails | 500 (non-fatal) / 503 |
| 500/503 + best-effort metadata compensation rollback |
Avatar storage/upload failure | 500 |
Client network failure (no response) | Modal inline error / toast fallback, no state corruption |
Transaction / Rollback
No cross-store transaction exists (GoTrue has no transaction over auth.users).
applyProfileChanges writes metadata first, then the authoritative app_users row.
On row failure it compensates by restoring the previous metadata document and nulling any keys the failed write added.
The avatar route deletes its new object only after applyProfileChanges succeeds, and removeManagedAvatar is best-effort (an orphaned object never fails the save that replaced it).
TESTING CHECKLIST
Happy Path
GET /api/user/profilereturns the caller's own row (200).PATCH { fullName }writesapp_users.namescoped to the caller'sclerk_idand mirrorsfull_name/first_name/last_nameinto metadata, clearing stalepreferred_username.Name-only save keeps an existing avatar untouched on both stores.
Avatar upload stores under
avatars/{authUserId}/with a server-pinned content type and records the URL on the caller's row.Avatar replacement deletes the previous managed object.
PATCH { removeImage: true }clearsprofile_image_url, sendsavatar_url: null(pluspicture/image_urlnull), and deletes a managed object.Password change verifies the current password, writes the new one for the session-derived id, and (client) re-authenticates this device / signs others out.
Modal + header reflect the change immediately via
refreshUser().
Edge Cases
Unauthenticated caller reaches no query at all (401, no
supabase.fromcall).Suspended account → 403.
No profile row → 404 (not a leak).
Payload smuggling
role/status/agency_id/email/clerk_id/id/imageUrl→ 400strictObjectrejection.removeImage: falserejected as "no changes"; empty/malformed JSON rejected.SVG, SVG-MIME-under-PNG-name, and arbitrary-bytes-as-PNG all rejected before storage.
Oversized file and oversized
Content-Lengthrejected withfieldErrors.size, before storage is touched.Wrong current password and body-supplied
emailrejected beforesignInWithPassword.OAuth account with an email is provider-managed; an account with a linked
emailidentity may change its password.Reused password rejected at the schema; GoTrue
same_passwordsurfaced with shared copy.Metadata merge: unrelated keys (
app_user_id) survive a name save; explicitnullactually removesavatar_url.Row-write failure rolls metadata back byte-identically (added keys nulled); fatal read/write → 503.
removeManagedAvatarnever deletes third-party (OAuth), foreign-user, or different-bucket objects.Component: stale load responses dropped (
loadSeqRef); duplicate submits blocked in one tick; busy state disables all write controls.
OPEN QUESTIONS
For Frontend
Should theme/language selections recorded in
/learner/settingsbe applied app-wide (.darkbootstrap / i18n layer), and should ProfileModal surface them too?Should the risk of an account being silently signed out later (instead of the current explicit re-auth) be surfaced in the password-change success message for unusual identity configurations?
For Backend
The
20260909trigger migration notes the sign-up welcome email is not re-added for direct sign-ups and the mirror trigger is not guaranteed to exist in environments whereapp_userswas created out-of-band — should the profile writes become self-healing (assert trigger existence) rather than relying on the explicit second write?Should account deletion (currently a Danger Zone placeholder) be implemented as a route in this branch or in a dedicated data-lifecycle feature?
SUCCESS METRICS
Users can correct their own name/avatar — % of profile edits completed without a support ticket.
Self-service password changes executed successfully with the current-password gate (remediation of compromised credentials in-product).
Header/
useUser()consumers reflect a saved name/avatar with zero page reloads (regression suite keeps the dual-store merge semantics locked).Route and component suites (auth-before-read, owner-scoped writes, read-only-column injection) remain green on CI for every touch of the service-role client.
DEPENDENCIES
This Feature Depends On
Existing features:
SessionProvider, useAuth, useUser, getProfileInitials, the app-wide UI primitives, and the Settings page shell.
Database tables:
app_users(identity bridge)auth.users(via GoTrue)storage.objectsbucketpublic-assets
APIs:
authenticateUser()/authenticateUserWithRole()getCurrentSupabaseUser()(request-memoized)supabase.auth.admin.updateUserByIdSupabase Storage upload/getPublicUrl/remove
Services:
Supabase Auth (GoTrue), Supabase Storage; the public-assets bucket with the allowed_mime_types allow-list (20260923).
Authentication:
Native Supabase Auth session cookie (@supabase/ssr); no Clerk dependency on these routes.
Migrations:
20260430_add_profile_image_url_to_app_users.sql20260909_create_auth_users_triggers.sql20260922_export_core_table_rls.sql20260923_set_public_assets_allowed_mime_types.sql
Libraries:
zod@supabase/supabase-js@supabase/ssrsonnerlucide-reactsharp@testing-library/dom
These Features Depend On This
Settings page (learner) — profile entry point and password action.
Header/user-menu identity rendering (
UserButton).Any future account-safety flows (account deletion, email change) will build on the same ownership/scoping and dual-store write patterns.
TIMELINE & OWNERSHIP
Owner: WyzQuests Platform Engineering (this PR: #890, branch feat/profile-management-01).
Implementation timeline: MVP implemented across PR #890 / the feat/profile-management-01 branch set (profile routes, modal, session reconcile, Schema hardening, route/component tests).
Completion date: 2026-10-09 (branch set current on this date).
Follow-up work:
Sign-up welcome email for direct sign-ups (noted in
20260909_create_auth_users_triggers.sql)Account deletion flow
App-wide theme/language application
Avatar resizing for header use
app_usersemail UNIQUE andclerk_idindex enforcement via a checked-in migration
Blocking Environment Prerequisites
Supabase project with the service-role key env var and the
public-assetsbucket;allowed_mime_typesmigration applied (avoids SVG/HTML storage).Auth triggers migration applied so new auth users get
app_usersrows.NEXT_PUBLIC_SUPABASE_URL/NEXT_PUBLIC_SUPABASE_ANON_KEY/SUPABASE_SERVICE_ROLE_KEYconfigured (routes 503 "Authentication is not configured" otherwise).
Document Version
1.0 — Initial technical documentation for PR #890 / feat/profile-management-01 — 2026-10-09