Profile Management

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) and auth.users metadata (what useUser()/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 in UserButton and /learner/settings.

  • GET /api/user/profile — the caller's own durable profile details.

  • PATCH /api/user/profile — update fullName and/or removeImage.

  • 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 fresh auth.users metadata to useUser() 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.ts

  • tests/components/ProfileModal.test.tsx

  • tests/components/UserButtonProfile.test.tsx

  • tests/unit/profile.schema.test.ts


USER FLOWS

Entry Point

  • Global header UserButton drop-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_users values, 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

  1. User opens the modal → loadProfile runs GET /api/user/profile with cache: "no-store".

  2. Route authenticates, resolves the auth id from the session cookie, reads the row by .eq("clerk_id", id), maps to ProfileDetails.

  3. Modal fills the avatar and name field; email, role and status are shown read-only.

Edit Full Name

  1. User edits the name → client validates with the same profileNameSchema the route uses.

  2. Submit PATCH /api/user/profile { fullName }.

  3. Route writes name to auth.users metadata first (fires the mirror trigger where it exists), then writes app_users.name as the authoritative value.

  4. Modal stores the refreshed profile, toasts "Profile updated", calls refreshUser() → header re-resolves the user from the network.

Change / Remove Avatar

  1. User picks a file (PNG/JPG/GIF/WEBP, ≤5 MB) → POST /api/user/profile/avatar (multipart field avatar).

  2. Route validates declared metadata, then validateRasterImageUpload (SVG rejected), then magic-byte sniff; uploads to public-assets/avatars/{authUserId}/avatar_<timestamp>.<ext>.

  3. applyProfileChanges commits the new URL to metadata + app_users; only then is the previous managed object deleted.

  4. Modal toasts and calls refreshUser(). Remove image follows the same path via PATCH { removeImage: true }, sending avatar_url: null so GoTrue actually clears the key.

Change Password

  1. User fills current/new/confirm and submits POST /api/user/password.

  2. Route authenticates and rejects provider-managed accounts; schema rejects weak/mismatched/reused passwords.

  3. Current password is verified with a throwaway anon client (persistSession: false) so the live session cookies are untouched.

  4. admin.updateUserById writes the new password (revokes every session).

  5. 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)

GET/PATCH return 404 "No profile found"; modal shows message + "Try again"

Suspended account

authenticateUser() throws → 403 ACCOUNT_SUSPENDED, surfaced before any DB access

Reopening the modal quickly / stale load response

loadSeqRef sequence numbers loads; a superseded response is dropped

Double-click / Enter twice in one tick

In-flight guard refs (saveProfileRef etc.) allow exactly one request

Removed avatar "reappearing" in header

Metadata patch sends avatar_url: null (not omission) + nulls lower-precedence picture/image_url; app_users.profile_image_url cleared with null

app_users write fails after metadata write

applyProfileChanges compensates by restoring previous metadata, nulling added keys

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

removeManagedAvatar only deletes under avatars/{authUserId}/ in public-assets; otherwise no-op

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

signInWithPassword re-auth fails after a successful change

Explicit signOut() + "Please sign in again with your new password"

Oversized avatar / oversized Content-Length

400 with fieldErrors.size; huge bodies rejected before formData() buffers them

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, not disabled, 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"
|
v
GET /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"
|
v
POST /api/user/password --[400: wrong current / provider-managed / weak]--> inline error
|
v
[200: { changed: true }]
|
v
supabase.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)

  1. Sign in → open Profile from the header avatar drop-down → confirm name, email, avatar match the account.

  2. Rename yourself (with an invalid name first, e.g. "A" or <img>) → confirm the inline validation and that nothing is saved.

  3. Save a valid name → confirm the header name updates immediately, no reload.

  4. Upload a small PNG/JPG/WebP → confirm the avatar updates everywhere; upload an SVG/oversized file → confirm a clean 400 toast.

  5. Remove the avatar → confirm the header falls back to initials and the object is gone from the bucket.

  6. 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.

  7. As a Google/SSO account, attempt a password change → confirm the provider-managed message.

  8. 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.sql

  • 20260909_create_auth_users_triggers.sql

  • 20260922_export_core_table_rls.sql

-- Relevant columns (full table predates the migrations directory)
id uuid PRIMARY KEY
clerk_id text -- auth.users.id (auth UUID), session-derived
email text UNIQUE -- app_users_email_key (live schema)
name text
profile_image_url text -- added by 20260430 (ADD COLUMN IF NOT EXISTS)
role text -- display-only, never writable here
status 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_url
identities jsonb -- provider list: 'email' present ⇒ password-capable
app_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

clerk_id

app_users

Every profile query filters by .eq("clerk_id", <auth id>)

app_users_email_key (UNIQUE on email)

app_users

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

app_users

