Files
Convivo/docs/frontend/api-client.md
T
Lago d4e4637e7c feat(sessions): material downloads unlock when the session ends
Private materials bucket + RLS read gate (admins/own speakers anytime, all
attendees after the scheduled slot end, event-local Amsterdam time); always
visible uploaded-state, locked download panel, authenticated client downloads,
admin signed URLs. 12 new assertions in material_time_lock_tests.sql.
2026-10-21 18:57:15 +02:00

192 lines
11 KiB
Markdown

# API Client
How the app talks to Supabase. Source:
[`apps/convivo/src/lib/supabase.ts`](../../apps/convivo/src/lib/supabase.ts) and
[`apps/convivo/src/lib/api.ts`](../../apps/convivo/src/lib/api.ts).
## The Supabase client (`lib/supabase.ts`)
```ts
const url = import.meta.env.VITE_SUPABASE_URL || window.location.origin;
const anonKey = import.meta.env.VITE_SUPABASE_ANON_KEY;
export const supabase = createClient(url, anonKey, {
auth: { persistSession: true, autoRefreshToken: true, detectSessionInUrl: false },
realtime: { params: { eventsPerSecond: 10 } },
});
```
- **Same-origin by default.** `VITE_SUPABASE_URL` is intentionally left unset, so
the client uses `window.location.origin`. The app is served behind a proxy
(Vite dev server, or nginx in Docker) that forwards `/auth/v1`, `/rest`,
`/realtime`, `/storage` to the Supabase core. This avoids CORS entirely. See
[../backend/docker.md](../backend/docker.md).
- **Anon key only.** The client is created with the **anon key** (public). The
user's identity comes from the session JWT, and RLS enforces access. See
[../backend/rls.md](../backend/rls.md).
- **Session persistence** — the session is stored in `localStorage` and
auto-refreshed, so a reload keeps you logged in. The JWT expiry is **24h**
(`jwt_expiry = 86400`), so a login lasts a full day.
## The typed wrapper (`lib/api.ts`)
A thin, typed layer over `supabase.rpc` and `supabase.from`. It centralizes error
handling (wraps Supabase errors in `ApiError`) and gives every screen a clean
async API.
### RPC calls (mutations + complex reads)
These map 1:1 to the Postgres RPCs documented in
[../backend/rpcs.md](../backend/rpcs.md):
| Client function | RPC | Purpose |
|---|---|---|
| `lanyardLookup(qrToken)` | `lanyard_lookup` | Resolve a scanned QR to a public contact + registration type |
| `getPublicContacts()` | `get_public_contacts` | Active-event contact directory (names + types) |
| `getAgenda()` | `get_agenda` | Slots + sessions (flat rows) |
| `getActiveEvent()` | `get_active_event` | The active event row |
| `setPreference(sessionId)` | `set_preference` | Pick a session for its slot |
| `clearPreference(slotId)` | `clear_preference` | Remove a pick |
| `createConnectionRequest(targetQr)` | `create_connection_request` | Send a connection request |
| `acceptConnection(id)` | `accept_connection` | Accept (+5 to both) |
| `rejectConnection(id)` | `reject_connection` | Decline |
| `checkinAttendee(sessionId, attendeeQr)` | `checkin_attendee` | Staff session check-in (+10, or nothing for excluded staff — `points_awarded` says which) |
| `welcomeCheckin(attendeeQr)` | `welcome_checkin` | Staff welcome check-in (marks present at the event **and awards +10**, first time only; `points` + `points_awarded` report what happened) |
| `previewWelcomeCheckin(attendeeQr)` | `preview_welcome_checkin` | Read-only pre-confirm lookup: `{ already, will_print, copies, points_awarded }` |
| `submitFeedback(sessionId, rating, comment)` | `submit_feedback` | Rate a session (+5/+10) |
| `getLeaderboard()` | `get_leaderboard` | Active-event leaderboard |
| `uploadSessionMaterial(sessionId, file)` | `set_session_material` | Upload to `materials` bucket + set `material_path` |
| `removeSessionMaterial(sessionId)` | `set_session_material` | Clear `material_path`, then delete the detached storage object |
| `updateMyProfile({linkedin_url, show_email, show_linkedin})` | `update_my_profile` | Self-service: set LinkedIn + visibility toggles on the caller's own contact |
### Direct table reads (RLS-scoped)
These read the caller's own rows (RLS returns only what the user may see). For an
admin contact, RLS returns **all** rows, so the "my" reads filter by email
client-side to avoid leaking other people's data:
| Client function | Table | Returns |
|---|---|---|
| `getMyContact(email)` | `contacts` | the caller's contact |
| `getMyRegistration(email)` | `registrations` | the caller's registration (active event) |
| `getMyPreferences()` | `preferences` | the caller's picks |
| `getMyConnections()` | `connections` | connections the caller is in |
| `getMyCheckins(email)` | `checkins` | the caller's checked-in session ids |
| `getMyFeedback(email)` | `feedback` | the caller's feedback |
| `getMyPointsLog(email)` | `points_log` | the caller's points history |
| `getMySpeakerSessions(email)` | `session_speakers` | session ids the caller speaks |
### Helpers
- **`groupAgenda(rows)`** — turns the flat `get_agenda()` rows into
`{ slot, sessions[] }[]` ordered by slot id. Used by `useEvent()`.
- **`downloadSessionMaterial(path)`** — downloads a material file through
authenticated storage (private bucket; server-side RLS allows it for the
session's speakers/admins anytime, everyone else after the session ended).
**`materialFilename(path)`** strips the `sessions/<id>/<ts>-` prefix.
## Admin Email Entry
[adminEntry.ts](../../apps/convivo/src/lib/adminEntry.ts) handles email requests
and the normal app's verified session profile. Before sending, it calls the
read-only `can_request_admin_magic_link(p_email)` RPC. Eligibility requires both
an existing Auth user and a contact authorized by the existing admin rule
(`is_admin` flag or an `@appe.at` contact). Ineligible addresses do not trigger
an OTP request. Eligible addresses use `signInWithOtp` with
`shouldCreateUser: false` and
`emailRedirectTo: window.location.origin + '/auth/callback'`.
Deployment requires
[the eligibility migration](../../supabase/migrations/20261010093021_admin_magic_link_eligibility.sql)
and an Auth redirect allowlist entry for
`https://convivo.appe.at/auth/callback` (plus the corresponding URL for each
development origin). These are deployment prerequisites, not automatic frontend
configuration. Vite serves the callback as an SPA route rather than proxying it
to Auth; nginx uses an exact callback location with no access logging, no-store
caching and no-referrer policy. The document also sets no-referrer before assets
load.
The callback accepts implicit token pairs or a PKCE code exactly once per page
load, including StrictMode, and removes callback credentials from the address
bar before network calls. `getUser(access_token)` verifies identity at the Auth
server; `is_admin()` authorizes admin entry independently of editable metadata.
Failed callbacks sign out locally. Normal restored/QR sessions also verify the
user and admin role. Contact reads use the verified email; registration reads
filter by both that email and the active event, returning null when absent.
Admins need no registration or attendance state to use Convivo's existing staff
experience. This login path performs no registration, attendance or points
mutations.
Privacy boundary: the screen gives identical confirmations for eligible and
ineligible addresses and suppresses account-existence errors from OTP. However,
the public eligibility RPC returns a boolean that direct callers can inspect;
it is not enumeration-resistant. This gates this UI's sends, not direct calls
to Supabase Auth's OTP endpoint. The callback's server-backed admin check remains
the access boundary.
Mocked browser regressions are in
[convivo-admin-entry.spec.ts](../../e2e/tests/convivo-admin-entry.spec.ts);
[SQL regressions](../../supabase/tests/admin_magic_link_eligibility_tests.sql)
use rollback fixtures to check eligibility, grants and unchanged attendance
data. Neither suite sends real OTP email.
## Speaker Portal
[speakerPortal.ts](../../apps/convivo/src/lib/speakerPortal.ts) recognizes only
`/speaker/secret` and `/speaker` (optional trailing slash). It exposes a shared
`speakerPortalSession` promise, consuming implicit token pairs with `setSession`
or PKCE codes with `exchangeCodeForSession` exactly once per page load, including
React StrictMode. Automatic URL session detection remains disabled. Callback
parameters are scrubbed before auth calls; errors use generic recoverable text.
`SpeakerPortal` requests `signInWithOtp` with `shouldCreateUser: false` and
`emailRedirectTo: window.location.origin + '/speaker/secret'`. Supabase Auth's
redirect allowlist must include this URL on each deployment origin. This does
not create contacts, registrations or Auth users.
`getSpeakerPortalSessions()` calls `get_my_speaker_sessions`, returning typed
`SpeakerSession` rows with talk/material, event and slot information. Authorization
is [backend-owned](../backend/rls.md#speaker-portal-authorization); the client
does not filter by active event, clock, points or physical check-in.
Material helpers are shared with Agenda. Upload reads the previous path, creates
a unique `sessions/<session UUID>/<random UUID>-<sanitized filename>` object,
then calls `set_session_material`. A rejected attachment removes the new object.
After successful replacement, the previous object is removed. Removal detaches
the path first, then deletes the old object. Cleanup errors distinguish a saved
or detached material from a failed attachment; the portal refreshes the list
after each attempted operation. These Storage and RPC calls are not one atomic
transaction, so simultaneous clients remain last-writer-wins and can leave an
unattached object; they never mutate attendance or points.
See [RPC contract](../backend/rpcs.md#speaker-portal-rpcs),
[screen states](./screens.md#speaker-portal) and [tests](../backend/tests.md#speaker-portal).
## Types (`lib/types.ts`)
TypeScript interfaces mirroring the DB tables and RPC return shapes
(`Contact`, `Registration`, `Event`, `Slot`, `Session`, `AgendaRow`,
`Preference`, `Connection`, `Checkin`, `Feedback`, `LeaderboardRow`,
`PointsLogRow`, `PublicContact`, `CheckinResult`, `FeedbackResult`).
`PublicContact` is the safe projection (email + name + visibility-respected
linkedin + registration type) returned by the public read functions.
## Error handling
- `rpc()` throws `ApiError` with the Postgres message on failure.
- Screens catch errors and surface them via toasts
(`useToast().toast(message, 'err')`). RPCs raise human-readable messages
(e.g. "staff or admin only", "you must be checked in to this session to give
feedback", "not a speaker of this session") — see
[../backend/rpcs.md#error-handling](../backend/rpcs.md#error-handling).
## Realtime + polling
- **Realtime** — the only realtime subscription is on the `leaderboard` table
(see [screens.md#leaderboard](./screens.md#leaderboard)). The `leaderboard`
table is the Realtime source and is kept in sync transactionally by the RPCs —
see [../backend/schema.md#leaderboard--realtime-mirror](../backend/schema.md#leaderboard--realtime-mirror).
- **Polling** — Connections and the Shell's pending-connection red dot use
`usePolling` (5s, visibility-aware) — see
[app-structure.md#the-polling-hook-libusepollingts](./app-structure.md#the-polling-hook-libusepollingts).