Authenticated: own row (clerk_id = auth.uid()::text); Platform ADMIN: all rows (user_is_platform_admin())

None for authenticated — writes only via service-role routes

storage.objects (public-assets)

Public read of stored assets

Bucket-level allowed_mime_types allow-list (M4); uploads via service-role routes

Helper Functions

Function

Purpose

handle_new_user() (trigger on_auth_user_created)

AFTER INSERT on auth.users: provisions the app_users row and seeds LEARNER role

sync_app_user_profile() (trigger on_auth_user_updated)

AFTER UPDATE on auth.users: mirrors email/name/avatar into app_users; guarded by WHEN email or metadata changed; keeps existing email on conflict

user_is_platform_admin()

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:

  1. Declared metadata (size/type/name)

  2. validateRasterImageUpload (SVG hard-reject, stored content type derived from validated extension)

  3. 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/confirm
export 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 newPassword matching confirmPassword, differing from currentPassword, and meeting the shared strength policy (≥8 chars, upper+lower+digit+special).

API Calls Frontend Will Make

Call

Trigger

GET /api/user/profile

Profile modal opens (cache: "no-store")

PATCH /api/user/profile

"Save changes" or "Remove" image

POST /api/user/profile/avatar

File selected in the picker

POST /api/user/password

"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 KB Content-Length pre-check.

Required fields:

  • fullName for name saves.

  • avatar part 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 UNAUTHORIZED (before any DB/storage access)

Suspended account

403 ACCOUNT_SUSPENDED

No app_users row

404 NOT_FOUND ("No profile found…")

Invalid name / weak PATCH payload / unknown key / removeImage: false

400 VALIDATION_ERROR + Zod fieldErrors; nothing written

Invalid/mismatched/reused password

400 VALIDATION_ERROR (field-level)

Wrong current password

400 BAD_REQUEST ("Your current password is incorrect.") — write never attempted

Provider-managed account

400 BAD_REQUEST (third-party message; checked before verification)

Non-image/oversized avatar

400 VALIDATION_ERROR (declared-size pre-check avoids buffering)

Metadata write fails

500 (non-fatal) / 503 SERVICE_UNAVAILABLE (fatal); nothing durable written

app_users write fails after metadata write

500/503 + best-effort metadata compensation rollback

Avatar storage/upload failure

500 INTERNAL_ERROR; fatal transport → 503; freshly uploaded object cleaned up on commit failure

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/profile returns the caller's own row (200).

  • PATCH { fullName } writes app_users.name scoped to the caller's clerk_id and mirrors full_name/first_name/last_name into metadata, clearing stale preferred_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 } clears profile_image_url, sends avatar_url: null (plus picture/image_url null), 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.from call).

  • Suspended account → 403.

  • No profile row → 404 (not a leak).

  • Payload smuggling role/status/agency_id/email/clerk_id/id/imageUrl → 400 strictObject rejection.

  • removeImage: false rejected 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-Length rejected with fieldErrors.size, before storage is touched.

  • Wrong current password and body-supplied email rejected before signInWithPassword.

  • OAuth account with an email is provider-managed; an account with a linked email identity may change its password.

  • Reused password rejected at the schema; GoTrue same_password surfaced with shared copy.

  • Metadata merge: unrelated keys (app_user_id) survive a name save; explicit null actually removes avatar_url.

  • Row-write failure rolls metadata back byte-identically (added keys nulled); fatal read/write → 503.

  • removeManagedAvatar never 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/settings be applied app-wide (.dark bootstrap / 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 20260909 trigger 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 where app_users was 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.objects bucket public-assets

APIs:

  • authenticateUser() / authenticateUserWithRole()

  • getCurrentSupabaseUser() (request-memoized)

  • supabase.auth.admin.updateUserById

  • Supabase 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.sql

  • 20260909_create_auth_users_triggers.sql

  • 20260922_export_core_table_rls.sql

  • 20260923_set_public_assets_allowed_mime_types.sql

Libraries:

  • zod

  • @supabase/supabase-js

  • @supabase/ssr

  • sonner

  • lucide-react

  • sharp

  • @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_users email UNIQUE and clerk_id index enforcement via a checked-in migration

Blocking Environment Prerequisites

  • Supabase project with the service-role key env var and the public-assets bucket; allowed_mime_types migration applied (avoids SVG/HTML storage).

  • Auth triggers migration applied so new auth users get app_users rows.

  • NEXT_PUBLIC_SUPABASE_URL / NEXT_PUBLIC_SUPABASE_ANON_KEY / SUPABASE_SERVICE_ROLE_KEY configured (routes 503 "Authentication is not configured" otherwise).


Document Version

1.0 — Initial technical documentation for PR #890 / feat/profile-management-01 — 2026-10-09


Was this article helpful?