From 5550914979b1629bf8195e97f221c298c40dcb8c Mon Sep 17 00:00:00 2001 From: Arena Agent Date: Sun, 11 Oct 2026 00:40:12 +0000 Subject: [PATCH 01/11] Fix the code-only items from docs/KNOWN_ISSUES.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Security (P0) - /api/send-notification: requires a verified Supabase JWT, derives the recipients and the notification title from the database, caps the body and is rate limited. It is no longer an open push relay. - /api/upload-file: auth required, MIME allowlist, per-media-type size caps (15/25/50 MB instead of a 100 MB free-for-all), 8 req/min. - Server hardening: helmet, cors allowlist + origin guard (403 on cross-origin writes), express-rate-limit on every surface, per-route JSON limits (256 kB default), JSON 404/400/413 handlers, trust proxy. - /api/livekit-token now verifies the caller participates in the call and takes the token identity from the session; /api/grix-ai requires auth; /api/github/debug is dev-only; FCM token cleanup no longer scans users. Correctness (P1) - notifications finally has a write path (services/db/notificationService.ts), wired into follow requests, request accepts and the offline worker. - Readers use the `content` column the schema actually defines. - users.saved_posts removed from code and mock (the column never existed). - /forgot-password renders the reset form instead of bouncing to /login. Deploy & CI (P2) - Pages builds with VITE_BASE_URL=/grixchat/; CI typechecks and tests first. - VITE_* values wired from Actions secrets, plus a loud build-time warning for the silent trap where missing Supabase creds tree-shake the whole SDK out. Performance (P2) - manualChunks: entry chunk 1.14 MB -> 170 kB. - emoji-picker-react is lazy (own chunk, loaded on tap). - console/debugger dropped from production builds. Quality (P3) - Removed the dead Reels/Tube leftovers in SearchUserScreen, reconnected the /search-user route, and fixed the sitemap advertising deleted routes. Verification: npm run lint 0 errors · npm test 85/85 (6 files) · npm run build clean. Remaining items need SQL, secrets or a product decision - see the top of docs/KNOWN_ISSUES.md. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .env.example | 8 +- .github/workflows/deploy.yml | 28 + AGENTS.md | 24 +- README.md | 7 +- dev/mock/auth.ts | 1 - dev/mock/query.ts | 2 + dev/mock/seed.ts | 8 - docs/ARCHITECTURE.md | 13 + docs/CONTEXT.md | 39 +- docs/DATA_MODEL.md | 20 +- docs/DEAD_CODE.md | 2 +- docs/DEV_SETUP.md | 71 ++- docs/KNOWN_ISSUES.md | 318 +++++----- docs/TESTING.md | 10 +- package-lock.json | 80 +++ package.json | 4 + server.ts | 544 ++++++++++++++++-- src/App.tsx | 8 +- src/__tests__/app.smoke.test.tsx | 16 + src/__tests__/notificationService.test.ts | 116 ++++ src/components/chat-ui/ChatMessageMenu.tsx | 6 +- src/components/chat-ui/EmojiPickerMenu.tsx | 6 +- src/components/chat-ui/LazyEmojiPicker.tsx | 37 ++ src/features/auth/LoginScreen.tsx | 43 +- src/features/chat/MessageRequestsScreen.tsx | 4 + src/features/chat/SearchUserScreen.tsx | 35 +- .../chat/services/pushNotificationService.ts | 49 +- .../notifications/LikeNotificationsScreen.tsx | 7 +- .../notifications/NotificationsScreen.tsx | 11 +- src/features/profile/UserProfileScreen.tsx | 7 + .../settings/NotificationsSettingsScreen.tsx | 30 +- src/lib/apiClient.ts | 64 +++ src/providers/CallProvider.tsx | 3 +- src/services/AIService.ts | 21 +- src/services/db/notificationService.ts | 119 ++++ src/services/db/transactionQueueService.ts | 5 + src/services/db/userProfileService.ts | 1 - src/types/index.ts | 1 - vite.config.ts | 69 +++ 39 files changed, 1452 insertions(+), 385 deletions(-) create mode 100644 src/__tests__/notificationService.test.ts create mode 100644 src/components/chat-ui/LazyEmojiPicker.tsx create mode 100644 src/lib/apiClient.ts create mode 100644 src/services/db/notificationService.ts diff --git a/.env.example b/.env.example index 5c6e705..81b0351 100644 --- a/.env.example +++ b/.env.example @@ -51,9 +51,15 @@ GITHUB_CLIENT_SECRET= # Server-side Supabase client (bypasses RLS — server only) SUPABASE_SERVICE_ROLE_KEY= -# Base URL used to build OAuth redirects +# Base URL used to build OAuth redirects, the sitemap origin, and the first +# entry of the CORS/origin allowlist. APP_URL= +# Extra browser origins allowed to call /api/* (comma-separated). +# Same-origin requests are always allowed, so this is only needed when the +# frontend and server are deployed on different hosts. +ALLOWED_ORIGINS= + # Set to "production" to serve dist/ instead of the Vite dev middleware NODE_ENV= diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 530b56b..f94adfd 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -30,7 +30,35 @@ jobs: - name: Install dependencies run: npm install + # `vite build` does not typecheck, so without this an entire class of + # breakage ships silently. Both of these are expected to pass. + - name: Typecheck + run: npm run lint + + - name: Test + run: npm test + - name: Build + # VITE_BASE_URL is what makes the bundle work off /grixchat/ instead of + # the domain root — without it every /assets/… URL 404s to a blank page. + # + # The VITE_* values are public client configuration (the anon key is + # designed to be shipped). Add them under + # Settings → Secrets and variables → Actions. Undefined ones are empty, + # which only means the deployed client has no backend attached. + env: + VITE_BASE_URL: /grixchat/ + VITE_SUPABASE_URL: ${{ secrets.VITE_SUPABASE_URL }} + VITE_SUPABASE_ANON_KEY: ${{ secrets.VITE_SUPABASE_ANON_KEY }} + VITE_FIREBASE_API_KEY: ${{ secrets.VITE_FIREBASE_API_KEY }} + VITE_FIREBASE_AUTH_DOMAIN: ${{ secrets.VITE_FIREBASE_AUTH_DOMAIN }} + VITE_FIREBASE_PROJECT_ID: ${{ secrets.VITE_FIREBASE_PROJECT_ID }} + VITE_FIREBASE_STORAGE_BUCKET: ${{ secrets.VITE_FIREBASE_STORAGE_BUCKET }} + VITE_FIREBASE_MESSAGING_SENDER_ID: ${{ secrets.VITE_FIREBASE_MESSAGING_SENDER_ID }} + VITE_FIREBASE_APP_ID: ${{ secrets.VITE_FIREBASE_APP_ID }} + VITE_FIREBASE_VAPID_KEY: ${{ secrets.VITE_FIREBASE_VAPID_KEY }} + VITE_FIREBASE_DATABASE_URL: ${{ secrets.VITE_FIREBASE_DATABASE_URL }} + VITE_LIVEKIT_URL: ${{ secrets.VITE_LIVEKIT_URL }} run: | npm run build cp dist/index.html dist/404.html diff --git a/AGENTS.md b/AGENTS.md index 3b8cd84..87fe0b7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,7 +12,7 @@ npm install npm run dev:mock # full app, no credentials → http://localhost:3000 # login: demo@grixchat.app / grixchat -npm test # 78 tests, ~9s +npm test # 85 tests, ~11s npm run lint # tsc --noEmit → 0 errors ``` @@ -97,7 +97,13 @@ Initial loads are 20–30 rows. `ChatService.getMessages(id, limit = 50)`. - **No loose `any`.** There are currently 470 of them — that is technical debt to burn down, not a licence to add more. - `src/types/database.types.ts` **does not exist yet**. Generate it - (`supabase gen types typescript`) and prefer it over hand-written row shapes. + (`supabase gen types typescript --project-id `) and prefer it over + hand-written row shapes. +- Browser → `/api` calls go through `src/lib/apiClient.ts`; it attaches the + Supabase access token the server verifies. Never call the API routes with a + bare `fetch` — you will get a 401. +- Notifications: write through `services/db/notificationService.ts` only, and + read the `content` column (`sql/01_core_schema.sql` has no `text`). ### File size @@ -135,7 +141,7 @@ aliased to `dev/mock/` in `vitest.config.ts` so a test can never reach a real project. ```bash -npm test # 78 tests, 5 files +npm test # 85 tests, 6 files npm run test:watch ``` @@ -161,16 +167,18 @@ Rules: |---|---| | `npm run build` | ✅ passes | | `npm run dev` / `dev:mock` | ✅ passes | -| `npm test` | ✅ 78/78 | +| `npm test` | ✅ 85/85 | | `npm run lint` | ✅ 0 errors | | Dead code | ✅ **0 files** — 189/189 reachable. See [`docs/DEAD_CODE.md`](./docs/DEAD_CODE.md) | | Tables queried but missing from `sql/` | ✅ 0 | | RPCs called but missing from `sql/` | ✅ 0 | | Vercel deploy | ✅ fixed — duplicate server deleted, `vercel.json` → `server.ts` | -| GitHub Pages deploy | ⚠️ needs `VITE_BASE_URL=/grixchat/` in the workflow | -| `/api/send-notification`, `/api/upload-file` | 🔴 **unauthenticated** — fix before any public deploy | -| `notifications` table | ⚠️ nothing writes to it any more; reader uses `text`, schema says `content` | -| Test coverage | ⚠️ only the login→chat path is exercised | +| GitHub Pages deploy | ✅ `VITE_BASE_URL=/grixchat/` set in the workflow | +| `/api/send-notification`, `/api/upload-file` | ✅ **authenticated** + rate limited + allowlisted (see `requireAuth`) | +| Notifications inbox | ✅ written by `services/db/notificationService.ts`, read from `content` | +| CI | ✅ typecheck + test + build | +| Deploy secrets | 🧑 **not wired** — see KNOWN_ISSUES "the three things code cannot do" | +| Test coverage | ⚠️ only login→chat, the notification writer and the reset route are exercised | Full prioritised list: **[`docs/KNOWN_ISSUES.md`](./docs/KNOWN_ISSUES.md)**. diff --git a/README.md b/README.md index 1ce1b2d..94e9ba7 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ To support more than 50,000 active users comfortably on Supabase's free tier, da ## 📁 System Registry Map - `/src/providers`: Application context singletons (Supabase `AuthProvider`, global WebRTC `CallProvider`). -- `/src/features`: Modular screens broken into focus zones (`chat`, `call`, `profile`, `search`, `reels`). +- `/src/features`: Modular screens broken into focus zones (`chat`, `call`, `profile`, `search`, `stories`, `github`, `grixai`). - `/src/components`: UI layouts, bottom/top navigation components, and global drop-downs. - `/sql`: The **only** place for schema — numbered migrations `01_` … `08_`, plus `00_master_instructions.md`. Contains tables, PostgreSQL functions, triggers, row-level security and indices. - `/docs`: Developer documentation — orientation, setup, testing, data model, known issues. @@ -72,10 +72,13 @@ npm run dev ### 4. Test and build ```bash -npm test # 78 tests +npm test # 85 tests npm run lint # tsc --noEmit npm run build # vite build + server bundle ``` +CI (`.github/workflows/deploy.yml`) runs all three before deploying to Pages, +and builds with `VITE_BASE_URL=/grixchat/`. + --- Crafted under high-precision directives for the GrixChat Mobile Ecosystem. 🌌 diff --git a/dev/mock/auth.ts b/dev/mock/auth.ts index 1edf633..d51ca5e 100644 --- a/dev/mock/auth.ts +++ b/dev/mock/auth.ts @@ -147,7 +147,6 @@ class MockAuth { hidden_chats: [], archived_chats: [], hidden_chat_settings: { secretCode: null, showMenuEntry: true }, fcm_tokens: [], - saved_posts: [], }; store.table('users').push(profile); store.emit('INSERT', 'users', profile); diff --git a/dev/mock/query.ts b/dev/mock/query.ts index 8ed1a10..4f01e9b 100644 --- a/dev/mock/query.ts +++ b/dev/mock/query.ts @@ -339,6 +339,8 @@ export class MockQueryBuilder implements PromiseLike<{ data: any; error: any; co if (out.created_at === undefined) out.created_at = nowISO(); if (this.table === 'users' && out.updated_at === undefined) out.updated_at = nowISO(); if (this.table === 'conversations' && out.updated_at === undefined) out.updated_at = nowISO(); + // Mirrors `notifications.is_read BOOLEAN DEFAULT FALSE` from sql/01. + if (this.table === 'notifications' && out.is_read === undefined) out.is_read = false; return out; } diff --git a/dev/mock/seed.ts b/dev/mock/seed.ts index 8ff5bcf..1352a15 100644 --- a/dev/mock/seed.ts +++ b/dev/mock/seed.ts @@ -64,7 +64,6 @@ export function buildSeed() { archived_chats: [], hidden_chat_settings: { secretCode: null, showMenuEntry: true }, fcm_tokens: [], - saved_posts: [], }, { id: SEED.aarav, @@ -88,7 +87,6 @@ export function buildSeed() { archived_chats: [], hidden_chat_settings: { secretCode: null, showMenuEntry: true }, fcm_tokens: [], - saved_posts: [], }, { id: SEED.sanya, @@ -112,7 +110,6 @@ export function buildSeed() { archived_chats: [], hidden_chat_settings: { secretCode: null, showMenuEntry: true }, fcm_tokens: [], - saved_posts: [], }, { id: SEED.rohit, @@ -136,7 +133,6 @@ export function buildSeed() { archived_chats: [], hidden_chat_settings: { secretCode: null, showMenuEntry: true }, fcm_tokens: [], - saved_posts: [], }, { id: SEED.priya, @@ -160,7 +156,6 @@ export function buildSeed() { archived_chats: [], hidden_chat_settings: { secretCode: null, showMenuEntry: true }, fcm_tokens: [], - saved_posts: [], }, { id: SEED.kabir, @@ -184,7 +179,6 @@ export function buildSeed() { archived_chats: [], hidden_chat_settings: { secretCode: null, showMenuEntry: true }, fcm_tokens: [], - saved_posts: [], }, { id: SEED.meera, @@ -208,7 +202,6 @@ export function buildSeed() { archived_chats: [], hidden_chat_settings: { secretCode: null, showMenuEntry: true }, fcm_tokens: [], - saved_posts: [], }, { id: SEED.official, @@ -232,7 +225,6 @@ export function buildSeed() { archived_chats: [], hidden_chat_settings: { secretCode: null, showMenuEntry: true }, fcm_tokens: [], - saved_posts: [], }, ]; diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f89627a..92e02bf 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -28,6 +28,19 @@ The Express server exists only for things a browser cannot do: holding secret API keys, OAuth code exchange, and FCM's service-account auth. **It holds no application data.** All state lives in Supabase. +Every `/api` route runs the same security chain (`server.ts`): + +``` +helmet → cors(allowlist) → origin guard → rate limit → json(≤256kB) + → requireAuth (Supabase JWT) → route-specific authorisation +``` + +Routes that fan out or cost money add their own limiter, and the two routes +that used to trust the client — `send-notification` and `livekit-token` — derive +their recipients/grant from the database instead. The browser side of that +contract lives in `src/lib/apiClient.ts` (`apiFetch` / `apiPostJson`), which +attaches the session token. + --- ## Boot sequence diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index bb4fe98..b383c90 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -43,7 +43,7 @@ engine) via a Vite alias, so nothing touches the network and no `.env` is needed. See **[DEV_SETUP.md](./DEV_SETUP.md)**. ```bash -npm test # 78 tests, 5 files, ~10s — includes a real login→chat-list render +npm test # 85 tests, 6 files, ~11s — includes a real login→chat-list render npm run lint # tsc --noEmit → 0 errors npm run build # production bundle ``` @@ -57,33 +57,40 @@ All three currently pass. | Check | Result | |---|---| | `npm run lint` | ✅ 0 errors | -| `npm test` | ✅ 78/78 | +| `npm test` | ✅ 85/85 | | `npm run build` | ✅ exit 0 | | Dead code | ✅ **0 files** (189/189 reachable) | | Tables queried but missing from `sql/` | ✅ **0** | | RPCs called but missing from `sql/` | ✅ **0** | -| Unauthenticated server endpoints | 🔴 2 — see below | +| Unauthenticated server endpoints | ✅ **0** — every `/api` route is authenticated (mock mode excepted) | +| Notifications inbox | ✅ has a write path (`services/db/notificationService.ts`) | | Vercel deploy | ✅ fixed (`vercel.json` → root `server.ts`) | -| GitHub Pages deploy | ⚠️ needs `VITE_BASE_URL=/grixchat/` | +| GitHub Pages deploy | ✅ `VITE_BASE_URL=/grixchat/` set in the workflow | +| CI | ✅ typecheck + test + build | --- -## The two things that will still bite you +## The three things that will still bite you -### 1. Two endpoints are wide open +### 1. Deploy secrets are not wired up yet -`/api/send-notification` and `/api/upload-file` have **no auth, no origin -check, no rate limit**. The first lets anyone push a notification to any FCM -token; the second is a free 100 MB file host. Fix before any public deploy. -→ **[KNOWN_ISSUES.md](./KNOWN_ISSUES.md#-p0--security)** +The server endpoints now verify a Supabase JWT. That means `VITE_SUPABASE_URL`, +`VITE_SUPABASE_ANON_KEY` (and the rest of `.env.example`) have to exist **on the +server host**, and the `VITE_*` values must be added as GitHub Actions secrets +for the Pages build — without them the Supabase SDK is compiled out of the +bundle and the deployed app cannot sign in (the build prints a warning). +→ **[KNOWN_ISSUES.md → the three things code cannot do](./KNOWN_ISSUES.md#-read-this-first--the-three-things-code-cannot-do)** -### 2. Nothing writes to `notifications` +### 2. Rate limits and the origin guard are per-process, in-memory -Every notification writer lived in the deleted `features/home/` components. The -notification screens still read the table, so they will always be empty. -Either restore a write path or remove the screens. -Also: `NotificationsScreen.tsx:118` reads `notif.text` but the schema column -is `content`. +`express-rate-limit` counts per running instance. On a serverless target that +scales out, treat the limits as a speed bump, not a quota. + +### 3. Nothing else. Really. + +The notification tables, the reset-password route, the Pages base path, the +bundle split and the open endpoints were the outstanding items; each is fixed +and covered in **[KNOWN_ISSUES.md](./KNOWN_ISSUES.md)**. --- diff --git a/docs/DATA_MODEL.md b/docs/DATA_MODEL.md index c692029..d82bf62 100644 --- a/docs/DATA_MODEL.md +++ b/docs/DATA_MODEL.md @@ -47,8 +47,9 @@ Profile row, 1:1 with `auth.users`. | `hidden_chat_settings` | JSONB | `{secretCode, showMenuEntry}` | | `fcm_tokens` | TEXT[] | FCM registration tokens | -> 🔴 `services/db/userProfileService.ts:192` reads `saved_posts` — **not in the -> schema**. Add the column or drop the field. +> ✅ The `saved_posts` read that lived in `userProfileService.ts` was a leftover +> from the deleted Reels feature — the column never existed in `sql/`, so the +> field was dropped from the code and the mock instead of being added. ### `follows` — `:56` `id`, `follower_id`, `following_id`, `created_at`. `UNIQUE(follower_id, following_id)`. @@ -95,12 +96,15 @@ Per-user chat customisation. `id`, `user_id`, `receiver_id`, `nickname`, `id`, `user_id`, `from_user_id`, `type`, `title`, `content`, `is_read`, `post_id`, `created_at`. -> 🔴 **Two problems.** -> 1. **Nothing writes to it.** Every insert lived in the deleted -> `features/home/components/`. All five remaining call sites are reads. -> `grep -rn "from('notifications')" src | grep -c insert` → `0`. -> 2. **Column mismatch.** The schema defines `content`; the reader at -> `NotificationsScreen.tsx:118` reads `notif.text`. +> ✅ Both problems are fixed. `services/db/notificationService.ts` is the single +> write path (`create` / `notifyFollow` / `notifySystem`), called when a +> connection is made or accepted in `UserProfileScreen`, `MessageRequestsScreen` +> and the offline follow worker. Readers use `content` — the column the schema +> defines — and the writer only writes `content`. +> +> Writes need no new policy: `sql/01_core_schema.sql` already grants +> `INSERT` on `notifications` to `authenticated`, and `UPDATE` to the row owner +> (used to mark notifications read). ### `posts` — `sql/02_posts_and_interactions_schema.sql` `id`, `user_id`, `image_url`, `caption`, `created_at`. diff --git a/docs/DEAD_CODE.md b/docs/DEAD_CODE.md index 5c69983..ea3e245 100644 --- a/docs/DEAD_CODE.md +++ b/docs/DEAD_CODE.md @@ -17,7 +17,7 @@ Verification after the deletion: | Reachability re-scan | **0 dead files** (189/189 reachable from entry points) | | Broken relative imports | **0** | | `npm run lint` (`tsc --noEmit`) | **exit 0, 0 errors** — was 11 | -| `npm test` | **78/78 pass** | +| `npm test` | **85/85 pass** | | `npm run build` | **exit 0** | | Dev server module graph | **55 modules walked, 0 failures** | | `npm install` | 103 packages removed (7 unused deps) | diff --git a/docs/DEV_SETUP.md b/docs/DEV_SETUP.md index 4834873..97a60bb 100644 --- a/docs/DEV_SETUP.md +++ b/docs/DEV_SETUP.md @@ -99,8 +99,7 @@ cp .env.example .env npm run dev ``` -`.env.example` is **incomplete** — it lists 6 variables and the codebase reads -21. The full list: +`.env.example` lists every variable the codebase reads. The full list: ### Frontend (`VITE_*` — exposed to the browser bundle) @@ -117,12 +116,17 @@ npm run dev | `VITE_FIREBASE_VAPID_KEY` | `NotificationHandler.tsx` | | `VITE_FIREBASE_DATABASE_URL` | presence code | | `VITE_LIVEKIT_URL` | `src/providers/CallProvider.tsx` | -| `VITE_IMGBB_API_KEY` | `features/reels/grixtube/TubeUploadScreen.tsx` — ⚠️ see note | +| `VITE_BASE_URL` | build-time path prefix (`/grixchat/` on GitHub Pages) | -> ⚠️ **`VITE_IMGBB_API_KEY` is a secret exposed to the browser.** Any -> `VITE_`-prefixed variable is inlined into the shipped bundle in plaintext. -> That file is currently dead code, so the key is not live — but the pattern -> must not be copied. Proxy uploads through the server instead. +> ⚠️ Any `VITE_`-prefixed variable is inlined into the shipped bundle in +> plaintext. Only the Supabase anon key and the Firebase web config belong +> there. Secrets go through `server.ts`. + +> ⚠️ `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` must be present at **build** +> time. `src/lib/supabase.ts` returns `null` without them, Rollup folds that to +> `null` and tree-shakes the whole SDK out of the bundle — the build succeeds +> and the app can never reach the backend. `vite.config.ts` now warns loudly +> when a production build is missing them. ### Server (`process.env` — never exposed) @@ -132,17 +136,31 @@ npm run dev | `FIREBASE_SERVICE_ACCOUNT` | `/api/send-notification` (JSON, newlines may be escaped) | | `LIVEKIT_API_KEY` / `LIVEKIT_API_SECRET` | `/api/livekit-token` | | `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` | `/api/github/auth-url` | -| `SUPABASE_SERVICE_ROLE_KEY` | server-side Supabase client | -| `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` | server-side Supabase client | -| `APP_URL` | OAuth redirect base | -| `NODE_ENV` | `production` disables the Vite middleware and serves `dist/` | +| `SUPABASE_SERVICE_ROLE_KEY` | privileged reads/writes (FCM token cleanup). Falls back to the anon key + the caller's JWT. | +| `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` | **required server-side too** — every `/api` route verifies the caller's JWT against the project | +| `APP_URL` | OAuth redirect base, sitemap origin, first CORS allowlist entry | +| `ALLOWED_ORIGINS` | extra comma-separated browser origins allowed to call `/api/*` | +| `MOCK_SUPABASE` | `1` skips JWT verification for the credential-free dev loop (never in production) | +| `NODE_ENV` | `production` disables the Vite middleware, serves `dist/`, hides `/api/github/debug` | Every missing credential degrades gracefully — the server logs a warning and returns a simulated response rather than crashing. That is deliberate, but it -also means **a misconfigured deploy looks like it is working.** +also means **a misconfigured deploy looks like it is working.** The one +exception is authentication: without `VITE_SUPABASE_URL` + +`VITE_SUPABASE_ANON_KEY` the `/api` routes answer `503`, on purpose. + +--- + +## GitHub Actions secrets -> **`VITE_GROQ_API_KEY`** appears in `.env.example` but is read nowhere in the -> codebase. `groq-sdk` is installed and unused. Both are dead. +The Pages workflow builds the client, so it needs the `VITE_*` values from the +table above. Add them under **Settings → Secrets and variables → Actions** +(`.github/workflows/deploy.yml` already references them). Undefined secrets +resolve to empty strings, so the build still succeeds — you just get a client +with no backend attached, and the build log says so. + +**Server secrets are not needed for the Pages deploy** (it is a static build); +they belong on whichever host runs `server.ts`. --- @@ -167,7 +185,7 @@ proxies. | `npm run build` | `vite build` + esbuild bundle of `server.ts` → `dist/server.cjs` | | `npm run build:mock` | static bundle wired to the mock (for demoing without a backend) | | `npm run start` | serve the built `dist/` via `dist/server.cjs` | -| `npm run test` | `vitest run` — 78 tests | +| `npm run test` | `vitest run` — 85 tests | | `npm run test:watch` | watch mode | | `npm run lint` | `tsc --noEmit` — **currently fails, see KNOWN_ISSUES** | | `npm run preview` / `preview:mock` | serve the built bundle | @@ -178,23 +196,18 @@ proxies. ### Vercel (`vercel.json`) -⚠️ **Broken for two features.** `vercel.json` builds `src/server/server.ts`, -which lacks `/api/grix-ai` and `/api/livekit-token`. Either point Vercel at the -root `server.ts`, or port those two routes across. Until then, GrixAI and -calling 404 in production while working locally. +✅ `vercel.json` points at the root `server.ts` (the duplicate +`src/server/server.ts` was deleted), so `/api/grix-ai` and +`/api/livekit-token` exist there. Set the server-side variables listed above — +including `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY`, which the auth layer +needs — or every `/api` call answers `503`. ### GitHub Pages (`.github/workflows/deploy.yml`) -⚠️ **Likely broken.** The workflow deploys `dist/` to Pages, but -`vite.config.ts` sets `base: '/'` (now overridable via `VITE_BASE_URL`) and the -repo has no `CNAME`. A `GothwadTech/grixchat` Pages URL is served from -`/grixchat/`, so every absolute `/assets/…` path 404s and the app renders -blank. - -Fix: set `VITE_BASE_URL=/grixchat/` in the workflow, or add a `CNAME` for a -custom domain. - -> This is static analysis — an actual Pages deploy was not run. +✅ The workflow builds with `VITE_BASE_URL=/grixchat/`, so assets resolve under +the sub-path Pages serves from. Add the `VITE_*` Actions secrets (above) for the +deployed client to reach a backend; add a `CNAME` file if you move to a custom +domain at the domain root, and drop `VITE_BASE_URL` at the same time. ### Android (TWA / WebView) diff --git a/docs/KNOWN_ISSUES.md b/docs/KNOWN_ISSUES.md index ce19556..4c0023a 100644 --- a/docs/KNOWN_ISSUES.md +++ b/docs/KNOWN_ISSUES.md @@ -1,223 +1,243 @@ # Known Issues -Prioritised. Verified against the code on 2026-10-10, after the dead-code -removal. The command that proved each item is noted where useful. +Prioritised. Originally verified against the code on 2026-10-10; **re-verified +and largely fixed on 2026-10-11** (see the status on each item). **Severity:** 🔴 blocks a safe deploy · 🟠 breaks a feature or misleads a developer · 🟡 quality / performance · 🟢 nice to have ---- - -## 🔴 P0 — Security +**Legend:** ✅ fixed in code · ⚠️ partly fixed · ❌ still open · 🧑 needs a +human step (SQL run, secret, or a product decision) -### 1. `/api/send-notification` is an open push relay +--- -`server.ts:153`. No authentication, no origin check, no rate limit. +## 🧑 Read this first — the three things code cannot do -```bash -curl -X POST https:///api/send-notification \ - -H 'Content-Type: application/json' \ - -d '{"tokens":[""],"title":"Alert","body":"Tap here"}' -``` +Everything that could be fixed from the repository alone **has been**. These +tasks need Supabase, GitHub settings or a decision: -FCM tokens live client-side (`users.fcm_tokens`), so a leaked token plus this -endpoint is a spam/phishing channel to the whole user base. +| # | Task | Where | Why it matters | +|---|---|---|---| +| A | Add `VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY` (+ the `VITE_FIREBASE_*` and `VITE_LIVEKIT_URL` values) as **Actions secrets** | GitHub → Settings → Secrets and variables → Actions | The Pages workflow now passes them to the build. **Without them the Supabase SDK is compiled out and the deployed app cannot sign in** — the build warns loudly in the log. | +| B | Set the server secrets on whichever host runs `server.ts` (Vercel/Cloudflare): `GEMINI_API_KEY`, `FIREBASE_SERVICE_ACCOUNT`, `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET`, `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `SUPABASE_SERVICE_ROLE_KEY`, `APP_URL` | host dashboard | The new auth layer verifies JWTs against `VITE_SUPABASE_URL` + `VITE_SUPABASE_ANON_KEY`, so those two must be set **server-side** as well. | +| C | Decide the fate of `call_candidates` (issue 7) | Supabase SQL editor | It is defined but unused. Drop it with:
`DROP TABLE IF EXISTS public.call_candidates CASCADE;`
or keep it and adopt the table-based signalling in `db/3_webrtc_signaling_architecture.md`. | -**Fix:** verify a Supabase JWT (`Authorization: Bearer`) and confirm the caller -participates in the conversation; add a per-IP rate limit. +Optional: set `ALLOWED_ORIGINS=https://your-domain.tld,https://your-other.tld` +(comma-separated) on the server to extend the CORS/origin allowlist beyond +same-origin + `APP_URL`. -### 2. `/api/upload-file` is an open file host +--- -`server.ts:346`. Multer limit **100 MB per file**, `express.json` limit 50 MB. -No auth, no rate limit, no MIME allowlist. Re-uploads to `catbox.moe` / -`gofile.io`, so the server is a free anonymous file host on your bandwidth. +## ✅ P0 — Security (all fixed) -**Fix:** require auth; cap size per media type; rate limit; preferably upload -straight to Supabase Storage with a signed URL. +### 1. `/api/send-notification` was an open push relay — ✅ FIXED -### 3. No server hardening at all +It is no longer a token relay at all: -``` -grep -n "cors\|helmet\|rate" server.ts → 0 results -``` +- **Auth:** requires `Authorization: Bearer `, verified + with `supabase.auth.getUser()` (`server.ts` → `requireAuth`). +- **Recipients are derived server-side.** The client now sends only + `{ conversationId, body }`; the server checks the caller is a participant and + reads the other participants' `fcm_tokens` itself. Client-supplied token + lists are ignored for conversations. +- **Self-test mode** (the diagnostics button in notification settings) accepts + tokens only if they are already registered on the caller's own profile. +- **Title can no longer be spoofed** — it is read from the sender's row. +- **Limits:** 200-char body, 20 requests/min/IP (`notificationLimiter`). +- **Bonus:** `removeInvalidFcmToken()` no longer scans the whole `users` table + — it uses `contains('fcm_tokens', [...])`. -No CORS policy, no security headers, no rate limiting on any route. +Client side: `pushNotificationService.ts` and `NotificationsSettingsScreen.tsx` +go through the new `src/lib/apiClient.ts`, which attaches the session token. -**Fix:** `helmet()` + an explicit `cors({origin})` allowlist + `express-rate-limit`. +### 2. `/api/upload-file` was an open 100 MB file host — ✅ FIXED ---- +- Auth required (`requireAuth`). +- **MIME allowlist** (`ALLOWED_MIME_TYPES`) — no more anonymous `.exe`, and + `image/svg+xml` is deliberately excluded (script container). +- **Size caps by media type:** images 15 MB, audio 25 MB, documents 25 MB, + video 50 MB (hard ceiling), 1 file per request, temp file always unlinked. +- Rate limited to 8 uploads/min/IP (`uploadLimiter`). -## 🟠 P1 — Correctness +> No caller in this repository uses this route. It is kept for the Android +> WebView wrapper, but now requires a signed-in session. -### 4. Nothing writes to `notifications` +### 3. No server hardening at all — ✅ FIXED -Every insert into `notifications` lived in `features/home/components/` -(`PostCard.tsx`, `VideoPostCard.tsx`), which was dead code and has been deleted. -The remaining five call sites are all **reads**: +`server.ts` now runs: -``` -src/components/layout/TabHeader.tsx:82 select -src/features/notifications/NotificationsScreen.tsx select -src/features/notifications/LikeNotificationsScreen.tsx:29 select -src/features/notifications/LikeNotificationsScreen.tsx:52 update(is_read) -``` +| Layer | What | +|---|---| +| `helmet()` | nosniff, referrer policy, `X-Powered-By` off, CORP `cross-origin`. CSP/COOP/COEP/frameguard are deliberately relaxed so the Vite dev server, the GitHub OAuth popup and the WebView/TWA wrapper keep working (documented inline). | +| `cors()` | Reflects an origin only when it is same-origin or allowlisted (`APP_URL` + `ALLOWED_ORIGINS` + localhost). | +| Origin guard | Cross-origin writes to `/api/*` are refused with **403** (CSRF belt-and-braces). Loopback/bind-all hosts are exempt so tunnel/preview deployments keep working. | +| `express-rate-limit` | global 300/min · API 60/min · notifications 20/min · uploads 8/min · AI 20/min, per IP. `trust proxy` is set so the real client IP is used behind Vercel/preview proxies. | +| Body limits | `express.json` is opt-in per route: **256 kB** by default, 32 MB only for the GitHub push routes. The blanket 50 MB parser is gone. | +| Error handling | Unknown `/api/*` → JSON 404; malformed JSON → 400; oversized body → 413. | + +Also hardened while in there: `/api/livekit-token` requires auth **and** checks +the caller actually participates in that call/conversation (the token identity +comes from the verified session, not the request body); `/api/grix-ai` requires +auth (upstream quota); `/api/github/debug` returns 404 in production. -`grep -rn "from('notifications')" src | grep -c insert` → **0** +--- -So the notification screens will always be empty. +## 🟠 P1 — Correctness -**Fix:** either add a write path (e.g. on new messages / follows) or remove the -screens. Decide deliberately — right now the UI advertises a feature the -backend never feeds. +### 4. Nothing wrote to `notifications` — ✅ FIXED -### 5. `notifications` column mismatch +New `src/services/db/notificationService.ts` is the single write path +(`create`, `notifyFollow`, `notifySystem`). It is wired into every place a +connection is created: -`sql/01_core_schema.sql:157` defines `title` and **`content`**. -`NotificationsScreen.tsx:118` reads **`notif.text`**. +- `features/profile/UserProfileScreen.tsx` — send request, and accept request +- `features/chat/MessageRequestsScreen.tsx` — accept +- `services/db/transactionQueueService.ts` — the offline follow worker -```tsx -{notif.text} -``` +Re-following updates the existing row (bumped to unread) instead of stacking +duplicates. Failures are swallowed with a warning so they can never abort the +follow itself. Covered by `src/__tests__/notificationService.test.ts` (6 tests). -Whatever write path you add must agree with the reader and the schema. Pick -`content` (matches the migration) and change the reader. +### 5. `notifications` column mismatch — ✅ FIXED -### 6. `users.saved_posts` is not in the schema +`sql/01_core_schema.sql` is right: the column is `content`. Both readers now +map `content` (with a `text` fallback kept only for rows written by older +builds), and the new writer only ever writes `content`. The mock seeds both and +the mock now applies the `is_read DEFAULT FALSE` the SQL declares. -`services/db/userProfileService.ts:192` reads and writes it; `sql/` does not -define it. Either add the column or drop the field. +### 6. `users.saved_posts` was not in the schema — ✅ FIXED -### 7. `call_candidates` is defined but never used +The column never existed; the only consumers were a read in +`userProfileService.ts` and a field on `UserProfile`, both leftovers from the +deleted Posts/Reels features. Removed from the code **and** from `dev/mock/`, so +the mock keeps mirroring `sql/`. -`sql/01_core_schema.sql:135` creates it for WebRTC ICE signalling, but the live -calling path (`providers/CallProvider.tsx`) signals over Broadcast channels. -Either use it or drop it. `db/3_webrtc_signaling_architecture.md` describes the -table-based design that was not adopted. +### 7. `call_candidates` is defined but never used — ❌ STILL OPEN (needs SQL) -### 8. Password reset has no path +The live calling path (`providers/CallProvider.tsx`) signals over Broadcast +channels, so the table is dead weight. Dropping it is a one-line migration the +repo cannot run for you — see task **C** at the top. No code change is pending +on either side of the decision. -```tsx -// App.tsx -} /> -``` +### 8. Password reset had no path — ✅ FIXED -`ForgotPasswordScreen.tsx` was deleted as dead code. `LoginScreen` still has a -working `isForgotPassword` mode that calls `auth.resetPasswordForEmail`, so -users can reset from the login screen — but the dedicated route is a dead end. -Either wire the route to that mode or remove it. +`/forgot-password` now renders `LoginScreen` in its reset mode instead of +redirecting to `/login`. The screen derives the mode from the route and keeps +`/login` ↔ `/forgot-password` in sync (including browser back/forward), so the +existing working `auth.resetPasswordForEmail` flow is finally reachable from a +URL. Covered by a new case in `src/__tests__/app.smoke.test.tsx`. --- -## 🟡 P2 — Deploy & CI +## 🟡 P2 — Deploy & CI (all fixed) -### 9. GitHub Pages base path +### 9. GitHub Pages base path — ✅ FIXED -`vite.config.ts` now reads `base: process.env.VITE_BASE_URL || '/'`. The -workflow deploys `dist/` to Pages for `GothwadTech/grixchat`, which serves from -`/grixchat/`, and there is no `CNAME`. Every absolute `/assets/…` URL would 404 -→ blank page. +`.github/workflows/deploy.yml` builds with `VITE_BASE_URL: /grixchat/`, so +`dist/assets/…` is emitted under the sub-path Pages serves from. -**Fix:** add to the workflow's Build step: +### 10. CI did not typecheck or test — ✅ FIXED -```yaml -env: - VITE_BASE_URL: /grixchat/ -``` +The workflow now runs `npm run lint` (tsc) and `npm test` before `npm run +build`. Both pass. -or add a `CNAME` for a custom domain. +### 11. `.env.example` and CI env were not connected — ✅ FIXED -> *Static analysis — an actual Pages deploy was not executed.* +The Pages build receives every `VITE_*` value from Actions secrets (add them — +task **A**). Two extra safeguards came out of this: -### 10. CI does not typecheck or test - -`.github/workflows/deploy.yml` runs only `npm run build`. Vite does not -typecheck, so type errors ship silently. - -**Fix:** - -```yaml -- name: Lint - run: npm run lint -- name: Test - run: npm test -``` - -Both currently pass, so this is free. - -### 11. `.env.example` and CI env are not connected - -`.env.example` now lists all 22 variables, but the workflow sets none. The -GitHub Pages build works because it is client-only, but any server-side deploy -target needs them wired up. +- `vite.config.ts` prints a loud build-time warning when a production build has + no `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY`. +- That warning exists because of a nastier trap found while fixing this: + `src/lib/supabase.ts` returns `null` without those two values, Rollup + constant-folds that into `null`, and then **tree-shakes the entire Supabase + SDK out of the bundle**. The build "succeeds", the app just can never reach + the backend. With the credentials present the SDK is bundled normally + (`vendor-supabase`, 207 kB). --- -## 🟡 P2 — Performance +## 🟡 P2 — Performance (all fixed) -### 12. Main bundle is 1.14 MB (317 KB gzip) +### 12. Main bundle was 1.14 MB — ✅ FIXED + +`build.rollupOptions.output.manualChunks` splits the heavyweights. With +credentials configured, the build now emits: ``` -dist/assets/index-*.js 1,148.43 kB │ gzip: 316.76 kB -dist/assets/MessageList-*.js 415.67 kB │ gzip: 100.87 kB -dist/assets/GithubScreen-*.js 194.51 kB │ gzip: 59.89 kB +before after +index-*.js 1,148 kB → index-*.js 170 kB (gzip 43 kB) +MessageList-*.js 416 kB → MessageList-*.js 97 kB +GithubScreen-*.js 195 kB → GithubScreen-*.js 190 kB + → vendor-react 232 kB + → vendor-supabase 207 kB + → vendor-emoji 309 kB (lazy) + → vendor-livekit 527 kB (calls only) ``` -`vite.config.ts` has **no `manualChunks`**, so firebase + livekit + supabase -all land in one chunk. Vite emits its own >500 kB warning. - -**Fix:** split vendors with `build.rollupOptions.output.manualChunks`. -Deleting the dead features did not shrink this — the weight is in the vendor -libraries, not the app code. +### 13. `emoji-picker-react` statically imported twice — ✅ FIXED -### 13. `emoji-picker-react` is statically imported twice +Both call sites (`components/chat-ui/ChatMessageMenu.tsx` and +`EmojiPickerMenu.tsx`) now render `LazyEmojiPicker`, which wraps the package in +`React.lazy` + `Suspense`. The `Theme` enum is no longer imported statically +(that alone would have defeated the split), so the picker lives in its own chunk +and is fetched on first tap. -`ChatMessageMenu.tsx:18` and `EmojiPickerMenu.tsx:3`. A heavy dependency pulled -into the chat chunk. +### 14. ~350 `console.*` calls shipped to production — ✅ FIXED -**Fix:** `React.lazy`. - -### 14. 350 `console.*` statements ship to production - -`grep -rn "console\.\(log\|warn\|error\)" src | wc -l` → **350** (was 499). - -**Fix:** `esbuild.drop: ['console']` for the client build, or a logger that -no-ops in production. +`vite.config.ts` sets `esbuild.drop: ['console', 'debugger']` for production +builds only; dev keeps its logging. The built client went from 350+ calls to 20 +references, and those 20 are load-bearing: `ConsoleLoggerService` patching +`console` itself, and pre-existing `.catch(console.error)` — a *reference*, not +a call, so `drop` rightly leaves it alone. --- ## 🟢 P3 — Quality -### 15. 470 `any` usages +### 15. 470 `any` usages — ❌ STILL OPEN + +Now 478: this pass added exactly one in app code (`apiClient.ts`'s +`{ auth?: any }` cast, because the exported client is already `any`) and the +rest are in the new test file, which follows the existing `(row: any)` +convention. Everything else added by this pass is typed. The remaining burn-down +is mechanical, file-by-file work, not something to do blind. -`grep -rno ": any\|as any\|" src | wc -l` → **470** (was 624). -`AGENTS.md` forbids this. +### 16. `src/types/database.types.ts` does not exist — ❌ STILL OPEN (needs project id) -### 16. `src/types/database.types.ts` does not exist +Generating it requires the Supabase project: -`AGENTS.md` mandates strictly-typed Supabase schema definitions. +```bash +npx supabase gen types typescript --project-id > src/types/database.types.ts +``` -**Fix:** `npx supabase gen types typescript --project-id > src/types/database.types.ts` +Then prefer those row types over hand-written shapes. -### 17. Giant files +### 17. Giant files — ❌ STILL OPEN + +Unchanged: ``` 1244 features/github/GithubScreen.tsx 987 providers/CallProvider.tsx 844 features/chat/components/MessageBubble.tsx - 746 features/chat/ImagePreviewScreen.tsx - 739 features/chat/ChatSettingsScreen.tsx - 649 features/chat/components/ChatUserList.tsx - 603 features/auth/SignupScreen.tsx - 602 features/chat/ChatScreen.tsx - 581 App.tsx ``` -`AGENTS.md`: *"Do not bloat files like `App.tsx` or `ChatScreen.tsx`."* +Pure extraction work with real regression risk — worth doing deliberately, per +file, with tests, not as a drive-by. + +### 18. Stale reference in a live file — ✅ FIXED -### 18. Stale reference in a live file +`features/chat/SearchUserScreen.tsx` lost its dead `VideoGridItem` / +`ReelGridItem` components, the `SearchTab = 'users' | 'videos' | 'reels'` union +and the leftover `reel.likes_count` read (30 lines). Two related dead ends went +with it: -`features/chat/SearchUserScreen.tsx:73` renders `reel.likes_count` but the -screen only queries `users` — a leftover variable from the Reels feature. +- the `/search-user` route redirected to `/profile`, which made the “Discover + People” button in the notifications empty state a no-op. It now renders the + screen it already lazy-imported. +- the sitemap advertised `/reels` and `/tools`, two features that no longer + exist. It now lists real routes. --- @@ -226,7 +246,7 @@ screen only queries `users` — a leftover variable from the Reels feature. | Issue | Resolution | |---|---| | No way to run the app without credentials | `npm run dev:mock` + `dev/mock/` | -| No test infrastructure | Vitest + jsdom + Testing Library, **78 tests** | +| No test infrastructure | Vitest + jsdom + Testing Library, **85 tests** | | No agent context docs | `docs/` (7 files) + rewritten `AGENTS.md` | | `npm run lint` failed with 11 errors | dead code deleted → **0 errors** | | 13,103+ lines of unreachable code | **146 files deleted, 0 remaining** | @@ -234,10 +254,16 @@ screen only queries `users` — a leftover variable from the Reels feature. | 5 RPCs called but never defined | same → **0** | | Two divergent Express servers | `src/server/server.ts` deleted; `vercel.json` → `server.ts` | | Vercel missing `/api/grix-ai` + `/api/livekit-token` | fixed by the above | -| `vite.config.ts` hardcoded `base: '/'` | now `process.env.VITE_BASE_URL \|\| '/'` | -| `.env.example` listed 6 of 21 vars | all 22 documented; `VITE_GROQ_API_KEY` dropped | +| `vite.config.ts` hardcoded `base: '/'` | now `process.env.VITE_BASE_URL \|\| '/'`, wired in CI | +| `.env.example` listed 6 of 21 vars | all documented; missing server vars added | | 7 unused npm dependencies | removed (103 packages) | | 5 stale root `.sql` duplicates | deleted; `sql/` is the only source | | ~2.3 MB of unreferenced binaries | deleted | | `dist/` not gitignored | added to `.gitignore` | | `firestore.rules`, `firebase-blueprint.json`, `metadata.json` | deleted (AI Studio / Firestore leftovers) | +| Open push relay, open file host, no hardening | **#1, #2, #3 — this pass** | +| Notification screens had no write path | **#4, #5 — this pass** | +| Dead password-reset route | **#8 — this pass** | +| Pages base path, no CI typecheck/test, env not wired | **#9, #10, #11 — this pass** | +| 1.14 MB entry chunk, eager emoji picker, console in prod | **#12, #13, #14 — this pass** | +| Stale Reels leftovers in a live screen | **#18 — this pass** | diff --git a/docs/TESTING.md b/docs/TESTING.md index bd88c0d..c7e4c59 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -5,7 +5,7 @@ npm test # one-shot run npm run test:watch # watch mode ``` -**Current state: 78 tests across 5 files, all passing, ~9 s.** +**Current state: 85 tests across 6 files, all passing, ~11 s.** | File | Tests | What it covers | |---|---|---| @@ -13,7 +13,8 @@ npm run test:watch # watch mode | `dev/mock/__tests__/auth-rpc.test.ts` | 17 | Mock auth, all 7 RPCs, realtime channels | | `src/__tests__/chatService.test.ts` | 15 | **Real** `ChatService` against the mock | | `src/__tests__/utils.test.ts` | 20 | `dateUtils`, `lastSeenFormatter`, `scheduleUtils` | -| `src/__tests__/app.smoke.test.tsx` | 3 | **Real** `` — login form → chat list | +| `src/__tests__/notificationService.test.ts` | 6 | **Real** notification write path — column contract, de-duplication | +| `src/__tests__/app.smoke.test.tsx` | 4 | **Real** `` — login form → chat list, `/forgot-password` reset mode | --- @@ -56,6 +57,11 @@ explicitly: correctly — both directions are tested, because a filter that matches everything looks identical to a working filter in a happy-path test +> **Testing the notification writer:** assert on the `content` column, not +> `text` — `sql/01_core_schema.sql` has no `text` column. The mock now mirrors +> the SQL default (`is_read boolean default false`) so an insert that forgets +> the flag fails a test instead of passing locally. + ### 2. App tests (`src/__tests__/`) These import **real shipped code** — no stand-ins. diff --git a/package-lock.json b/package-lock.json index 39e5c02..8153fca 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,13 +19,16 @@ "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^5.0.4", "axios": "^1.14.0", + "cors": "^2.8.6", "dotenv": "^17.2.3", "emoji-picker-react": "^4.19.1", "esbuild": "^0.28.0", "express": "^4.21.2", + "express-rate-limit": "^8.7.1", "firebase": "^12.14.0", "form-data": "^4.0.5", "google-auth-library": "^10.6.2", + "helmet": "^8.3.0", "jszip": "^3.10.1", "livekit-client": "^2.19.2", "livekit-server-sdk": "^2.15.4", @@ -45,6 +48,7 @@ "@testing-library/jest-dom": "^6.6.3", "@testing-library/react": "^16.3.0", "@testing-library/user-event": "^14.6.1", + "@types/cors": "^2.8.19", "jsdom": "^25.0.1", "vitest": "^3.2.4" }, @@ -2015,6 +2019,16 @@ "@types/node": "*" } }, + "node_modules/@types/cors": { + "version": "2.8.19", + "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz", + "integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/deep-eql": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", @@ -2690,6 +2704,23 @@ "version": "1.0.3", "license": "MIT" }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/css.escape": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz", @@ -3085,6 +3116,25 @@ "url": "https://opencollective.com/express" } }, + "node_modules/express-rate-limit": { + "version": "8.7.1", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.1.tgz", + "integrity": "sha512-2FXbqkygil3mZiXzEtM0IjE/UBmBNot0J1GEVrJT4JbrvwOSoEtqtO+wHbiMQELWe1eNvHoYRg2dkjOid+6JkA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "ip-address": "^10.2.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, "node_modules/express/node_modules/debug": { "version": "2.6.9", "license": "MIT", @@ -3463,6 +3513,18 @@ "node": ">= 0.4" } }, + "node_modules/helmet": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/helmet/-/helmet-8.3.0.tgz", + "integrity": "sha512-Qgpiaws3Sm30Av8Eah6sjMCZZwjlBu+E68rhpCWBshY1lb09HtLwj5GviX0OyQIn+ulUS0iX0AxN5n3tLZzz1w==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/EvanHahn" + } + }, "node_modules/html-encoding-sniffer": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", @@ -3576,6 +3638,15 @@ "version": "2.0.4", "license": "ISC" }, + "node_modules/ip-address": { + "version": "10.7.3", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.3.tgz", + "integrity": "sha512-A1kdq/tSb5QjvKvAMgIoEvDBIgL7qaqVP/jkvSwYYRZ9iEzvPpopxp2wQfu3SuZRHtpHNxMn8Fs0bS+gf5Xmwg==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, "node_modules/ipaddr.js": { "version": "1.9.1", "license": "MIT", @@ -4117,6 +4188,15 @@ "dev": true, "license": "MIT" }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/object-inspect": { "version": "1.13.4", "license": "MIT", diff --git a/package.json b/package.json index a9f2087..c6fd626 100644 --- a/package.json +++ b/package.json @@ -33,13 +33,16 @@ "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^5.0.4", "axios": "^1.14.0", + "cors": "^2.8.6", "dotenv": "^17.2.3", "emoji-picker-react": "^4.19.1", "esbuild": "^0.28.0", "express": "^4.21.2", + "express-rate-limit": "^8.7.1", "firebase": "^12.14.0", "form-data": "^4.0.5", "google-auth-library": "^10.6.2", + "helmet": "^8.3.0", "jszip": "^3.10.1", "livekit-client": "^2.19.2", "livekit-server-sdk": "^2.15.4", @@ -59,6 +62,7 @@ "@testing-library/jest-dom": "^6.6.3", "@testing-library/react": "^16.3.0", "@testing-library/user-event": "^14.6.1", + "@types/cors": "^2.8.19", "jsdom": "^25.0.1", "vitest": "^3.2.4" } diff --git a/server.ts b/server.ts index 0d8612b..6c655f8 100644 --- a/server.ts +++ b/server.ts @@ -1,29 +1,293 @@ -import express from "express"; +import express, { type Request, type NextFunction, type Response } from "express"; import path from "path"; import axios from "axios"; +import cors from "cors"; import dotenv from "dotenv"; +import helmet from "helmet"; import multer from "multer"; import FormData from "form-data"; import fs from "fs"; import os from "os"; +import rateLimit from "express-rate-limit"; import { GoogleAuth } from "google-auth-library"; import { GoogleGenAI } from "@google/genai"; import { AccessToken } from "livekit-server-sdk"; -import { createClient } from "@supabase/supabase-js"; +import { createClient, type SupabaseClient, type User } from "@supabase/supabase-js"; dotenv.config(); const app = express(); -app.use(express.json({ limit: '50mb' })); + +// Every deploy target (Vercel, the sandbox preview proxy) terminates TLS in +// front of this process, so `req.ip` must be read from X-Forwarded-For for the +// rate limiter to see the real caller. +app.set("trust proxy", 1); +app.disable("x-powered-by"); + +const MOCK_MODE = process.env.MOCK_SUPABASE === "1" || process.env.MOCK_SUPABASE === "true"; // GitHub OAuth Config const GITHUB_CLIENT_ID = process.env.GITHUB_CLIENT_ID; const GITHUB_CLIENT_SECRET = process.env.GITHUB_CLIENT_SECRET; -// Configure Multer for temporary storage in the OS temp directory -const upload = multer({ +// ───────────────────────────────────────────────────────────────────────────── +// SECURITY LAYER — headers, CORS, origin check, rate limits, body limits +// ───────────────────────────────────────────────────────────────────────────── + +/** + * helmet, with the three defaults that would break this particular app relaxed: + * + * - CSP is left to the deploy target: the Vite dev server injects inline + * scripts/styles and the GitHub callback page is an inline ` diff --git a/package-lock.json b/package-lock.json index 8153fca..e50d981 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,7 +8,6 @@ "name": "grixchat", "version": "1.0.0", "dependencies": { - "@google/genai": "^2.7.0", "@livekit/components-react": "^2.9.21", "@supabase/supabase-js": "^2.105.4", "@tailwindcss/vite": "^4.1.14", @@ -19,22 +18,16 @@ "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^5.0.4", "axios": "^1.14.0", - "cors": "^2.8.6", "dotenv": "^17.2.3", "emoji-picker-react": "^4.19.1", "esbuild": "^0.28.0", "express": "^4.21.2", - "express-rate-limit": "^8.7.1", "firebase": "^12.14.0", - "form-data": "^4.0.5", - "google-auth-library": "^10.6.2", - "helmet": "^8.3.0", + "jose": "^6.2.12", "jszip": "^3.10.1", "livekit-client": "^2.19.2", - "livekit-server-sdk": "^2.15.4", "lucide-react": "^0.546.0", "motion": "^12.23.24", - "multer": "^2.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", "react-error-boundary": "^6.1.1", @@ -48,9 +41,9 @@ "@testing-library/jest-dom": "^6.6.3", "@testing-library/react": "^16.3.0", "@testing-library/user-event": "^14.6.1", - "@types/cors": "^2.8.19", "jsdom": "^25.0.1", - "vitest": "^3.2.4" + "vitest": "^3.2.4", + "wrangler": "^4.149.0" }, "engines": { "node": ">=20.0.0" @@ -325,6 +318,141 @@ "integrity": "sha512-wJ8ReQbHxsAfXhrf9ixl0aYbZorRuOWpBNzm8pL8ftmSxQx/wnJD5Eg861NwJU/czy2VXFIebCeZnZrI9rktIQ==", "license": "(Apache-2.0 AND BSD-3-Clause)" }, + "node_modules/@cloudflare/kv-asset-handler": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.0.tgz", + "integrity": "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==", + "dev": true, + "license": "MIT OR Apache-2.0", + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@cloudflare/unenv-preset": { + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.2.tgz", + "integrity": "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ==", + "dev": true, + "license": "MIT OR Apache-2.0", + "peerDependencies": { + "unenv": "2.0.0-rc.24", + "workerd": ">1.20260305.0 <2.0.0-0" + }, + "peerDependenciesMeta": { + "workerd": { + "optional": true + } + } + }, + "node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20261006.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261006.1.tgz", + "integrity": "sha512-lCX6avJO2It9AyDEYitjmOtJRVp/xmaW0TziyoLAnfxlzozyyRbSFfIIMMCiDx/sTP1++E4VLbV+7BHSD33f0Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20261006.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261006.1.tgz", + "integrity": "sha512-PyFGjOaldtppnLuKsdkoYWXfLVpDjuf8u+uoykX+1Xvxo2EPmCVViq0iDKm+U7c7PRno85ehS3/MPVXyk2HwHw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-64": { + "version": "1.20261006.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261006.1.tgz", + "integrity": "sha512-Ntf9S8eesmVufdjaT2kzWlz6Ng9XGYTc6cHQVRKAg59lFufwsIabGeMT6U4KkrpEeSIxgHq8aPtuLbZXE19tCA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-arm64": { + "version": "1.20261006.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261006.1.tgz", + "integrity": "sha512-JyeDBymVWw5tVRebSsVE8ojDYxd6UlZrAseHU8G+NpIyd5wF61tXlF/axLeCUqu0pOhBFHb8I5QKi0jwrCK41Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20261006.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261006.1.tgz", + "integrity": "sha512-nWP0URNqOBN9fa/gZ7eh/w051DwjOXN8j4lDZDYVXyQPsux6sV3DfyYZT+CjR/rt9nKBSmJT9QE9/bWT18+84w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@cspotcode/source-map-support/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, "node_modules/@csstools/color-helpers": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", @@ -440,10 +568,21 @@ "node": ">=18" } }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@esbuild/aix-ppc64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.0.tgz", - "integrity": "sha512-lhRUCeuOyJQURhTxl4WkpFTjIsbDayJHih5kZC1giwE+MhIzAb7mEsQMqMf18rHLsrb5qI1tafG20mLxEWcWlA==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", "cpu": [ "ppc64" ], @@ -457,9 +596,9 @@ } }, "node_modules/@esbuild/android-arm": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.0.tgz", - "integrity": "sha512-wqh0ByljabXLKHeWXYLqoJ5jKC4XBaw6Hk08OfMrCRd2nP2ZQ5eleDZC41XHyCNgktBGYMbqnrJKq/K/lzPMSQ==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", "cpu": [ "arm" ], @@ -473,9 +612,9 @@ } }, "node_modules/@esbuild/android-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.0.tgz", - "integrity": "sha512-+WzIXQOSaGs33tLEgYPYe/yQHf0WTU0X42Jca3y8NWMbUVhp7rUnw+vAsRC/QiDrdD31IszMrZy+qwPOPjd+rw==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", "cpu": [ "arm64" ], @@ -489,9 +628,9 @@ } }, "node_modules/@esbuild/android-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.0.tgz", - "integrity": "sha512-+VJggoaKhk2VNNqVL7f6S189UzShHC/mR9EE8rDdSkdpN0KflSwWY/gWjDrNxxisg8Fp1ZCD9jLMo4m0OUfeUA==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", "cpu": [ "x64" ], @@ -505,9 +644,9 @@ } }, "node_modules/@esbuild/darwin-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.0.tgz", - "integrity": "sha512-0T+A9WZm+bZ84nZBtk1ckYsOvyA3x7e2Acj1KdVfV4/2tdG4fzUp91YHx+GArWLtwqp77pBXVCPn2We7Letr0Q==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", "cpu": [ "arm64" ], @@ -521,9 +660,9 @@ } }, "node_modules/@esbuild/darwin-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.0.tgz", - "integrity": "sha512-fyzLm/DLDl/84OCfp2f/XQ4flmORsjU7VKt8HLjvIXChJoFFOIL6pLJPH4Yhd1n1gGFF9mPwtlN5Wf82DZs+LQ==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", "cpu": [ "x64" ], @@ -537,9 +676,9 @@ } }, "node_modules/@esbuild/freebsd-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.0.tgz", - "integrity": "sha512-l9GeW5UZBT9k9brBYI+0WDffcRxgHQD8ShN2Ur4xWq/NFzUKm3k5lsH4PdaRgb2w7mI9u61nr2gI2mLI27Nh3Q==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", "cpu": [ "arm64" ], @@ -553,9 +692,9 @@ } }, "node_modules/@esbuild/freebsd-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.0.tgz", - "integrity": "sha512-BXoQai/A0wPO6Es3yFJ7APCiKGc1tdAEOgeTNy3SsB491S3aHn4S4r3e976eUnPdU+NbdtmBuLncYir2tMU9Nw==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", "cpu": [ "x64" ], @@ -569,9 +708,9 @@ } }, "node_modules/@esbuild/linux-arm": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.0.tgz", - "integrity": "sha512-CjaaREJagqJp7iTaNQjjidaNbCKYcd4IDkzbwwxtSvjI7NZm79qiHc8HqciMddQ6CKvJT6aBd8lO9kN/ZudLlw==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", "cpu": [ "arm" ], @@ -585,9 +724,9 @@ } }, "node_modules/@esbuild/linux-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.0.tgz", - "integrity": "sha512-RVyzfb3FWsGA55n6WY0MEIEPURL1FcbhFE6BffZEMEekfCzCIMtB5yyDcFnVbTnwk+CLAgTujmV/Lgvih56W+A==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", "cpu": [ "arm64" ], @@ -601,9 +740,9 @@ } }, "node_modules/@esbuild/linux-ia32": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.0.tgz", - "integrity": "sha512-KBnSTt1kxl9x70q+ydterVdl+Cn0H18ngRMRCEQfrbqdUuntQQ0LoMZv47uB97NljZFzY6HcfqEZ2SAyIUTQBQ==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", "cpu": [ "ia32" ], @@ -617,9 +756,9 @@ } }, "node_modules/@esbuild/linux-loong64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.0.tgz", - "integrity": "sha512-zpSlUce1mnxzgBADvxKXX5sl8aYQHo2ezvMNI8I0lbblJtp8V4odlm3Yzlj7gPyt3T8ReksE6bK+pT3WD+aJRg==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", "cpu": [ "loong64" ], @@ -633,9 +772,9 @@ } }, "node_modules/@esbuild/linux-mips64el": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.0.tgz", - "integrity": "sha512-2jIfP6mmjkdmeTlsX/9vmdmhBmKADrWqN7zcdtHIeNSCH1SqIoNI63cYsjQR8J+wGa4Y5izRcSHSm8K3QWmk3w==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", "cpu": [ "mips64el" ], @@ -649,9 +788,9 @@ } }, "node_modules/@esbuild/linux-ppc64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.0.tgz", - "integrity": "sha512-bc0FE9wWeC0WBm49IQMPSPILRocGTQt3j5KPCA8os6VprfuJ7KD+5PzESSrJ6GmPIPJK965ZJHTUlSA6GNYEhg==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", "cpu": [ "ppc64" ], @@ -665,9 +804,9 @@ } }, "node_modules/@esbuild/linux-riscv64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.0.tgz", - "integrity": "sha512-SQPZOwoTTT/HXFXQJG/vBX8sOFagGqvZyXcgLA3NhIqcBv1BJU1d46c0rGcrij2B56Z2rNiSLaZOYW5cUk7yLQ==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", "cpu": [ "riscv64" ], @@ -681,9 +820,9 @@ } }, "node_modules/@esbuild/linux-s390x": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.0.tgz", - "integrity": "sha512-SCfR0HN8CEEjnYnySJTd2cw0k9OHB/YFzt5zgJEwa+wL/T/raGWYMBqwDNAC6dqFKmJYZoQBRfHjgwLHGSrn3Q==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", "cpu": [ "s390x" ], @@ -697,7 +836,9 @@ } }, "node_modules/@esbuild/linux-x64": { - "version": "0.28.0", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", "cpu": [ "x64" ], @@ -711,9 +852,9 @@ } }, "node_modules/@esbuild/netbsd-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.0.tgz", - "integrity": "sha512-CR/RYotgtCKwtftMwJlUU7xCVNg3lMYZ0RzTmAHSfLCXw3NtZtNpswLEj/Kkf6kEL3Gw+BpOekRX0BYCtklhUw==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", "cpu": [ "arm64" ], @@ -727,9 +868,9 @@ } }, "node_modules/@esbuild/netbsd-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.0.tgz", - "integrity": "sha512-nU1yhmYutL+fQ71Kxnhg8uEOdC0pwEW9entHykTgEbna2pw2dkbFSMeqjjyHZoCmt8SBkOSvV+yNmm94aUrrqw==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", "cpu": [ "x64" ], @@ -743,9 +884,9 @@ } }, "node_modules/@esbuild/openbsd-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.0.tgz", - "integrity": "sha512-cXb5vApOsRsxsEl4mcZ1XY3D4DzcoMxR/nnc4IyqYs0rTI8ZKmW6kyyg+11Z8yvgMfAEldKzP7AdP64HnSC/6g==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", "cpu": [ "arm64" ], @@ -759,9 +900,9 @@ } }, "node_modules/@esbuild/openbsd-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.0.tgz", - "integrity": "sha512-8wZM2qqtv9UP3mzy7HiGYNH/zjTA355mpeuA+859TyR+e+Tc08IHYpLJuMsfpDJwoLo1ikIJI8jC3GFjnRClzA==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", "cpu": [ "x64" ], @@ -775,9 +916,9 @@ } }, "node_modules/@esbuild/openharmony-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.0.tgz", - "integrity": "sha512-FLGfyizszcef5C3YtoyQDACyg95+dndv79i2EekILBofh5wpCa1KuBqOWKrEHZg3zrL3t5ouE5jgr94vA+Wb2w==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", "cpu": [ "arm64" ], @@ -791,9 +932,9 @@ } }, "node_modules/@esbuild/sunos-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.0.tgz", - "integrity": "sha512-1ZgjUoEdHZZl/YlV76TSCz9Hqj9h9YmMGAgAPYd+q4SicWNX3G5GCyx9uhQWSLcbvPW8Ni7lj4gDa1T40akdlw==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", "cpu": [ "x64" ], @@ -807,9 +948,9 @@ } }, "node_modules/@esbuild/win32-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.0.tgz", - "integrity": "sha512-Q9StnDmQ/enxnpxCCLSg0oo4+34B9TdXpuyPeTedN/6+iXBJ4J+zwfQI28u/Jl40nOYAxGoNi7mFP40RUtkmUA==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", "cpu": [ "arm64" ], @@ -823,9 +964,9 @@ } }, "node_modules/@esbuild/win32-ia32": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.0.tgz", - "integrity": "sha512-zF3ag/gfiCe6U2iczcRzSYJKH1DCI+ByzSENHlM2FcDbEeo5Zd2C86Aq0tKUYAJJ1obRP84ymxIAksZUcdztHA==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", "cpu": [ "ia32" ], @@ -839,9 +980,9 @@ } }, "node_modules/@esbuild/win32-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.0.tgz", - "integrity": "sha512-pEl1bO9mfAmIC+tW5btTmrKaujg3zGtUmWNdCw/xs70FBjwAL3o9OEKNHvNmnyylD6ubxUERiEhdsL0xBQ9efw==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", "cpu": [ "x64" ], @@ -1490,59 +1631,562 @@ "integrity": "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==", "license": "MIT" }, - "node_modules/@google/genai": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/@google/genai/-/genai-2.7.0.tgz", - "integrity": "sha512-tv0DRtcndt2oEhBYy+5mA0TaXH98+L1Gt0AP9unBfH7DP20KhB7+O3QqAN1Lz+laMARGTHS7BFQSNpLbl4gm1g==", - "hasInstallScript": true, + "node_modules/@grpc/grpc-js": { + "version": "1.9.16", + "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.9.16.tgz", + "integrity": "sha512-wE4Ut/olIzfKqp631XrG+wbF0v1vWFN4YL9FyXC2LJiG33DsV7PLzURjrCvY/6je2ntdRkeLpPDluzSRGaVltQ==", "license": "Apache-2.0", "dependencies": { - "google-auth-library": "^10.3.0", - "p-retry": "^4.6.2", - "protobufjs": "^7.5.4", - "ws": "^8.18.0" + "@grpc/proto-loader": "^0.7.8", + "@types/node": ">=12.12.47" }, "engines": { - "node": ">=20.0.0" + "node": "^8.13.0 || >=10.10.0" + } + }, + "node_modules/@grpc/proto-loader": { + "version": "0.7.15", + "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.7.15.tgz", + "integrity": "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ==", + "license": "Apache-2.0", + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.2.5", + "yargs": "^17.7.2" + }, + "bin": { + "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" }, - "peerDependencies": { - "@modelcontextprotocol/sdk": "^1.25.2" + "engines": { + "node": ">=20.9.0" }, - "peerDependenciesMeta": { - "@modelcontextprotocol/sdk": { - "optional": true - } + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@grpc/grpc-js": { - "version": "1.9.16", - "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.9.16.tgz", - "integrity": "sha512-wE4Ut/olIzfKqp631XrG+wbF0v1vWFN4YL9FyXC2LJiG33DsV7PLzURjrCvY/6je2ntdRkeLpPDluzSRGaVltQ==", + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", + "cpu": [ + "wasm32" + ], + "dev": true, "license": "Apache-2.0", + "optional": true, "dependencies": { - "@grpc/proto-loader": "^0.7.8", - "@types/node": ">=12.12.47" + "@img/sharp-wasm32": "0.35.5" }, "engines": { - "node": "^8.13.0 || >=10.10.0" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, - "node_modules/@grpc/proto-loader": { - "version": "0.7.15", - "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.7.15.tgz", - "integrity": "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ==", - "license": "Apache-2.0", - "dependencies": { - "lodash.camelcase": "^4.3.0", - "long": "^5.0.0", - "protobufjs": "^7.2.5", - "yargs": "^17.7.2" + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" }, - "bin": { - "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], "engines": { - "node": ">=6" + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, "node_modules/@jridgewell/gen-mapping": { @@ -1654,6 +2298,35 @@ "@bufbuild/protobuf": "^1.10.0" } }, + "node_modules/@poppinss/colors": { + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz", + "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==", + "dev": true, + "license": "MIT", + "dependencies": { + "kleur": "^4.1.5" + } + }, + "node_modules/@poppinss/dumper": { + "version": "0.6.5", + "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz", + "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@sindresorhus/is": "^7.0.2", + "supports-color": "^10.0.0" + } + }, + "node_modules/@poppinss/exception": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz", + "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==", + "dev": true, + "license": "MIT" + }, "node_modules/@protobufjs/aspromise": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", @@ -1732,6 +2405,26 @@ "linux" ] }, + "node_modules/@sindresorhus/is": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", + "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/@speed-highlight/core": { + "version": "1.2.24", + "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.24.tgz", + "integrity": "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==", + "dev": true, + "license": "CC0-1.0" + }, "node_modules/@supabase/auth-js": { "version": "2.106.0", "license": "MIT", @@ -2019,16 +2712,6 @@ "@types/node": "*" } }, - "node_modules/@types/cors": { - "version": "2.8.19", - "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz", - "integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, "node_modules/@types/deep-eql": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", @@ -2111,12 +2794,6 @@ "@types/react": "^19.2.0" } }, - "node_modules/@types/retry": { - "version": "0.12.0", - "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz", - "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==", - "license": "MIT" - }, "node_modules/@types/send": { "version": "1.2.1", "license": "MIT", @@ -2319,10 +2996,6 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/append-field": { - "version": "1.0.0", - "license": "MIT" - }, "node_modules/aria-query": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", @@ -2361,24 +3034,6 @@ "proxy-from-env": "^2.1.0" } }, - "node_modules/base64-js": { - "version": "1.5.1", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, "node_modules/baseline-browser-mapping": { "version": "2.10.31", "license": "Apache-2.0", @@ -2389,12 +3044,12 @@ "node": ">=6.0.0" } }, - "node_modules/bignumber.js": { - "version": "9.3.1", - "license": "MIT", - "engines": { - "node": "*" - } + "node_modules/blake3-wasm": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz", + "integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==", + "dev": true, + "license": "MIT" }, "node_modules/body-parser": { "version": "1.20.5", @@ -2460,23 +3115,6 @@ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" } }, - "node_modules/buffer-equal-constant-time": { - "version": "1.0.1", - "license": "BSD-3-Clause" - }, - "node_modules/buffer-from": { - "version": "1.1.2", - "license": "MIT" - }, - "node_modules/busboy": { - "version": "1.6.0", - "dependencies": { - "streamsearch": "^1.1.0" - }, - "engines": { - "node": ">=10.16.0" - } - }, "node_modules/bytes": { "version": "3.1.2", "license": "MIT", @@ -2519,36 +3157,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/camelcase": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-8.0.0.tgz", - "integrity": "sha512-8WB3Jcas3swSvjIeA2yvCJ+Miyz5l1ZmB6HFb9R1317dt9LCQoswg/BGrmAmkWVEszSrrg4RwmO46qIm2OEnSA==", - "license": "MIT", - "engines": { - "node": ">=16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/camelcase-keys": { - "version": "9.1.3", - "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-9.1.3.tgz", - "integrity": "sha512-Rircqi9ch8AnZscQcsA1C47NFdaO3wukpmIRzYcDOrmvgt78hM/sj5pZhZNec2NM12uk5vTwRHZ4anGcrC4ZTg==", - "license": "MIT", - "dependencies": { - "camelcase": "^8.0.0", - "map-obj": "5.0.0", - "quick-lru": "^6.1.1", - "type-fest": "^4.3.2" - }, - "engines": { - "node": ">=16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/caniuse-lite": { "version": "1.0.30001793", "funding": [ @@ -2643,31 +3251,6 @@ "node": ">= 0.8" } }, - "node_modules/concat-stream": { - "version": "2.0.0", - "engines": [ - "node >= 6.0" - ], - "license": "MIT", - "dependencies": { - "buffer-from": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.0.2", - "typedarray": "^0.0.6" - } - }, - "node_modules/concat-stream/node_modules/readable-stream": { - "version": "3.6.2", - "license": "MIT", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" - } - }, "node_modules/content-disposition": { "version": "0.5.4", "license": "MIT", @@ -2704,23 +3287,6 @@ "version": "1.0.3", "license": "MIT" }, - "node_modules/cors": { - "version": "2.8.6", - "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", - "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", - "license": "MIT", - "dependencies": { - "object-assign": "^4", - "vary": "^1" - }, - "engines": { - "node": ">= 0.10" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/css.escape": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz", @@ -2753,13 +3319,6 @@ "version": "3.2.3", "license": "MIT" }, - "node_modules/data-uri-to-buffer": { - "version": "4.0.1", - "license": "MIT", - "engines": { - "node": ">= 12" - } - }, "node_modules/data-urls": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", @@ -2875,13 +3434,6 @@ "node": ">= 0.4" } }, - "node_modules/ecdsa-sig-formatter": { - "version": "1.0.11", - "license": "Apache-2.0", - "dependencies": { - "safe-buffer": "^5.0.1" - } - }, "node_modules/ee-first": { "version": "1.1.1", "license": "MIT" @@ -2940,6 +3492,16 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/error-stack-parser-es": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz", + "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, "node_modules/es-define-property": { "version": "1.0.1", "license": "MIT", @@ -2985,9 +3547,9 @@ } }, "node_modules/esbuild": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.0.tgz", - "integrity": "sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", "hasInstallScript": true, "license": "MIT", "bin": { @@ -2997,32 +3559,32 @@ "node": ">=18" }, "optionalDependencies": { - "@esbuild/aix-ppc64": "0.28.0", - "@esbuild/android-arm": "0.28.0", - "@esbuild/android-arm64": "0.28.0", - "@esbuild/android-x64": "0.28.0", - "@esbuild/darwin-arm64": "0.28.0", - "@esbuild/darwin-x64": "0.28.0", - "@esbuild/freebsd-arm64": "0.28.0", - "@esbuild/freebsd-x64": "0.28.0", - "@esbuild/linux-arm": "0.28.0", - "@esbuild/linux-arm64": "0.28.0", - "@esbuild/linux-ia32": "0.28.0", - "@esbuild/linux-loong64": "0.28.0", - "@esbuild/linux-mips64el": "0.28.0", - "@esbuild/linux-ppc64": "0.28.0", - "@esbuild/linux-riscv64": "0.28.0", - "@esbuild/linux-s390x": "0.28.0", - "@esbuild/linux-x64": "0.28.0", - "@esbuild/netbsd-arm64": "0.28.0", - "@esbuild/netbsd-x64": "0.28.0", - "@esbuild/openbsd-arm64": "0.28.0", - "@esbuild/openbsd-x64": "0.28.0", - "@esbuild/openharmony-arm64": "0.28.0", - "@esbuild/sunos-x64": "0.28.0", - "@esbuild/win32-arm64": "0.28.0", - "@esbuild/win32-ia32": "0.28.0", - "@esbuild/win32-x64": "0.28.0" + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" } }, "node_modules/escalade": { @@ -3116,25 +3678,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/express-rate-limit": { - "version": "8.7.1", - "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.1.tgz", - "integrity": "sha512-2FXbqkygil3mZiXzEtM0IjE/UBmBNot0J1GEVrJT4JbrvwOSoEtqtO+wHbiMQELWe1eNvHoYRg2dkjOid+6JkA==", - "license": "MIT", - "dependencies": { - "debug": "^4.4.3", - "ip-address": "^10.2.0" - }, - "engines": { - "node": ">= 16" - }, - "funding": { - "url": "https://github.com/sponsors/express-rate-limit" - }, - "peerDependencies": { - "express": ">= 4.11" - } - }, "node_modules/express/node_modules/debug": { "version": "2.6.9", "license": "MIT", @@ -3146,10 +3689,6 @@ "version": "2.0.0", "license": "MIT" }, - "node_modules/extend": { - "version": "3.0.2", - "license": "MIT" - }, "node_modules/faye-websocket": { "version": "0.11.4", "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.4.tgz", @@ -3177,27 +3716,6 @@ } } }, - "node_modules/fetch-blob": { - "version": "3.2.0", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/jimmywarting" - }, - { - "type": "paypal", - "url": "https://paypal.me/jimmywarting" - } - ], - "license": "MIT", - "dependencies": { - "node-domexception": "^1.0.0", - "web-streams-polyfill": "^3.0.3" - }, - "engines": { - "node": "^12.20 || >= 14.13" - } - }, "node_modules/finalhandler": { "version": "1.3.2", "license": "MIT", @@ -3297,16 +3815,6 @@ "node": ">= 6" } }, - "node_modules/formdata-polyfill": { - "version": "4.0.10", - "license": "MIT", - "dependencies": { - "fetch-blob": "^3.1.2" - }, - "engines": { - "node": ">=12.20.0" - } - }, "node_modules/forwarded": { "version": "0.2.0", "license": "MIT", @@ -3346,53 +3854,25 @@ "node": ">= 0.6" } }, - "node_modules/function-bind": { - "version": "1.1.2", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/gaxios": { - "version": "7.1.4", - "license": "Apache-2.0", - "dependencies": { - "extend": "^3.0.2", - "https-proxy-agent": "^7.0.1", - "node-fetch": "^3.3.2" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/gaxios/node_modules/agent-base": { - "version": "7.1.4", - "license": "MIT", - "engines": { - "node": ">= 14" - } - }, - "node_modules/gaxios/node_modules/https-proxy-agent": { - "version": "7.0.6", + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, "license": "MIT", - "dependencies": { - "agent-base": "^7.1.2", - "debug": "4" - }, + "optional": true, + "os": [ + "darwin" + ], "engines": { - "node": ">= 14" + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, - "node_modules/gcp-metadata": { - "version": "8.1.2", - "license": "Apache-2.0", - "dependencies": { - "gaxios": "^7.0.0", - "google-logging-utils": "^1.0.0", - "json-bigint": "^1.0.0" - }, - "engines": { - "node": ">=18" + "node_modules/function-bind": { + "version": "1.1.2", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, "node_modules/gensync": { @@ -3444,28 +3924,6 @@ "node": ">= 0.4" } }, - "node_modules/google-auth-library": { - "version": "10.6.2", - "license": "Apache-2.0", - "dependencies": { - "base64-js": "^1.3.0", - "ecdsa-sig-formatter": "^1.0.11", - "gaxios": "^7.1.4", - "gcp-metadata": "8.1.2", - "google-logging-utils": "1.1.3", - "jws": "^4.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/google-logging-utils": { - "version": "1.1.3", - "license": "Apache-2.0", - "engines": { - "node": ">=14" - } - }, "node_modules/gopd": { "version": "1.2.0", "license": "MIT", @@ -3513,18 +3971,6 @@ "node": ">= 0.4" } }, - "node_modules/helmet": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/helmet/-/helmet-8.3.0.tgz", - "integrity": "sha512-Qgpiaws3Sm30Av8Eah6sjMCZZwjlBu+E68rhpCWBshY1lb09HtLwj5GviX0OyQIn+ulUS0iX0AxN5n3tLZzz1w==", - "license": "MIT", - "engines": { - "node": ">=18.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/EvanHahn" - } - }, "node_modules/html-encoding-sniffer": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", @@ -3638,15 +4084,6 @@ "version": "2.0.4", "license": "ISC" }, - "node_modules/ip-address": { - "version": "10.7.3", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.3.tgz", - "integrity": "sha512-A1kdq/tSb5QjvKvAMgIoEvDBIgL7qaqVP/jkvSwYYRZ9iEzvPpopxp2wQfu3SuZRHtpHNxMn8Fs0bS+gf5Xmwg==", - "license": "MIT", - "engines": { - "node": ">= 12" - } - }, "node_modules/ipaddr.js": { "version": "1.9.1", "license": "MIT", @@ -3682,9 +4119,9 @@ } }, "node_modules/jose": { - "version": "6.2.3", - "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.3.tgz", - "integrity": "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==", + "version": "6.2.12", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz", + "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/panva" @@ -3769,13 +4206,6 @@ "node": ">=6" } }, - "node_modules/json-bigint": { - "version": "1.0.0", - "license": "MIT", - "dependencies": { - "bignumber.js": "^9.0.0" - } - }, "node_modules/json5": { "version": "2.2.3", "license": "MIT", @@ -3796,21 +4226,14 @@ "setimmediate": "^1.0.5" } }, - "node_modules/jwa": { - "version": "2.0.1", - "license": "MIT", - "dependencies": { - "buffer-equal-constant-time": "^1.0.1", - "ecdsa-sig-formatter": "1.0.11", - "safe-buffer": "^5.0.1" - } - }, - "node_modules/jws": { - "version": "4.0.1", + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true, "license": "MIT", - "dependencies": { - "jwa": "^2.0.1", - "safe-buffer": "^5.0.1" + "engines": { + "node": ">=6" } }, "node_modules/lie": { @@ -3885,39 +4308,6 @@ "@types/dom-mediacapture-record": "^1" } }, - "node_modules/livekit-server-sdk": { - "version": "2.15.4", - "resolved": "https://registry.npmjs.org/livekit-server-sdk/-/livekit-server-sdk-2.15.4.tgz", - "integrity": "sha512-L/Ynu5zH1Qjfifmk3LnymL2JpvtisMFCM2wf7iM6H42WZRx6yvRECXa0hiK9/zi7br8d1x/a7fQIw1yJ/bneOA==", - "license": "Apache-2.0", - "dependencies": { - "@bufbuild/protobuf": "^1.10.1", - "@livekit/protocol": "^1.46.3", - "camelcase-keys": "^9.0.0", - "jose": "^5.1.2" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/livekit-server-sdk/node_modules/@livekit/protocol": { - "version": "1.47.0", - "resolved": "https://registry.npmjs.org/@livekit/protocol/-/protocol-1.47.0.tgz", - "integrity": "sha512-oJW1OpVAQ+/QZlSnvwwAtkP0fJ6OerlL68k7DFxXScMqaKnkMncwffPOLHjLmem7xNpPUiD0tJ2KSDdsIrNcpQ==", - "license": "Apache-2.0", - "dependencies": { - "@bufbuild/protobuf": "^1.10.0" - } - }, - "node_modules/livekit-server-sdk/node_modules/jose": { - "version": "5.10.0", - "resolved": "https://registry.npmjs.org/jose/-/jose-5.10.0.tgz", - "integrity": "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/panva" - } - }, "node_modules/lodash.camelcase": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", @@ -3988,18 +4378,6 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, - "node_modules/map-obj": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-5.0.0.tgz", - "integrity": "sha512-2L3MIgJynYrZ3TYMriLDLWocz15okFakV6J12HXvMXDHui2x/zgChzg1u9mFFGbbGWE+GsLpQByt4POb9Or+uA==", - "license": "MIT", - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/math-intrinsics": { "version": "1.1.0", "license": "MIT", @@ -4065,6 +4443,24 @@ "node": ">=4" } }, + "node_modules/miniflare": { + "version": "5.20261006.1-alpha", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261006.1-alpha.tgz", + "integrity": "sha512-6ylv8tamkrspDI2R/cAYfv+YWmfGNdXe76Pi9TauEUWsFVXn3LNF9Yk8oduzf1a+TYsSRYTqlOE7+nGGRsMHdw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "sharp": "0.35.5", + "undici": "7.29.1", + "workerd": "1.20261006.1", + "ws": "8.21.0", + "youch": "4.1.0-beta.10" + }, + "engines": { + "node": ">=22.0.0" + } + }, "node_modules/motion": { "version": "12.39.0", "license": "MIT", @@ -4104,23 +4500,6 @@ "version": "2.1.3", "license": "MIT" }, - "node_modules/multer": { - "version": "2.1.1", - "license": "MIT", - "dependencies": { - "append-field": "^1.0.0", - "busboy": "^1.6.0", - "concat-stream": "^2.0.0", - "type-is": "^1.6.18" - }, - "engines": { - "node": ">= 10.16.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/nanoid": { "version": "3.3.12", "funding": [ @@ -4144,39 +4523,6 @@ "node": ">= 0.6" } }, - "node_modules/node-domexception": { - "version": "1.0.0", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/jimmywarting" - }, - { - "type": "github", - "url": "https://paypal.me/jimmywarting" - } - ], - "license": "MIT", - "engines": { - "node": ">=10.5.0" - } - }, - "node_modules/node-fetch": { - "version": "3.3.2", - "license": "MIT", - "dependencies": { - "data-uri-to-buffer": "^4.0.0", - "fetch-blob": "^3.1.4", - "formdata-polyfill": "^4.0.10" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/node-fetch" - } - }, "node_modules/node-releases": { "version": "2.0.44", "license": "MIT" @@ -4188,15 +4534,6 @@ "dev": true, "license": "MIT" }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/object-inspect": { "version": "1.13.4", "license": "MIT", @@ -4217,19 +4554,6 @@ "node": ">= 0.8" } }, - "node_modules/p-retry": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz", - "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==", - "license": "MIT", - "dependencies": { - "@types/retry": "0.12.0", - "retry": "^0.13.1" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/pako": { "version": "1.0.11", "license": "(MIT AND Zlib)" @@ -4422,18 +4746,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/quick-lru": { - "version": "6.1.2", - "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-6.1.2.tgz", - "integrity": "sha512-AAFUA5O1d83pIHEhJwWCq/RQcRukCkn/NSm2QsTEMle5f2hP0ChI2+3Xb051PZCkLryI/Ir1MVKviT2FIloaTQ==", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/range-parser": { "version": "1.2.1", "license": "MIT", @@ -4570,15 +4882,6 @@ "node": ">=0.10.0" } }, - "node_modules/retry": { - "version": "0.13.1", - "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", - "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, "node_modules/rollup": { "version": "4.60.4", "license": "MIT", @@ -4756,6 +5059,69 @@ "version": "1.2.0", "license": "ISC" }, + "node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/sharp/node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/side-channel": { "version": "1.1.0", "license": "MIT", @@ -4855,12 +5221,6 @@ "dev": true, "license": "MIT" }, - "node_modules/streamsearch": { - "version": "1.1.0", - "engines": { - "node": ">=10.0.0" - } - }, "node_modules/string_decoder": { "version": "1.1.1", "license": "MIT", @@ -4931,6 +5291,19 @@ "dev": true, "license": "MIT" }, + "node_modules/supports-color": { + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", + "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, "node_modules/symbol-tree": { "version": "3.2.4", "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", @@ -5084,18 +5457,6 @@ "fsevents": "~2.3.3" } }, - "node_modules/type-fest": { - "version": "4.41.0", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", - "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", - "license": "(MIT OR CC0-1.0)", - "engines": { - "node": ">=16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/type-is": { "version": "1.6.18", "license": "MIT", @@ -5116,10 +5477,6 @@ "rxjs": "*" } }, - "node_modules/typedarray": { - "version": "0.0.6", - "license": "MIT" - }, "node_modules/typescript": { "version": "5.8.3", "license": "Apache-2.0", @@ -5131,10 +5488,30 @@ "node": ">=14.17" } }, + "node_modules/undici": { + "version": "7.29.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.1.tgz", + "integrity": "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, "node_modules/undici-types": { "version": "6.21.0", "license": "MIT" }, + "node_modules/unenv": { + "version": "2.0.0-rc.24", + "resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.24.tgz", + "integrity": "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "pathe": "^2.0.3" + } + }, "node_modules/unpipe": { "version": "1.0.0", "license": "MIT", @@ -5837,13 +6214,6 @@ "node": ">=18" } }, - "node_modules/web-streams-polyfill": { - "version": "3.3.3", - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, "node_modules/web-vitals": { "version": "4.2.4", "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-4.2.4.tgz", @@ -5964,6 +6334,70 @@ "node": ">=8" } }, + "node_modules/workerd": { + "version": "1.20261006.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261006.1.tgz", + "integrity": "sha512-8MadBuffZ5NdpLwZjUmsqT5QlaKXq4gjgT6wzcKeynZTICNXyePhc+5QVoKiK7+MMhFTLNrRO2KXLlpk8Q6BkA==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20261006.1", + "@cloudflare/workerd-darwin-arm64": "1.20261006.1", + "@cloudflare/workerd-linux-64": "1.20261006.1", + "@cloudflare/workerd-linux-arm64": "1.20261006.1", + "@cloudflare/workerd-windows-64": "1.20261006.1" + } + }, + "node_modules/wrangler": { + "version": "4.149.0", + "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.149.0.tgz", + "integrity": "sha512-OzK7xmB5r5iLKb3cIT3783g13fe6T7xyeKu9LEdUyl+DKAM2KP/jkjnE0OUhyw+mB/XJM9ycjgF3MWm8PR9amg==", + "dev": true, + "license": "MIT OR Apache-2.0", + "dependencies": { + "@cloudflare/kv-asset-handler": "0.5.0", + "@cloudflare/unenv-preset": "2.16.2", + "blake3-wasm": "2.1.5", + "esbuild": "0.28.2", + "miniflare": "5.20261006.1-alpha", + "path-to-regexp": "6.3.0", + "unenv": "2.0.0-rc.24", + "workerd": "1.20261006.1" + }, + "bin": { + "cf-wrangler": "bin/cf-wrangler.js", + "wrangler": "bin/wrangler.js", + "wrangler2": "bin/wrangler.js" + }, + "engines": { + "node": ">=22.0.0" + }, + "optionalDependencies": { + "fsevents": "2.3.3" + }, + "peerDependencies": { + "@cloudflare/workers-types": "^5.20261006.1" + }, + "peerDependenciesMeta": { + "@cloudflare/workers-types": { + "optional": true + } + } + }, + "node_modules/wrangler/node_modules/path-to-regexp": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz", + "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==", + "dev": true, + "license": "MIT" + }, "node_modules/wrap-ansi": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", @@ -5985,6 +6419,7 @@ "version": "8.21.0", "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "dev": true, "license": "MIT", "engines": { "node": ">=10.0.0" @@ -6058,6 +6493,45 @@ "engines": { "node": ">=12" } + }, + "node_modules/youch": { + "version": "4.1.0-beta.10", + "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz", + "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@poppinss/dumper": "^0.6.4", + "@speed-highlight/core": "^1.2.7", + "cookie": "^1.0.2", + "youch-core": "^0.3.3" + } + }, + "node_modules/youch-core": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz", + "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/exception": "^1.2.2", + "error-stack-parser-es": "^1.0.5" + } + }, + "node_modules/youch/node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } } } } diff --git a/package.json b/package.json index c6fd626..bacba7c 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,9 @@ "scripts": { "dev": "tsx server.ts", "dev:mock": "MOCK_SUPABASE=1 tsx server.ts", - "build": "vite build && esbuild server.ts --bundle --platform=node --format=cjs --packages=external --sourcemap --outfile=dist/server.cjs", + "build": "vite build", + "build:all": "npm run build && npm run build:server", + "build:server": "esbuild server.ts --bundle --platform=node --format=cjs --packages=external --sourcemap --outfile=dist/server.cjs", "build:mock": "MOCK_SUPABASE=1 vite build", "start": "node dist/server.cjs", "preview": "vite preview", @@ -18,11 +20,10 @@ "test": "vitest run", "test:watch": "vitest", "test:ui": "vitest --ui", - "clean": "rm -rf dist", - "lint": "tsc --noEmit" + "lint": "tsc --noEmit", + "clean": "rm -rf dist" }, "dependencies": { - "@google/genai": "^2.7.0", "@livekit/components-react": "^2.9.21", "@supabase/supabase-js": "^2.105.4", "@tailwindcss/vite": "^4.1.14", @@ -33,22 +34,16 @@ "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^5.0.4", "axios": "^1.14.0", - "cors": "^2.8.6", "dotenv": "^17.2.3", "emoji-picker-react": "^4.19.1", "esbuild": "^0.28.0", "express": "^4.21.2", - "express-rate-limit": "^8.7.1", "firebase": "^12.14.0", - "form-data": "^4.0.5", - "google-auth-library": "^10.6.2", - "helmet": "^8.3.0", + "jose": "^6.2.12", "jszip": "^3.10.1", "livekit-client": "^2.19.2", - "livekit-server-sdk": "^2.15.4", "lucide-react": "^0.546.0", "motion": "^12.23.24", - "multer": "^2.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", "react-error-boundary": "^6.1.1", @@ -62,8 +57,8 @@ "@testing-library/jest-dom": "^6.6.3", "@testing-library/react": "^16.3.0", "@testing-library/user-event": "^14.6.1", - "@types/cors": "^2.8.19", "jsdom": "^25.0.1", - "vitest": "^3.2.4" + "vitest": "^3.2.4", + "wrangler": "^4.149.0" } } diff --git a/public/.well-known/assetlinks.json b/public/.well-known/assetlinks.json new file mode 100644 index 0000000..418ba97 --- /dev/null +++ b/public/.well-known/assetlinks.json @@ -0,0 +1,12 @@ +[ + { + "relation": ["delegate_permission/common.handle_all_urls"], + "target": { + "namespace": "android_app", + "package_name": "com.gothwad.grixchat", + "sha256_cert_fingerprints": [ + "F1:A1:DA:3C:A9:74:9C:13:B9:92:EF:CD:AA:E1:92:BB:D4:57:3E:04:9E:FC:D7:E5:A9:DF:11:80:FF:E3:A3:AA" + ] + } + } +] diff --git a/public/_headers b/public/_headers new file mode 100644 index 0000000..e14b06d --- /dev/null +++ b/public/_headers @@ -0,0 +1,36 @@ +# Cloudflare Pages response headers for static assets. +# +# The API sets its own headers in `server/api.ts` (SECURITY_HEADERS) — Pages +# `_headers` only applies to files served straight from `dist/`, not to Function +# responses. Keep the two lists in step. +# +# No X-Frame-Options / CSP on purpose: the Android WebView (TWA) wrapper embeds +# the app, and the Vite build output relies on inline styles. + +/* + X-Content-Type-Options: nosniff + Referrer-Policy: no-referrer + X-Permitted-Cross-Domain-Policies: none + Cross-Origin-Resource-Policy: cross-origin + Permissions-Policy: camera=(self), microphone=(self), geolocation=(self) + +# Hashed asset filenames — safe to cache forever. +/assets/* + Cache-Control: public, max-age=31536000, immutable + +# The shell and the service workers must always be revalidated, otherwise a +# deploy can leave clients pinned to a stale bundle. +/ + Cache-Control: public, max-age=0, must-revalidate + +/index.html + Cache-Control: public, max-age=0, must-revalidate + +/sw.js + Cache-Control: public, max-age=0, must-revalidate + +/firebase-messaging-sw.js + Cache-Control: public, max-age=0, must-revalidate + +/manifest.json + Cache-Control: public, max-age=3600 diff --git a/public/_routes.json b/public/_routes.json new file mode 100644 index 0000000..9a86cc0 --- /dev/null +++ b/public/_routes.json @@ -0,0 +1,5 @@ +{ + "version": 1, + "include": ["/api/*", "/auth/*"], + "exclude": [] +} diff --git a/public/robots.txt b/public/robots.txt index d5f6a21..c888f16 100644 --- a/public/robots.txt +++ b/public/robots.txt @@ -4,5 +4,6 @@ Disallow: /settings Disallow: /verify-email Disallow: /setup-lock Disallow: /verify-lock +Disallow: /api/ -Sitemap: https://grixchat.gothwad.workers.dev/sitemap.xml +Sitemap: https://grixchat.gothwadtech.com/sitemap.xml diff --git a/public/sitemap.xml b/public/sitemap.xml index fab931a..da92520 100644 --- a/public/sitemap.xml +++ b/public/sitemap.xml @@ -1,39 +1,30 @@ + - https://grixchat.gothwad.workers.dev/ - 2024-03-24 + https://grixchat.gothwadtech.com/ 1.0 daily - https://grixchat.gothwad.workers.dev/chats - 2024-03-24 - 0.9 - always - - - https://grixchat.gothwad.workers.dev/reels - 2024-03-24 - 0.8 - always + https://grixchat.gothwadtech.com/login + 0.5 + monthly - https://grixchat.gothwad.workers.dev/hub - 2024-03-24 - 0.7 - weekly + https://grixchat.gothwadtech.com/signup + 0.5 + monthly - https://grixchat.gothwad.workers.dev/tube - 2024-03-24 - 0.8 - daily + https://grixchat.gothwadtech.com/privacy-policy + 0.3 + yearly - https://grixchat.gothwad.workers.dev/login - 2024-03-24 - 0.5 - monthly + https://grixchat.gothwadtech.com/terms + 0.3 + yearly diff --git a/server.ts b/server.ts index 6c655f8..439bcd6 100644 --- a/server.ts +++ b/server.ts @@ -1,1256 +1,166 @@ -import express, { type Request, type NextFunction, type Response } from "express"; -import path from "path"; -import axios from "axios"; -import cors from "cors"; -import dotenv from "dotenv"; -import helmet from "helmet"; -import multer from "multer"; -import FormData from "form-data"; -import fs from "fs"; -import os from "os"; -import rateLimit from "express-rate-limit"; -import { GoogleAuth } from "google-auth-library"; -import { GoogleGenAI } from "@google/genai"; -import { AccessToken } from "livekit-server-sdk"; -import { createClient, type SupabaseClient, type User } from "@supabase/supabase-js"; +/** + * Node adapter for the GrixChat API. + * + * All route logic lives in `server/api.ts` and is shared byte-for-byte with the + * Cloudflare Pages Functions in `functions/`. This file only does the plumbing + * a Node host needs: + * + * - `npm run dev` / `dev:mock` → Vite middleware mode + the API + * - `npm run start` → serves `dist/` + the API + * + * Production runs on **Cloudflare Pages** (static `dist/` + `functions/api`), + * so treat this as the development and self-hosting path. + */ +import express, { type Request as ExpressRequest, type Response as ExpressResponse } from 'express'; +import fs from 'fs'; +import path from 'path'; +import dotenv from 'dotenv'; +import { handleApiRequest, SECURITY_HEADERS, type ApiEnv, type RepoFsCapability } from './server/api'; dotenv.config(); const app = express(); - -// Every deploy target (Vercel, the sandbox preview proxy) terminates TLS in -// front of this process, so `req.ip` must be read from X-Forwarded-For for the -// rate limiter to see the real caller. -app.set("trust proxy", 1); -app.disable("x-powered-by"); - -const MOCK_MODE = process.env.MOCK_SUPABASE === "1" || process.env.MOCK_SUPABASE === "true"; - -// GitHub OAuth Config -const GITHUB_CLIENT_ID = process.env.GITHUB_CLIENT_ID; -const GITHUB_CLIENT_SECRET = process.env.GITHUB_CLIENT_SECRET; +app.disable('x-powered-by'); +// Behind Cloudflare/tunnels TLS terminates upstream, so `req.protocol` has to +// read `x-forwarded-proto` to build correct absolute URLs. +app.set('trust proxy', 1); // ───────────────────────────────────────────────────────────────────────────── -// SECURITY LAYER — headers, CORS, origin check, rate limits, body limits +// Environment + the one Node-only capability the API uses // ───────────────────────────────────────────────────────────────────────────── -/** - * helmet, with the three defaults that would break this particular app relaxed: - * - * - CSP is left to the deploy target: the Vite dev server injects inline - * scripts/styles and the GitHub callback page is an inline ` -
-
- -

Authenticating with GitHub...

-

Securely connecting your accounts

-
- - - - `); - } catch (error) { - res.status(500).send("Auth failed"); - } -}); - -// GitHub Push -app.post("/api/github/push", apiLimiter, jsonLarge, async (req, res) => { - const { token, owner, repo, path: filePath, content, message, branch = 'main' } = req.body; - try { - let sha; - try { - const getFileRes = await axios.get(`https://api.github.com/repos/${owner}/${repo}/contents/${filePath}`, { - headers: { Authorization: `token ${token}` } - }); - sha = getFileRes.data.sha; - } catch (e) {} - - const pushRes = await axios.put(`https://api.github.com/repos/${owner}/${repo}/contents/${filePath}`, { - message, content, sha, branch - }, { - headers: { Authorization: `token ${token}` } - }); - res.json(pushRes.data); - } catch (error: any) { - res.status(error.response?.status || 500).json(error.response?.data || { message: error.message }); - } -}); - -import crypto from "crypto"; - -// Helper to calculate GitHub's blob SHA -function calculateGitHubSha(contentBase64: string): string { - const content = Buffer.from(contentBase64, 'base64'); - const header = `blob ${content.length}\0`; - const store = Buffer.concat([Buffer.from(header), content]); - return crypto.createHash('sha1').update(store).digest('hex'); -} - -// GitHub Batch Push (Atomic commit for multiple files) -app.post("/api/github/push-batch", apiLimiter, jsonLarge, async (req, res) => { - const { token, owner, repo, files, message, branch = 'main', isSequential = false } = req.body; - - try { - const headers = { - Authorization: `token ${token}`, - Accept: 'application/vnd.github.v3+json' - }; - - console.log(`Starting smart batch push for ${files.length} files to ${owner}/${repo} on branch ${branch} [isSequential: ${isSequential}]`); - - // 1. Get the latest commit SHA of the branch - const branchRes = await axios.get(`https://api.github.com/repos/${owner}/${repo}/branches/${branch}`, { headers }); - const parentSha = branchRes.data.commit.sha; - const baseTreeSha = branchRes.data.commit.commit.tree.sha; - - // 2. Fetch the current recursive tree to compare SHAs - console.log(`Fetching current tree for comparison...`); - const existingTreeRes = await axios.get(`https://api.github.com/repos/${owner}/${repo}/git/trees/${baseTreeSha}?recursive=1`, { headers }); - const existingFiles = new Map(); // path -> sha - if (existingTreeRes.data.tree) { - existingTreeRes.data.tree.forEach((node: any) => { - if (node.type === 'blob') { - existingFiles.set(node.path, node.sha); - } - }); - } - - // 3. Filter files that actually changed - const modifiedFiles = files.filter((file: any) => { - const localSha = calculateGitHubSha(file.content); - const remoteSha = existingFiles.get(file.path); - return localSha !== remoteSha; - }); - - console.log(`Smart Sync: ${modifiedFiles.length} of ${files.length} files changed.`); - - if (modifiedFiles.length === 0) { - return res.json({ - message: "No changes detected. Repository is already up to date.", - noChanges: true - }); - } - - // If sequential mode is enabled, upload files one-by-one to support safe incrementing - if (isSequential) { - console.log(`Sequential Sync Mode: Uploading ${modifiedFiles.length} files individually...`); - let uploadedCount = 0; - - try { - for (let i = 0; i < modifiedFiles.length; i++) { - const file = modifiedFiles[i]; - const sha = existingFiles.get(file.path); - - console.log(`Uploading file ${i + 1}/${modifiedFiles.length}: ${file.path} (SHA: ${sha || 'new'})`); - - await axios.put(`https://api.github.com/repos/${owner}/${repo}/contents/${file.path}`, { - message: `${message} - update ${file.path}`, - content: file.content, - sha: sha || undefined, - branch - }, { headers }); - - uploadedCount++; - - // Small pause to prevent hitting GitHub's abuse detection rates on continuous fast writes - await new Promise(resolve => setTimeout(resolve, 150)); - } - - return res.json({ - message: `Successfully uploaded all ${uploadedCount} files sequentially.`, - sequential: true, - uploadedCount, - html_url: `https://github.com/${owner}/${repo}/commits/${branch}` - }); - - } catch (err: any) { - const errorDetail = err.response?.data?.message || err.message; - console.error(`Sequential sync error after uploading ${uploadedCount} files:`, err.response?.data || err.message); - - if (uploadedCount > 0) { - return res.json({ - message: `Uploaded ${uploadedCount} files successfully, but stopped because of GitHub limit.`, - sequential: true, - uploadedCount, - error: errorDetail, - html_url: `https://github.com/${owner}/${repo}/commits/${branch}` - }); - } else { - throw new Error(`Failed to upload first file ${modifiedFiles[0].path}: ${errorDetail}`); - } - } - } - - // 4. Create blobs for each modified file with concurrency control - const treeItems = []; - const BATCH_SIZE = 5; - const DELAY_BETWEEN_BATCHES = 400; // ms - - for (let i = 0; i < modifiedFiles.length; i += BATCH_SIZE) { - const batch = modifiedFiles.slice(i, i + BATCH_SIZE); - console.log(`Processing batch ${Math.floor(i / BATCH_SIZE) + 1}/${Math.ceil(modifiedFiles.length / BATCH_SIZE)} (${batch.length} files)`); - - const results = await Promise.all(batch.map(async (file: any) => { - try { - const blobRes = await axios.post(`https://api.github.com/repos/${owner}/${repo}/git/blobs`, { - content: file.content, - encoding: 'base64' - }, { headers }); - - return { - path: file.path, - mode: '100644', - type: 'blob', - sha: blobRes.data.sha - }; - } catch (err: any) { - console.error(`Failed to create blob for ${file.path}:`, err.response?.data || err.message); - throw new Error(`Failed to upload ${file.path}: ${err.response?.data?.message || err.message}`); - } - })); - - treeItems.push(...results); - - if (i + BATCH_SIZE < modifiedFiles.length) { - await new Promise(resolve => setTimeout(resolve, DELAY_BETWEEN_BATCHES)); - } - } - - console.log(`Successfully created ${treeItems.length} new blobs. Creating updated tree...`); - - // 5. Create a new tree (basing it on the existing baseTreeSha to merge changes) - const treeRes = await axios.post(`https://api.github.com/repos/${owner}/${repo}/git/trees`, { - base_tree: baseTreeSha, - tree: treeItems - }, { headers }); - - // 6. Create a new commit - const commitRes = await axios.post(`https://api.github.com/repos/${owner}/${repo}/git/commits`, { - message, - tree: treeRes.data.sha, - parents: [parentSha] - }, { headers }); - - // 7. Update the branch reference - const refRes = await axios.patch(`https://api.github.com/repos/${owner}/${repo}/git/refs/heads/${branch}`, { - sha: commitRes.data.sha, - force: false - }, { headers }); - - console.log(`Successfully updated reference for branch ${branch}`); - res.json(refRes.data); - } catch (error: any) { - console.error("Smart Batch Push error:", error.response?.data || error.message); - res.status(error.response?.status || 500).json(error.response?.data || { message: error.message }); - } -}); - -// Retrieve list of codebase files for Sync Tool -app.get("/api/github/list-files", (req, res) => { - const listAllFiles = (dir: string, fileList: string[] = []): string[] => { - const files = fs.readdirSync(dir); - files.forEach((file) => { - const filePath = path.join(dir, file); - if (fs.statSync(filePath).isDirectory()) { - const baseName = path.basename(file); - if (!baseName.startsWith('.') && baseName !== 'node_modules' && baseName !== 'dist' && baseName !== '.git' && baseName !== 'tmp') { - listAllFiles(filePath, fileList); - } - } else { - const relativePath = path.relative(process.cwd(), filePath); - fileList.push(relativePath); - } - }); - return fileList; - }; - try { - const allFiles = listAllFiles(process.cwd()); - res.json({ files: allFiles }); - } catch (error: any) { - res.status(500).json({ error: error.message }); - } -}); - -// Retrieve localized file content for Sync Tool -app.get("/api/github/get-file-content", (req, res) => { - const filePath = req.query.path as string; - if (!filePath) return res.status(400).json({ error: "Path is required" }); - - // Normalize path to prevent directory traversal - const resolvedPath = path.resolve(process.cwd(), filePath); - if (!resolvedPath.startsWith(process.cwd())) { - return res.status(403).json({ error: "Access denied" }); - } - try { - if (!fs.existsSync(resolvedPath)) { - return res.status(404).json({ error: "File not found" }); - } - const content = fs.readFileSync(resolvedPath, 'base64'); - res.json({ content }); - } catch (error: any) { - res.status(500).json({ error: error.message }); - } +// Security headers for anything this process serves directly. Production is on +// Cloudflare Pages, where `public/_headers` does the same job for static files. +app.use((_req, res, next) => { + for (const [key, value] of Object.entries(SECURITY_HEADERS)) res.setHeader(key, value); + next(); }); // ───────────────────────────────────────────────────────────────────────────── -// Error handling — registered after every route +// Frontend // ───────────────────────────────────────────────────────────────────────────── -/** Unknown /api/* paths answer with JSON, not the SPA's index.html. */ -app.use("/api", (req, res) => { - res.status(404).json({ error: `Unknown API route: ${req.method} ${req.originalUrl}` }); -}); - -// Vite / Static handling -if (process.env.NODE_ENV !== "production") { - // Dynamic import for development - import("vite").then(({ createServer }) => { - createServer({ - server: { middlewareMode: true }, - appType: "spa", - }).then((vite) => { +if (process.env.NODE_ENV !== 'production') { + import('vite').then(({ createServer }) => { + createServer({ server: { middlewareMode: true }, appType: 'spa' }).then((vite) => { app.use(vite.middlewares); }); }); } else { - const distPath = path.resolve(process.cwd(), "dist"); - app.use(express.static(distPath, { dotfiles: "allow" })); - app.get("*", (req, res) => { - res.sendFile(path.resolve(distPath, "index.html")); + const distPath = path.resolve(process.cwd(), 'dist'); + app.use(express.static(distPath, { dotfiles: 'allow' })); + app.get('*', (_req, res) => { + res.sendFile(path.resolve(distPath, 'index.html')); }); } -// Malformed or oversized JSON bodies (from `express.json`) land here, so they -// return a JSON error instead of Express's HTML stack page. -app.use((err: any, req: Request, res: Response, next: NextFunction) => { - if (res.headersSent) return next(err); - - if (err?.type === "entity.too.large") { - return res.status(413).json({ error: "Request body too large" }); - } - if (err?.type === "entity.parse.failed" || err instanceof SyntaxError) { - return res.status(400).json({ error: "Malformed JSON request body" }); - } - - console.error("Unhandled server error:", err); - return res.status(err?.status || 500).json({ error: err?.message || "Internal server error" }); -}); - -// Start server -const PORT = 3000; -app.listen(PORT, "0.0.0.0", () => { - console.log(`Server running on port ${PORT}`); +const PORT = Number(process.env.PORT) || 3000; +app.listen(PORT, '0.0.0.0', () => { + console.log(`GrixChat dev server on http://localhost:${PORT}`); + console.log(' API routes: /api/* · GitHub OAuth: /auth/github/callback'); + console.log(' Production target: Cloudflare Pages (see docs/DEV_SETUP.md)'); }); export default app; diff --git a/server/api.ts b/server/api.ts new file mode 100644 index 0000000..66d928e --- /dev/null +++ b/server/api.ts @@ -0,0 +1,1416 @@ +/** + * GrixChat API — runtime-neutral core. + * + * Every route lives here exactly once, written against the **Fetch API** so the + * same code runs on both deployment targets: + * + * - Cloudflare Pages Functions (`functions/api/[[path]].ts`) — production, + * served from grixchat.gothwadtech.com. + * - Express (`server.ts`) — `npm run dev` and self-hosting. + * + * Hard rule: nothing in this file may touch Node built-ins (`fs`, `path`, + * `crypto`, `Buffer`, `process`, `multer`, `axios`, …). If a route genuinely + * needs a Node capability, it is declared as an optional capability in + * `ApiEnv` and the adapter that can provide it does — see `REPO_FS`. + * + * The Supabase SDK, `jose` and the platform `fetch` are all available on both + * runtimes (Workers + Node 20), so those are fair game. + */ +import { createClient, type SupabaseClient, type User } from '@supabase/supabase-js'; +import { SignJWT, importPKCS8 } from 'jose'; + +// ───────────────────────────────────────────────────────────────────────────── +// Environment & capabilities +// ───────────────────────────────────────────────────────────────────────────── + +/** Everything the API can read configuration from. Both adapters supply this. */ +export interface ApiEnv { + VITE_SUPABASE_URL?: string; + VITE_SUPABASE_ANON_KEY?: string; + SUPABASE_SERVICE_ROLE_KEY?: string; + GEMINI_API_KEY?: string; + FIREBASE_SERVICE_ACCOUNT?: string; + LIVEKIT_API_KEY?: string; + LIVEKIT_API_SECRET?: string; + GITHUB_CLIENT_ID?: string; + GITHUB_CLIENT_SECRET?: string; + /** Canonical origin, e.g. `https://grixchat.gothwadtech.com`. */ + APP_URL?: string; + /** Extra comma-separated origins allowed to call the API. */ + ALLOWED_ORIGINS?: string; + /** `1` in `npm run dev:mock` — skips JWT verification (never in production). */ + MOCK_SUPABASE?: string; + NODE_ENV?: string; + /** Set to `1` by Cloudflare on every Pages deployment (production + preview). */ + CF_PAGES?: string; + + /** + * Node-only capability: reading the checked-out repository, used by the + * GitHub "Sync Tool" (`/api/github/list-files`, `/api/github/get-file-content`). + * Cloudflare Workers have no filesystem, so those two routes answer `501` + * there instead of pretending to work. + */ + REPO_FS?: RepoFsCapability; + + /** Cloudflare Pages asset binding, if the adapter wants to expose it. */ + ASSETS?: { fetch: (input: Request) => Promise }; +} + +export interface RepoFsCapability { + /** Absolute path of the repository root the API was started from. */ + root: string; + /** Relative paths of every trackable source file. */ + listFiles: () => string[]; + /** Base64 content, or `null` when the path is missing/outside the root. */ + readFileBase64: (relativePath: string) => string | null; +} + +// ───────────────────────────────────────────────────────────────────────────── +// Response helpers +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Security headers for API responses. Mirrors what `public/_headers` applies to + * the static assets, so API and page responses are covered the same way. + * + * There is deliberately no `X-Frame-Options`: the Android WebView (TWA) wrapper + * embeds the app in a frame. + */ +export const SECURITY_HEADERS: Record = { + 'X-Content-Type-Options': 'nosniff', + 'Referrer-Policy': 'no-referrer', + 'X-Permitted-Cross-Domain-Policies': 'none', + 'Cross-Origin-Resource-Policy': 'cross-origin', +}; + +function json(body: unknown, status = 200, extra: Record = {}): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json; charset=utf-8', ...SECURITY_HEADERS, ...extra }, + }); +} + +function html(body: string, status = 200): Response { + return new Response(body, { + status, + headers: { 'Content-Type': 'text/html; charset=utf-8', ...SECURITY_HEADERS }, + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Origin handling (CORS + CSRF guard) +// ───────────────────────────────────────────────────────────────────────────── + +const hostOf = (value: string): string => { + if (!value) return ''; + try { + return new URL(value.includes('://') ? value : `https://${value}`).host.toLowerCase(); + } catch { + return ''; + } +}; + +/** True when the request arrived on a loopback / bind-all address. */ +function isLocalRequestHost(host: string): boolean { + const hostname = host.split(':')[0].replace(/^\[|\]$/g, ''); + return ['localhost', '127.0.0.1', '0.0.0.0', '::1', 'host.docker.internal'].includes(hostname); +} + +/** + * True when `origin` may call the API: same-origin with the request, + * `APP_URL`, anything in `ALLOWED_ORIGINS`, or a local dev origin. + */ +function isAllowedOrigin(request: Request, env: ApiEnv, origin: string): boolean { + const originHost = hostOf(origin); + if (!originHost) return false; + + const requestHosts = [request.headers.get('x-forwarded-host'), request.headers.get('host'), new URL(request.url).host] + .flatMap((h) => (h ? h.split(',') : [])) + .map((h) => h.trim().toLowerCase()) + .filter(Boolean); + + if (requestHosts.includes(originHost)) return true; + + // Behind a tunnel / container preview the process only sees its own bind + // address (`0.0.0.0:3000`) while the browser reports the public hostname, so + // the two can never be compared. Those deployments hold no production data; + // `ALLOWED_ORIGINS` restores strictness where it matters. + if (requestHosts.length > 0 && requestHosts.every(isLocalRequestHost)) return true; + + const allowlist = new Set( + [ + hostOf(env.APP_URL || ''), + ...(env.ALLOWED_ORIGINS || '') + .split(',') + .map((o) => hostOf(o.trim())), + 'localhost:3000', + '127.0.0.1:3000', + 'localhost:5173', + '127.0.0.1:5173', + ].filter(Boolean) + ); + + return allowlist.has(originHost); +} + +function corsHeaders(request: Request, env: ApiEnv): Record { + const origin = request.headers.get('origin'); + if (!origin || !isAllowedOrigin(request, env, origin)) return {}; + return { + 'Access-Control-Allow-Origin': origin, + 'Access-Control-Allow-Credentials': 'true', + 'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Requested-With, X-File-Name', + 'Access-Control-Max-Age': '600', + Vary: 'Origin', + }; +} + +// ───────────────────────────────────────────────────────────────────────────── +// Rate limiting +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Best-effort in-memory limiter, keyed by client IP + bucket. + * + * On Cloudflare this counts per isolate, which spreads the real limit across + * however many instances are warm — treat it as a speed bump and turn on a + * native Rate Limiting Rule in the dashboard for the real quota. Pooling it in + * KV/Durable Objects would add a dependency and latency to every API call, so + * it is deliberately not done here. + */ +const rateBuckets = new Map(); + +function takeRateLimit(key: string, limit: number, windowMs: number): { allowed: boolean; retryAfter: number } { + const now = Date.now(); + + // Cheap opportunistic cleanup keeps the map from growing without bound. + if (rateBuckets.size > 5000) { + for (const [k, v] of rateBuckets) if (v.resetAt <= now) rateBuckets.delete(k); + } + + const entry = rateBuckets.get(key); + if (!entry || entry.resetAt <= now) { + rateBuckets.set(key, { count: 1, resetAt: now + windowMs }); + return { allowed: true, retryAfter: 0 }; + } + + entry.count += 1; + if (entry.count > limit) { + return { allowed: false, retryAfter: Math.max(1, Math.ceil((entry.resetAt - now) / 1000)) }; + } + return { allowed: true, retryAfter: 0 }; +} + +/** Real client IP across Cloudflare, preview proxies and Express. */ +function clientIp(request: Request): string { + const direct = request.headers.get('cf-connecting-ip'); + if (direct) return direct.trim(); + const forwarded = request.headers.get('x-forwarded-for'); + if (forwarded) return forwarded.split(',')[0].trim(); + return request.headers.get('x-real-ip')?.trim() || 'unknown'; +} + +// ───────────────────────────────────────────────────────────────────────────── +// Auth +// ───────────────────────────────────────────────────────────────────────────── + +/** Client that talks to Postgres as the caller (RLS enforced). */ +function userScopedClient(env: ApiEnv, accessToken: string): SupabaseClient | null { + if (!env.VITE_SUPABASE_URL || !env.VITE_SUPABASE_ANON_KEY) return null; + return createClient(env.VITE_SUPABASE_URL, env.VITE_SUPABASE_ANON_KEY, { + global: { headers: { Authorization: `Bearer ${accessToken}` } }, + auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false }, + }); +} + +/** Client that bypasses RLS. Falls back to the anon key + the caller's JWT. */ +function serviceClient(env: ApiEnv): SupabaseClient | null { + if (!env.VITE_SUPABASE_URL) return null; + const key = env.SUPABASE_SERVICE_ROLE_KEY || env.VITE_SUPABASE_ANON_KEY; + if (!key) return null; + return createClient(env.VITE_SUPABASE_URL, key, { + auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false }, + }); +} + +const isMockMode = (env: ApiEnv) => env.MOCK_SUPABASE === '1' || env.MOCK_SUPABASE === 'true'; + +/** True on any Cloudflare Pages deployment (production and preview). */ +const isEdgeDeployment = (env: ApiEnv) => env.CF_PAGES === '1'; + +/** + * The credential-free dev loop (`npm run dev:mock`) is the only situation where + * a request may skip JWT verification. It needs the in-memory Supabase mock, + * which only exists in the local Node dev server — so an edge deployment or a + * production build can never take this path, whatever the environment says. + */ +const isCredentialFreeMock = (env: ApiEnv) => + isMockMode(env) && env.NODE_ENV !== 'production' && !isEdgeDeployment(env); + +/** + * Verifies `Authorization: Bearer ` and hands back the + * user plus an RLS-scoped client. + * + * In `npm run dev:mock` there is no Supabase project to verify against, so the + * check is skipped loudly rather than breaking the credential-free dev loop. + * Never possible in production: `MOCK_SUPABASE` plus `NODE_ENV=production` + * still verifies. + */ +async function authenticate( + request: Request, + env: ApiEnv +): Promise<{ user: User; db: SupabaseClient | null } | { error: Response }> { + if (isCredentialFreeMock(env)) { + console.warn(`[Auth] MOCK mode — skipping JWT verification for ${request.method} ${new URL(request.url).pathname}`); + return { user: { id: 'mock-user' } as User, db: null }; + } + + const header = request.headers.get('authorization') || ''; + const token = header.startsWith('Bearer ') ? header.slice(7).trim() : ''; + if (!token) return { error: json({ error: 'Authentication required' }, 401, corsHeaders(request, env)) }; + + const client = userScopedClient(env, token); + if (!client) { + console.error('[Auth] VITE_SUPABASE_URL / VITE_SUPABASE_ANON_KEY are not configured.'); + return { error: json({ error: 'Server authentication is not configured' }, 503, corsHeaders(request, env)) }; + } + + try { + const { data, error } = await client.auth.getUser(token); + if (error || !data?.user) { + return { error: json({ error: 'Invalid or expired session' }, 401, corsHeaders(request, env)) }; + } + return { user: data.user, db: client }; + } catch (err) { + console.error('[Auth] Token verification failed:', err); + return { error: json({ error: 'Invalid or expired session' }, 401, corsHeaders(request, env)) }; + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// Body parsing +// ───────────────────────────────────────────────────────────────────────────── + +/** + * `{ value, error }` rather than a discriminated union: `tsconfig.json` runs + * without `strictNullChecks`, and property-based narrowing does not work there. + */ +interface BodyResult { + value: T | null; + error: Response | null; +} + +const bodyError = (response: Response): BodyResult => ({ value: null, error: response }); + +/** + * Reads and parses a JSON body, refusing anything over `maxBytes`. + * + * The declared `Content-Length` is checked first so a huge payload is rejected + * before it is buffered; the decoded length is checked as well for chunked + * requests that never declare one. + */ +async function readJson(request: Request, maxBytes: number): Promise> { + const declared = Number(request.headers.get('content-length') || 0); + if (declared && declared > maxBytes) { + return bodyError(json({ error: 'Request body too large' }, 413)); + } + + const text = await request.text(); + if (text.length > maxBytes) { + return bodyError(json({ error: 'Request body too large' }, 413)); + } + if (!text) return { value: null, error: null }; + + try { + return { value: JSON.parse(text) as T, error: null }; + } catch { + return bodyError(json({ error: 'Malformed JSON request body' }, 400)); + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// Uploads +// ───────────────────────────────────────────────────────────────────────────── + +/** Hard ceiling for a single upload. */ +const MAX_UPLOAD_BYTES = 50 * 1024 * 1024; + +/** No `image/svg+xml`: an SVG is a script container, not a picture. */ +const ALLOWED_MIME_TYPES = new Set([ + 'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/heic', 'image/heif', 'image/bmp', 'image/avif', + 'video/mp4', 'video/webm', 'video/quicktime', 'video/x-matroska', 'video/3gpp', 'video/mpeg', + 'audio/mpeg', 'audio/mp4', 'audio/aac', 'audio/wav', 'audio/x-wav', 'audio/ogg', 'audio/webm', 'audio/flac', + 'application/pdf', 'text/plain', 'text/csv', 'application/json', + 'application/zip', 'application/x-zip-compressed', 'application/x-rar-compressed', + 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', +]); + +/** Per-media-type byte cap: images are cheap, video is not. */ +function sizeLimitFor(mimeType: string): number { + if (mimeType.startsWith('image/')) return 15 * 1024 * 1024; + if (mimeType.startsWith('video/')) return 50 * 1024 * 1024; + if (mimeType.startsWith('audio/')) return 25 * 1024 * 1024; + return 25 * 1024 * 1024; +} + +interface UploadedFile { + name: string; + type: string; + bytes: Uint8Array; +} + +/** + * Accepts both shapes so nothing breaks in the switch to the edge: + * - `multipart/form-data` with a `file` field (the original contract), or + * - a raw body with the MIME type in `Content-Type` and the name in + * `X-File-Name` (cheaper, and the only thing that works from a WebView). + */ +async function extractUpload(request: Request): Promise> { + const contentType = (request.headers.get('content-type') || '').toLowerCase(); + const declared = Number(request.headers.get('content-length') || 0); + + if (declared && declared > MAX_UPLOAD_BYTES) { + return bodyError(json({ status: 'error', message: 'File exceeds the 50MB ceiling' }, 413)); + } + + if (contentType.startsWith('multipart/form-data')) { + let form: FormData; + try { + form = await request.formData(); + } catch { + return bodyError(json({ status: 'error', message: 'Malformed multipart body' }, 400)); + } + const entry = form.get('file'); + if (!(entry instanceof File)) { + return bodyError(json({ status: 'error', message: 'No file uploaded' }, 400)); + } + return { + value: { name: entry.name || 'upload', type: entry.type, bytes: new Uint8Array(await entry.arrayBuffer()) }, + error: null, + }; + } + + const bytes = new Uint8Array(await request.arrayBuffer()); + if (bytes.byteLength === 0) { + return bodyError(json({ status: 'error', message: 'No file uploaded' }, 400)); + } + const rawName = request.headers.get('x-file-name') || 'upload'; + let name = rawName; + try { + name = decodeURIComponent(rawName); + } catch { + /* keep the raw value if it is not URI-encoded */ + } + return { value: { name, type: contentType || 'application/octet-stream', bytes }, error: null }; +} + +// ───────────────────────────────────────────────────────────────────────────── +// Push notifications (FCM HTTP v1) +// ───────────────────────────────────────────────────────────────────────────── + +interface ServiceAccount { + project_id: string; + client_email: string; + private_key: string; +} + +function parseServiceAccount(raw: string): ServiceAccount | null { + try { + let parsed = JSON.parse(raw); + if (typeof parsed === 'string') parsed = JSON.parse(parsed); + if (!parsed?.project_id || !parsed?.client_email || !parsed?.private_key) return null; + // Secret stores love escaping the newlines in PEM keys. + parsed.private_key = String(parsed.private_key).replace(/\\n/g, '\n'); + return parsed as ServiceAccount; + } catch { + return null; + } +} + +/** + * Google OAuth2 access token from a service account. + * + * This replaces `google-auth-library`, which is Node-only. Same JWT-bearer + * grant, ~15 lines, and it runs on Workers where the library cannot. + */ +async function googleAccessToken(account: ServiceAccount, scopes: string[]): Promise { + const key = await importPKCS8(account.private_key, 'RS256'); + const now = Math.floor(Date.now() / 1000); + + const assertion = await new SignJWT({ scope: scopes.join(' ') }) + .setProtectedHeader({ alg: 'RS256', typ: 'JWT' }) + .setIssuer(account.client_email) + .setAudience('https://oauth2.googleapis.com/token') + .setIssuedAt(now) + .setExpirationTime(now + 3600) + .sign(key); + + const res = await fetch('https://oauth2.googleapis.com/token', { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + assertion, + }), + }); + + const payload: any = await res.json().catch(() => null); + if (!res.ok || !payload?.access_token) { + throw new Error(payload?.error_description || payload?.error || 'Failed to obtain a Google access token'); + } + return payload.access_token as string; +} + +/** Removes a dead FCM token from whatever profile still holds it. */ +async function removeInvalidFcmToken(env: ApiEnv, badToken: string): Promise { + const db = serviceClient(env); + if (!db) return; + + try { + const { data: users, error } = await db + .from('users') + .select('id, fcm_tokens') + .contains('fcm_tokens', [badToken]); + + if (error || !users) { + console.warn('FCM cleanup: could not look up owners of a stale token:', error); + return; + } + + for (const user of users) { + if (!Array.isArray(user.fcm_tokens) || !user.fcm_tokens.includes(badToken)) continue; + const filtered = user.fcm_tokens.filter((t: string) => t !== badToken); + const { error: updateError } = await db.from('users').update({ fcm_tokens: filtered }).eq('id', user.id); + if (updateError) console.warn(`FCM cleanup: failed to update user ${user.id}:`, updateError); + else console.log(`FCM cleanup: dropped a stale token from user ${user.id}`); + } + } catch (err) { + console.warn('FCM cleanup threw:', err); + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// GitHub helpers +// ───────────────────────────────────────────────────────────────────────────── + +/** `git hash-object` for a base64 blob — SHA-1 over `blob \0`. */ +async function calculateGitHubSha(contentBase64: string): Promise { + const content = base64ToBytes(contentBase64); + const header = new TextEncoder().encode(`blob ${content.length}\0`); + const store = new Uint8Array(header.length + content.length); + store.set(header, 0); + store.set(content, header.length); + + const digest = await crypto.subtle.digest('SHA-1', store); + return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join(''); +} + +/** Base64 → bytes without `Buffer` (Workers have no Buffer). */ +function base64ToBytes(base64: string): Uint8Array { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; +} + +const GITHUB_API = 'https://api.github.com'; + +async function githubFetch(path: string, token: string, init: RequestInit = {}): Promise { + return fetch(`${GITHUB_API}${path}`, { + ...init, + headers: { + Authorization: `token ${token}`, + Accept: 'application/vnd.github.v3+json', + 'User-Agent': 'GrixChat', + ...(init.headers || {}), + }, + }); +} + +/** Turns a GitHub API failure into the same JSON shape the old proxy returned. */ +async function relayGitHubError(response: Response): Promise { + const payload: any = await response.json().catch(() => null); + return json(payload || { message: `GitHub responded ${response.status}` }, response.status); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Router +// ───────────────────────────────────────────────────────────────────────────── + +interface Ctx { + request: Request; + env: ApiEnv; + url: URL; + path: string; + cors: Record; +} + +/** `{ limit, windowMs }` per route family. */ +const LIMITS = { + api: { limit: 60, windowMs: 60_000 }, + notifications: { limit: 20, windowMs: 60_000 }, + upload: { limit: 8, windowMs: 60_000 }, + ai: { limit: 20, windowMs: 60_000 }, +} as const; + +function rateLimited(ctx: Ctx, bucket: keyof typeof LIMITS): Response | null { + const { limit, windowMs } = LIMITS[bucket]; + const verdict = takeRateLimit(`${bucket}:${clientIp(ctx.request)}`, limit, windowMs); + if (verdict.allowed) return null; + return json({ error: 'Too many requests. Please slow down and try again shortly.' }, 429, { + 'Retry-After': String(verdict.retryAfter), + }); +} + +/** + * Entry point for both adapters. + * + * Handles CORS preflight, the cross-origin write guard, rate limiting, the + * route table, and a last-resort error handler — so a route handler only ever + * has to deal with its own logic. + */ +export async function handleApiRequest(request: Request, env: ApiEnv): Promise { + const url = new URL(request.url); + const ctx: Ctx = { request, env, url, path: url.pathname, cors: corsHeaders(request, env) }; + + const finish = (response: Response): Response => { + const headers = new Headers(response.headers); + for (const [key, value] of Object.entries(ctx.cors)) headers.set(key, value); + for (const [key, value] of Object.entries(SECURITY_HEADERS)) { + if (!headers.has(key)) headers.set(key, value); + } + return new Response(response.body, { status: response.status, statusText: response.statusText, headers }); + }; + + try { + if (request.method === 'OPTIONS') { + const origin = request.headers.get('origin'); + if (origin && !isAllowedOrigin(request, env, origin)) { + return finish(json({ error: 'Origin not allowed' }, 403)); + } + return finish(new Response(null, { status: 204 })); + } + + // CSRF belt-and-braces: a browser that sends an Origin we do not recognise + // is rejected outright. Requests without an Origin (native clients) pass. + const origin = request.headers.get('origin'); + const isWrite = !['GET', 'HEAD', 'OPTIONS'].includes(request.method); + if (isWrite && origin && !isAllowedOrigin(request, env, origin)) { + console.warn(`Blocked cross-origin ${request.method} ${ctx.path} from ${origin}`); + return finish(json({ error: 'Origin not allowed' }, 403)); + } + + return finish(await route(ctx)); + } catch (err: any) { + console.error('Unhandled API error:', err); + return finish(json({ error: err?.message || 'Internal server error' }, 500)); + } +} + +async function route(ctx: Ctx): Promise { + const { request, path } = ctx; + const method = request.method; + + // ── Health ─────────────────────────────────────────────────────────────── + if (method === 'GET' && path === '/api/health') { + return json({ status: 'ok', message: 'GrixChat API is running', runtime: ctx.env.REPO_FS ? 'node' : 'edge' }); + } + + // ── LiveKit token ──────────────────────────────────────────────────────── + if (method === 'POST' && path === '/api/livekit-token') return livekitToken(ctx); + + // ── Push notifications ─────────────────────────────────────────────────── + if (method === 'POST' && path === '/api/send-notification') return sendNotification(ctx); + + // ── Grix AI (Gemini proxy) ─────────────────────────────────────────────── + if (method === 'POST' && path === '/api/grix-ai') return grixAi(ctx); + + // ── Uploads ────────────────────────────────────────────────────────────── + if (method === 'POST' && path === '/api/upload-file') return uploadFile(ctx); + + // ── GitHub ─────────────────────────────────────────────────────────────── + if (method === 'GET' && path === '/api/github/debug') return githubDebug(ctx); + if (method === 'GET' && path === '/api/github/auth-url') return githubAuthUrl(ctx); + if (method === 'GET' && (path === '/auth/github/callback' || path === '/auth/github/callback/')) { + return githubCallback(ctx); + } + if (method === 'POST' && path === '/api/github/push') return githubPush(ctx); + if (method === 'POST' && path === '/api/github/push-batch') return githubPushBatch(ctx); + if (method === 'GET' && path === '/api/github/list-files') return githubListFiles(ctx); + if (method === 'GET' && path === '/api/github/get-file-content') return githubGetFileContent(ctx); + + if (path.startsWith('/api/')) { + return json({ error: `Unknown API route: ${method} ${path}` }, 404); + } + + return json({ error: 'Not found' }, 404); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Routes +// ───────────────────────────────────────────────────────────────────────────── + +/** + * `iss`/`sub`/`nbf`/`exp` + the `video` grant — byte-for-byte the token + * `livekit-server-sdk`'s `AccessToken` produces, signed with WebCrypto via + * `jose` instead of the Node-oriented SDK so the same code runs on Workers. + */ +async function livekitToken(ctx: Ctx): Promise { + const limited = rateLimited(ctx, 'api'); + if (limited) return limited; + + const { value: body, error: bodyErrorResponse } = await readJson(ctx.request, 256 * 1024); + if (bodyErrorResponse) return bodyErrorResponse; + + const { roomName, participantIdentity } = body || {}; + if (!roomName || !participantIdentity) { + return json({ error: 'Missing roomName or participantIdentity parameters' }, 400); + } + + // The caller may only be issued a token for a room they are actually part of: + // either a call they participate in, or a conversation they belong to. + const auth = await authenticate(ctx.request, ctx.env); + if ('error' in auth) return auth.error; + + const db = serviceClient(ctx.env) || auth.db; + const isMock = isCredentialFreeMock(ctx.env); + if (db && !isMock) { + const [{ data: call }, { data: participant }] = await Promise.all([ + db.from('calls').select('id').eq('id', roomName) + .or(`caller_id.eq.${auth.user.id},receiver_id.eq.${auth.user.id}`) + .maybeSingle(), + db.from('conversation_participants').select('user_id') + .eq('conversation_id', roomName).eq('user_id', auth.user.id).maybeSingle(), + ]); + + if (!call && !participant) { + console.warn(`[LiveKit] Refusing a token for room ${roomName} — ${auth.user.id} is not a participant.`); + return json({ error: 'You are not a participant in this call' }, 403); + } + } + + // Never trust a client-supplied identity over the verified session. + const identity = isMock ? participantIdentity : auth.user.id; + + const apiKey = ctx.env.LIVEKIT_API_KEY; + const apiSecret = ctx.env.LIVEKIT_API_SECRET; + if (!apiKey || !apiSecret) { + console.warn('LiveKit: LIVEKIT_API_KEY / LIVEKIT_API_SECRET are not configured — returning a sandbox token.'); + return json({ + success: false, + error: + 'LiveKit server credentials are not configured. Please define LIVEKIT_API_KEY and LIVEKIT_API_SECRET in the Pages project settings.', + token: 'mock-livekit-token-sandbox', + }); + } + + const now = Math.floor(Date.now() / 1000); + const token = await new SignJWT({ + video: { roomJoin: true, room: roomName, canPublish: true, canSubscribe: true }, + }) + .setProtectedHeader({ alg: 'HS256' }) + .setIssuer(apiKey) + .setSubject(identity) + .setIssuedAt(now) + .setNotBefore(now) + .setExpirationTime(now + 6 * 3600) + .sign(new TextEncoder().encode(apiSecret)); + + return json({ success: true, token }); +} + +async function sendNotification(ctx: Ctx): Promise { + const limited = rateLimited(ctx, 'notifications'); + if (limited) return limited; + + const { value: parsed, error: parseError } = await readJson(ctx.request, 256 * 1024); + if (parseError) return parseError; + if (!parsed) return json({ error: 'Missing request body' }, 400); + + const { conversationId, tokens: requestedTokens, body, data } = parsed; + const env = ctx.env; + + const auth = await authenticate(ctx.request, env); + if ('error' in auth) return auth.error; + + const db = serviceClient(env) || auth.db; + const isMock = isCredentialFreeMock(env); + const canResolveRecipients = Boolean(db) && !isMock; + + // Without a database there is nothing to derive recipients from. The only + // acceptable case is the credential-free dev loop. + if (!canResolveRecipients) { + if (!isMock) return json({ error: 'Server database is not configured' }, 503); + const devTokens = Array.isArray(requestedTokens) + ? [...new Set(requestedTokens.filter((t: any) => typeof t === 'string' && t.trim()))] + : []; + console.warn(`[FCM] MOCK mode — simulating a dispatch to ${devTokens.length} client-supplied token(s).`); + return json({ + success: true, + simulated: true, + total: devTokens.length, + sentCount: 0, + message: 'Mock mode: push dispatch simulated, no device was contacted.', + }); + } + + let validTokens: string[] = []; + let title = 'GrixChat'; + + if (conversationId) { + const callerId = auth.user.id; + + const { data: participants, error } = await db! + .from('conversation_participants') + .select('user_id') + .eq('conversation_id', conversationId); + + if (error) { + console.error('FCM: failed to read conversation participants:', error); + return json({ error: 'Failed to read conversation participants' }, 500); + } + + const participantIds: string[] = (participants || []).map((p: any) => p.user_id); + if (!participantIds.includes(callerId)) { + return json({ error: 'You are not a participant in this conversation' }, 403); + } + + // Recipients come from the database; the request only says *which* thread. + const recipientIds = participantIds.filter((id) => id !== callerId); + if (recipientIds.length > 0) { + const { data: profiles, error: profileError } = await db! + .from('users') + .select('id, fcm_tokens, muted_users') + .in('id', recipientIds); + + if (profileError) console.warn('FCM: failed to read recipient profiles:', profileError); + + const collected = new Set(); + for (const profile of profiles || []) { + if (Array.isArray(profile.muted_users) && profile.muted_users.includes(callerId)) continue; + if (Array.isArray(profile.fcm_tokens)) { + profile.fcm_tokens.forEach((t: string) => { + if (typeof t === 'string' && t.trim()) collected.add(t); + }); + } + } + validTokens = [...collected]; + } + + // The title is read from the sender's row, never taken from the request, so + // it cannot be spoofed into a phishing message. + const { data: sender } = await db!.from('users').select('full_name, username').eq('id', callerId).maybeSingle(); + title = sender?.full_name || sender?.username || 'New message'; + } else { + // Self-send mode: the notification-settings test button. Anything that is + // not registered on the caller's own profile is dropped. + if (!Array.isArray(requestedTokens) || requestedTokens.length === 0) { + return json({ error: 'Missing recipient registration tokens' }, 400); + } + + const { data: self } = await db!.from('users').select('fcm_tokens').eq('id', auth.user.id).maybeSingle(); + const own = new Set( + Array.isArray(self?.fcm_tokens) ? self!.fcm_tokens.filter((t: any) => typeof t === 'string') : [] + ); + + const requested = requestedTokens.filter((t: any) => typeof t === 'string' && t.trim().length > 0); + validTokens = [...new Set(requested)].filter((t) => own.has(t)); + + if (validTokens.length === 0) { + return json({ error: 'None of those tokens belong to the authenticated user' }, 403); + } + title = typeof parsed.title === 'string' ? parsed.title.slice(0, 120) : 'GrixChat'; + } + + if (validTokens.length === 0) { + return json({ success: true, total: 0, sentCount: 0, results: [], message: 'No registered devices to notify' }); + } + + // Cap the body so this endpoint cannot be used to push essays. + const bodyText = (typeof body === 'string' ? body : '').slice(0, 200); + + const rawAccount = env.FIREBASE_SERVICE_ACCOUNT; + if (!rawAccount) { + console.warn('FCM: FIREBASE_SERVICE_ACCOUNT is not set — simulating the dispatch.'); + console.log(`[PUSH NOTIFICATION SIMULATION] title=${title} tokens=${validTokens.length}`); + return json({ + success: true, + simulated: true, + message: 'Push simulated. Configure FIREBASE_SERVICE_ACCOUNT to enable real FCM sending.', + }); + } + + const account = parseServiceAccount(rawAccount); + if (!account) return json({ error: 'FIREBASE_SERVICE_ACCOUNT is not valid JSON with a private key' }, 500); + + const accessToken = await googleAccessToken(account, ['https://www.googleapis.com/auth/firebase.messaging']); + + const results = await Promise.all( + validTokens.map(async (token) => { + try { + const response = await fetch( + `https://fcm.googleapis.com/v1/projects/${account.project_id}/messages:send`, + { + method: 'POST', + headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + message: { + token, + notification: { title, body: bodyText }, + data: { + click_action: data?.click_action || '/chats', + conversationId: data?.conversationId || '', + senderId: data?.senderId || '', + ...(data || {}), + }, + }, + }), + } + ); + + if (!response.ok) { + const failure: any = await response.json().catch(() => null); + const status = failure?.error?.status; + const message = failure?.error?.message || ''; + const isInvalidToken = + response.status === 400 || + response.status === 404 || + status === 'INVALID_ARGUMENT' || + status === 'NOT_FOUND' || + status === 'UNREGISTERED' || + message.includes('not a valid FCM registration token') || + message.includes('Requested entity was not found'); + + if (isInvalidToken) await removeInvalidFcmToken(env, token); + return { token: `${token.slice(0, 10)}…`, success: false, error: failure || response.status }; + } + + const payload: any = await response.json().catch(() => null); + return { token: `${token.slice(0, 10)}…`, success: true, messageId: payload?.name }; + } catch (err: any) { + console.error('FCM: send failed:', err?.message || err); + return { token: `${token.slice(0, 10)}…`, success: false, error: err?.message || 'send failed' }; + } + }) + ); + + return json({ + success: true, + total: validTokens.length, + sentCount: results.filter((r) => r.success).length, + results, + }); +} + +/** Server-side Gemini proxy — the API key never reaches the browser. */ +async function grixAi(ctx: Ctx): Promise { + const limited = rateLimited(ctx, 'ai'); + if (limited) return limited; + + const auth = await authenticate(ctx.request, ctx.env); + if ('error' in auth) return auth.error; + + const { value: parsed, error: parseError } = await readJson(ctx.request, 256 * 1024); + if (parseError) return parseError; + + const apiKey = ctx.env.GEMINI_API_KEY; + if (!apiKey) { + console.error('GrixAI: GEMINI_API_KEY is not configured.'); + return json({ error: 'Gemini API key is not configured on the server. Please register GEMINI_API_KEY in the Pages project settings.' }, 400); + } + + const { messages, model, modelType } = parsed || {}; + const formatted = Array.isArray(messages) ? messages : []; + + const systemMessage = formatted.find((m: any) => m.role === 'system'); + const systemInstruction = + systemMessage?.content || systemMessage?.text || 'You are Grix AI, a helpful and friendly assistant for GrixChat.'; + + const contents = formatted + .filter((m: any) => m.role !== 'system') + .map((m: any) => ({ + role: m.role === 'assistant' || m.role === 'model' ? 'model' : 'user', + parts: [{ text: m.content || m.text || '' }], + })); + + const variant = model || modelType || 'grix-ai'; + const modelId = 'gemini-3.5-flash'; + + const endpoint = `https://generativelanguage.googleapis.com/v1beta/models/${modelId}:generateContent`; + const response = await fetch(endpoint, { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-goog-api-key': apiKey }, + body: JSON.stringify({ + contents, + systemInstruction: { parts: [{ text: systemInstruction }] }, + generationConfig: { temperature: variant === 'grix-ai-pro' ? 1.0 : 0.7 }, + }), + }); + + const payload: any = await response.json().catch(() => null); + if (!response.ok) { + console.error('GrixAI: Gemini responded with an error:', payload); + return json({ error: payload?.error?.message || 'An error occurred while communicating with Gemini.' }, 502); + } + + const reply = + payload?.candidates?.[0]?.content?.parts?.map((p: any) => p.text).filter(Boolean).join('') || ''; + + return json({ success: true, reply: reply || "I'm sorry, I couldn't process that." }); +} + +/** + * Upload proxy (Catbox for media, Gofile for everything else). + * + * Signed-in callers only, MIME allowlist, per-media-type size caps — this used + * to be an anonymous 100MB-per-file host. + */ +async function uploadFile(ctx: Ctx): Promise { + const limited = rateLimited(ctx, 'upload'); + if (limited) return limited; + + const auth = await authenticate(ctx.request, ctx.env); + if ('error' in auth) return auth.error; + + const { value: file, error: uploadError } = await extractUpload(ctx.request); + if (uploadError) return uploadError; + if (!file) return json({ status: 'error', message: 'No file uploaded' }, 400); + const mime = (file.type || 'application/octet-stream').split(';')[0].trim().toLowerCase(); + + if (!ALLOWED_MIME_TYPES.has(mime)) { + return json({ status: 'error', message: `Unsupported file type: ${mime}` }, 415); + } + + const maxBytes = sizeLimitFor(mime); + if (file.bytes.byteLength > maxBytes) { + return json( + { status: 'error', message: `${mime} uploads are capped at ${Math.round(maxBytes / (1024 * 1024))}MB` }, + 413 + ); + } + + const blob = new Blob([file.bytes as unknown as BlobPart], { type: mime }); + const isMedia = mime.startsWith('image/') || mime.startsWith('video/'); + + try { + if (isMedia) { + const form = new FormData(); + form.append('reqtype', 'fileupload'); + form.append('fileToUpload', blob, file.name); + + console.log('Uploading media to Catbox…'); + const response = await fetch('https://catbox.moe/user/api.php', { + method: 'POST', + body: form, + signal: AbortSignal.timeout(60_000), + }); + const text = (await response.text()).trim(); + + if (response.ok && text.startsWith('http')) { + return json({ status: 'ok', downloadUrl: text, provider: 'catbox' }); + } + throw new Error(`Catbox error: ${text || response.status}`); + } + + console.log('Resolving a Gofile server…'); + const serverResponse = await fetch('https://api.gofile.io/servers'); + const serverPayload: any = await serverResponse.json().catch(() => null); + // The API has shipped both `data.server` and `data.servers[]` shapes. + const server = + serverPayload?.data?.server || + serverPayload?.data?.servers?.[0]?.name || + (await fetch('https://api.gofile.io/getServer').then((r) => r.json()).then((j: any) => j?.data?.server).catch(() => null)); + + if (!server) throw new Error('Gofile did not return an upload server'); + + const form = new FormData(); + form.append('file', blob, file.name); + + const response = await fetch(`https://${server}.gofile.io/contents/uploadfile`, { + method: 'POST', + body: form, + signal: AbortSignal.timeout(120_000), + }); + const payload: any = await response.json().catch(() => null); + + if (response.ok && payload?.status === 'ok') { + return json({ + status: 'ok', + downloadUrl: payload.data.downloadPage, + fileId: payload.data.fileId, + provider: 'gofile', + }); + } + throw new Error(`Gofile error: ${JSON.stringify(payload)}`); + } catch (err: any) { + console.error('Upload failed:', err?.message || err); + return json({ status: 'error', message: `Upload failed: ${err?.message || err}` }, 502); + } +} + +/** + * Reports which secrets exist. Development only. + * + * Cloudflare deployments never serve it: `CF_PAGES` is set on production *and* + * preview, and `NODE_ENV` is not automatically present on Workers, so relying + * on `NODE_ENV` alone would leave it exposed. `/api/github/auth-url` answers + * "GITHUB_CLIENT_ID is not set" when you need the same diagnostic in production. + */ +async function githubDebug(ctx: Ctx): Promise { + if (ctx.env.NODE_ENV === 'production' || isEdgeDeployment(ctx.env)) { + return json({ error: 'Not found' }, 404); + } + return json({ + hasClientId: !!ctx.env.GITHUB_CLIENT_ID, + hasClientSecret: !!ctx.env.GITHUB_CLIENT_SECRET, + appUrl: ctx.env.APP_URL || 'Not Set', + runtime: ctx.env.REPO_FS ? 'node' : 'cloudflare-pages', + env: ctx.env.NODE_ENV, + }); +} + +/** Canonical origin for OAuth redirects: APP_URL, else derived from the request. */ +function resolveAppUrl(ctx: Ctx): string { + const configured = ctx.env.APP_URL; + if (configured && configured.startsWith('http')) return configured.replace(/\/$/, ''); + + const forwardedHost = ctx.request.headers.get('x-forwarded-host') || ctx.request.headers.get('host'); + const protocol = ctx.request.headers.get('x-forwarded-proto') || ctx.url.protocol.replace(':', '') || 'https'; + return `${protocol}://${forwardedHost || ctx.url.host}`.replace(/\/$/, ''); +} + +async function githubAuthUrl(ctx: Ctx): Promise { + const clientId = ctx.env.GITHUB_CLIENT_ID; + if (!clientId) { + console.error('GITHUB_CLIENT_ID is missing from the environment.'); + return json({ error: 'GITHUB_CLIENT_ID is not set' }, 500); + } + + const redirectUri = `${resolveAppUrl(ctx)}/auth/github/callback`; + const state = crypto.randomUUID(); + const url = + `https://github.com/login/oauth/authorize?client_id=${clientId}` + + `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=repo,user,workflow&state=${state}`; + + return json({ url, redirectUri }); +} + +/** + * OAuth callback. Returns a tiny page that hands the token to the opener window + * — the popup flow the GitHub screen expects. + */ +async function githubCallback(ctx: Ctx): Promise { + const code = ctx.url.searchParams.get('code'); + const clientId = ctx.env.GITHUB_CLIENT_ID; + const clientSecret = ctx.env.GITHUB_CLIENT_SECRET; + + if (!code) return html('

Missing OAuth code.

', 400); + if (!clientId || !clientSecret) return html('

GitHub OAuth is not configured on the server.

', 500); + + try { + const response = await fetch('https://github.com/login/oauth/access_token', { + method: 'POST', + headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, + body: JSON.stringify({ client_id: clientId, client_secret: clientSecret, code }), + }); + + const payload: any = await response.json().catch(() => null); + const accessToken = payload?.access_token; + if (!accessToken) throw new Error('No access token returned'); + + // `window.opener` survives because COOP is off (see public/_headers and the + // Express adapter) — it is what makes the popup flow work. + return html(` + + + Authenticating… + + + + +
+
+ +

Authenticating with GitHub…

+

Securely connecting your accounts

+
+ + +`); + } catch (err: any) { + console.error('GitHub callback failed:', err?.message || err); + return html('

Auth failed

', 500); + } +} + +/** + * Single-file push. Relays the caller's *own* GitHub token, so this route is + * rate limited but needs no extra authorisation of its own — the server holds + * no GitHub secret here. + */ +async function githubPush(ctx: Ctx): Promise { + const limited = rateLimited(ctx, 'api'); + if (limited) return limited; + + const { value: parsed, error: parseError } = await readJson(ctx.request, 32 * 1024 * 1024); + if (parseError) return parseError; + + const { token, owner, repo, path: filePath, content, message, branch = 'main' } = parsed || {}; + if (!token || !owner || !repo || !filePath || !content) { + return json({ message: 'token, owner, repo, path and content are required' }, 400); + } + + try { + let sha: string | undefined; + const existing = await githubFetch( + `/repos/${owner}/${repo}/contents/${encodeURIComponent(filePath)}`, + token + ); + if (existing.ok) { + const meta: any = await existing.json().catch(() => null); + sha = meta?.sha; + } + + const pushResponse = await githubFetch(`/repos/${owner}/${repo}/contents/${encodeURIComponent(filePath)}`, token, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ message, content, sha, branch }), + }); + + if (!pushResponse.ok) return relayGitHubError(pushResponse); + return json(await pushResponse.json()); + } catch (err: any) { + console.error('GitHub push failed:', err?.message || err); + return json({ message: err?.message || 'Push failed' }, 502); + } +} + +/** + * Smart batch push: diffs against the remote tree, creates blobs in batches, + * then one tree + commit + ref update. + */ +async function githubPushBatch(ctx: Ctx): Promise { + const limited = rateLimited(ctx, 'api'); + if (limited) return limited; + + const { value: parsed, error: parseError } = await readJson(ctx.request, 32 * 1024 * 1024); + if (parseError) return parseError; + + const { token, owner, repo, files, message, branch = 'main', isSequential = false } = parsed || {}; + if (!token || !owner || !repo || !Array.isArray(files) || files.length === 0) { + return json({ message: 'token, owner, repo and a non-empty files[] are required' }, 400); + } + + const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + + try { + // 1. Current branch head + const branchResponse = await githubFetch(`/repos/${owner}/${repo}/branches/${branch}`, token); + if (!branchResponse.ok) return relayGitHubError(branchResponse); + const branchData: any = await branchResponse.json(); + const parentSha = branchData.commit.sha; + const baseTreeSha = branchData.commit.commit.tree.sha; + + // 2. Existing tree, to skip files that did not change + const treeResponse = await githubFetch(`/repos/${owner}/${repo}/git/trees/${baseTreeSha}?recursive=1`, token); + const treeData: any = treeResponse.ok ? await treeResponse.json().catch(() => null) : null; + const existingFiles = new Map(); + (treeData?.tree || []).forEach((node: any) => { + if (node.type === 'blob') existingFiles.set(node.path, node.sha); + }); + + // 3. Keep only what actually changed + const modified: Array<{ path: string; content: string }> = []; + for (const file of files) { + const localSha = await calculateGitHubSha(file.content); + if (localSha !== existingFiles.get(file.path)) modified.push(file); + } + console.log(`Smart Sync: ${modified.length} of ${files.length} files changed.`); + + if (modified.length === 0) { + return json({ message: 'No changes detected. Repository is already up to date.', noChanges: true }); + } + + // 3b. Sequential mode — one commit per file, for safe incremented pushes + if (isSequential) { + let uploaded = 0; + try { + for (const file of modified) { + const sha = existingFiles.get(file.path); + const response = await githubFetch(`/repos/${owner}/${repo}/contents/${file.path}`, token, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + message: `${message} - update ${file.path}`, + content: file.content, + sha: sha || undefined, + branch, + }), + }); + if (!response.ok) { + const failure: any = await response.json().catch(() => null); + throw new Error(failure?.message || `GitHub responded ${response.status}`); + } + uploaded++; + await sleep(150); // stay clear of GitHub's abuse detection + } + + return json({ + message: `Successfully uploaded all ${uploaded} files sequentially.`, + sequential: true, + uploadedCount: uploaded, + html_url: `https://github.com/${owner}/${repo}/commits/${branch}`, + }); + } catch (err: any) { + if (uploaded > 0) { + return json({ + message: `Uploaded ${uploaded} files successfully, but stopped because of a GitHub limit.`, + sequential: true, + uploadedCount: uploaded, + error: err?.message, + html_url: `https://github.com/${owner}/${repo}/commits/${branch}`, + }); + } + throw err; + } + } + + // 4. Create blobs, 5 at a time + const treeItems: Array<{ path: string; mode: string; type: string; sha: string }> = []; + const BATCH_SIZE = 5; + for (let i = 0; i < modified.length; i += BATCH_SIZE) { + const batch = modified.slice(i, i + BATCH_SIZE); + const results = await Promise.all( + batch.map(async (file) => { + const response = await githubFetch(`/repos/${owner}/${repo}/git/blobs`, token, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ content: file.content, encoding: 'base64' }), + }); + if (!response.ok) { + const failure: any = await response.json().catch(() => null); + throw new Error(`Failed to upload ${file.path}: ${failure?.message || response.status}`); + } + const blob: any = await response.json(); + return { path: file.path, mode: '100644', type: 'blob', sha: blob.sha }; + }) + ); + treeItems.push(...results); + if (i + BATCH_SIZE < modified.length) await sleep(400); + } + + // 5. New tree on top of the existing one + const newTreeResponse = await githubFetch(`/repos/${owner}/${repo}/git/trees`, token, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ base_tree: baseTreeSha, tree: treeItems }), + }); + if (!newTreeResponse.ok) return relayGitHubError(newTreeResponse); + const newTree: any = await newTreeResponse.json(); + + // 6. Commit + const commitResponse = await githubFetch(`/repos/${owner}/${repo}/git/commits`, token, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ message, tree: newTree.sha, parents: [parentSha] }), + }); + if (!commitResponse.ok) return relayGitHubError(commitResponse); + const commit: any = await commitResponse.json(); + + // 7. Move the branch + const refResponse = await githubFetch(`/repos/${owner}/${repo}/git/refs/heads/${branch}`, token, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ sha: commit.sha, force: false }), + }); + if (!refResponse.ok) return relayGitHubError(refResponse); + + console.log(`Smart Sync: branch ${branch} updated.`); + return json(await refResponse.json()); + } catch (err: any) { + console.error('Smart batch push failed:', err?.message || err); + return json({ message: err?.message || 'Batch push failed' }, 502); + } +} + +/** + * Repository Sync Tool: enumerate the checked-out source tree. + * + * Node-only by nature — Cloudflare Workers have no filesystem, so the edge + * answers 501 and the screen degrades instead of hanging. + */ +async function githubListFiles(ctx: Ctx): Promise { + const limited = rateLimited(ctx, 'api'); + if (limited) return limited; + + const auth = await authenticate(ctx.request, ctx.env); + if ('error' in auth) return auth.error; + + const repoFs = ctx.env.REPO_FS; + if (!repoFs) { + return json( + { + error: 'The repository sync tool needs a Node host with the source tree. Cloudflare Pages has no filesystem.', + files: [], + }, + 501 + ); + } + + try { + return json({ files: repoFs.listFiles() }); + } catch (err: any) { + return json({ error: err?.message || 'Failed to list files' }, 500); + } +} + +/** Repository Sync Tool: base64 of one source file (path-traversal guarded). */ +async function githubGetFileContent(ctx: Ctx): Promise { + const limited = rateLimited(ctx, 'api'); + if (limited) return limited; + + const auth = await authenticate(ctx.request, ctx.env); + if ('error' in auth) return auth.error; + + const repoFs = ctx.env.REPO_FS; + if (!repoFs) { + return json( + { error: 'The repository sync tool needs a Node host with the source tree. Cloudflare Pages has no filesystem.' }, + 501 + ); + } + + const requested = ctx.url.searchParams.get('path'); + if (!requested) return json({ error: 'Path is required' }, 400); + + try { + const content = repoFs.readFileBase64(requested); + if (content === null) return json({ error: 'File not found' }, 404); + return json({ content }); + } catch (err: any) { + return json({ error: err?.message || 'Failed to read file' }, 500); + } +} diff --git a/src/__tests__/apiRoutes.test.ts b/src/__tests__/apiRoutes.test.ts new file mode 100644 index 0000000..a108a0f --- /dev/null +++ b/src/__tests__/apiRoutes.test.ts @@ -0,0 +1,162 @@ +/** + * @vitest-environment node + * + * Contract tests for the shared API (`server/api.ts`). + * + * The same file runs on Cloudflare Pages Functions and under Express, so these + * assertions are the safety net for the security behaviour that used to be + * missing: nothing reaches a route without either a verified session or the + * credential-free local mock, cross-origin writes are refused, and oversized or + * malformed bodies are rejected before a handler sees them. + * + * Node environment on purpose: jsdom does not implement `Request`/`Response`. + */ +import {beforeEach, describe, expect, it} from 'vitest'; +import {handleApiRequest, type ApiEnv} from '../../server/api'; + +/** `npm run dev:mock` shaped env: no Supabase project, no network. */ +const MOCK_ENV: ApiEnv = {MOCK_SUPABASE: '1', NODE_ENV: 'development'}; +/** Cloudflare-shaped env: always verifies, whatever else is set. */ +const EDGE_ENV: ApiEnv = {MOCK_SUPABASE: '1', CF_PAGES: '1'}; + +const call = (path: string, init: RequestInit = {}, env: ApiEnv = MOCK_ENV) => + handleApiRequest(new Request(`http://localhost:3000${path}`, init), env); + +const postJson = ( + path: string, + body: unknown, + env: ApiEnv = MOCK_ENV, + headers: Record = {} +) => + call( + path, + { + method: 'POST', + headers: {'Content-Type': 'application/json', ...headers}, + body: typeof body === 'string' ? body : JSON.stringify(body), + }, + env + ); + +beforeEach(() => { + // The limiter is module-level state; keep tests from tripping over each other. + // (Each test uses a distinct path or well under the per-minute budget.) +}); + +describe('routing', () => { + it('answers /api/health without credentials', async () => { + const response = await call('/api/health'); + expect(response.status).toBe(200); + const body: any = await response.json(); + expect(body.status).toBe('ok'); + }); + + it('reports whether the filesystem capability was injected', async () => { + // The Express adapter injects REPO_FS; Cloudflare cannot, so the same + // handler reports which one it is running under. + const nodeAdapter: ApiEnv = { + ...MOCK_ENV, + REPO_FS: {root: '/repo', listFiles: () => [], readFileBase64: () => null}, + }; + expect((await (await call('/api/health', {}, nodeAdapter)).json() as any).runtime).toBe('node'); + expect((await (await call('/api/health', {}, EDGE_ENV)).json() as any).runtime).toBe('edge'); + }); + + it('404s unknown API paths with JSON, not the SPA shell', async () => { + const response = await call('/api/does-not-exist'); + expect(response.status).toBe(404); + expect(response.headers.get('content-type')).toContain('application/json'); + const body: any = await response.json(); + expect(body.error).toContain('Unknown API route'); + }); + + it('hides the diagnostic route on Cloudflare', async () => { + expect((await call('/api/github/debug')).status).toBe(200); + expect((await call('/api/github/debug', {}, EDGE_ENV)).status).toBe(404); + }); +}); + +describe('security headers and CORS', () => { + it('marks responses nosniff and no-referrer', async () => { + const response = await call('/api/health'); + expect(response.headers.get('x-content-type-options')).toBe('nosniff'); + expect(response.headers.get('referrer-policy')).toBe('no-referrer'); + }); + + it('answers a preflight from an allowed origin with CORS headers', async () => { + const response = await call('/api/grix-ai', { + method: 'OPTIONS', + headers: {'Origin': 'http://localhost:3000', 'Access-Control-Request-Method': 'POST'}, + }); + expect(response.status).toBe(204); + expect(response.headers.get('access-control-allow-origin')).toBe('http://localhost:3000'); + }); + + it('grants no CORS headers to an unknown origin', async () => { + const response = await call('/api/grix-ai', { + method: 'OPTIONS', + headers: {'Origin': 'https://evil.example.com', 'Access-Control-Request-Method': 'POST', 'Host': 'grixchat.gothwadtech.com'}, + }); + expect(response.headers.get('access-control-allow-origin')).toBeNull(); + }); + + it('refuses a cross-origin write outright', async () => { + const response = await handleApiRequest( + new Request('http://localhost:3000/api/send-notification', { + method: 'POST', + headers: { + 'Origin': 'https://evil.example.com', + 'Host': 'grixchat.gothwadtech.com', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({tokens: ['x']}), + }), + MOCK_ENV + ); + expect(response.status).toBe(403); + }); +}); + +describe('body handling', () => { + it('rejects malformed JSON with 400', async () => { + const response = await postJson('/api/send-notification', '{not json'); + expect(response.status).toBe(400); + expect((await response.json() as any).error).toMatch(/Malformed/i); + }); + + it('rejects a body over the route cap with 413', async () => { + const huge = JSON.stringify({tokens: ['a'.repeat(300 * 1024)]}); + const response = await postJson('/api/send-notification', huge); + expect(response.status).toBe(413); + }); + + it('rejects an empty body where one is required', async () => { + const response = await call('/api/send-notification', {method: 'POST'}); + expect(response.status).toBe(400); + }); +}); + +describe('authentication', () => { + it('lets the credential-free local mock through', async () => { + const response = await postJson('/api/send-notification', {tokens: ['demo-token']}); + expect(response.status).toBe(200); + const body: any = await response.json(); + expect(body.simulated).toBe(true); + }); + + it('never lets a Cloudflare deployment skip verification', async () => { + const response = await call( + '/api/send-notification', + {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({tokens: ['t']})}, + EDGE_ENV + ); + expect(response.status).toBe(401); + }); + + it('rejects a request with no Authorization header on a configured server', async () => { + // `{}` is a real, configured deployment: no mock flag, so no bypass. + const response = await postJson('/api/grix-ai', {messages: []}, {}); + expect(response.status).toBe(401); + expect((await response.json() as any).error).toMatch(/Authentication required/i); + }); +}); diff --git a/src/features/auth/LoginScreen.tsx b/src/features/auth/LoginScreen.tsx index 666e34a..be300e5 100644 --- a/src/features/auth/LoginScreen.tsx +++ b/src/features/auth/LoginScreen.tsx @@ -444,12 +444,12 @@ export default function LoginScreen() {

- By using GrixChat, you agree to our navigate('/terms')} className="font-bold text-[var(--primary)] hover:underline cursor-pointer">Terms of Service & navigate('/terms')} className="font-bold text-[var(--primary)] hover:underline cursor-pointer">Privacy Policy. + By using GrixChat, you agree to our navigate('/terms')} className="font-bold text-[var(--primary)] hover:underline cursor-pointer">Terms of Service & navigate('/terms')} className="font-bold text-[var(--primary)] hover:underline cursor-pointer">Privacy Policy.

- GrixChat is proudly developed and managed by Gothwad in support of India's Atmanirbhar Bharat initiative. If you have any concerns, please contact us. + GrixChat is proudly developed and managed by Gothwad in support of India's Atmanirbhar Bharat initiative. If you have any concerns, please contact us.
diff --git a/src/features/auth/SignupScreen.tsx b/src/features/auth/SignupScreen.tsx index 3179e44..81b3f96 100644 --- a/src/features/auth/SignupScreen.tsx +++ b/src/features/auth/SignupScreen.tsx @@ -584,12 +584,12 @@ export default function SignupScreen() {

- By using GrixChat, you agree to our navigate('/terms')} className="font-bold text-[var(--primary)] hover:underline cursor-pointer">Terms of Service & navigate('/terms')} className="font-bold text-[var(--primary)] hover:underline cursor-pointer">Privacy Policy. + By using GrixChat, you agree to our navigate('/terms')} className="font-bold text-[var(--primary)] hover:underline cursor-pointer">Terms of Service & navigate('/terms')} className="font-bold text-[var(--primary)] hover:underline cursor-pointer">Privacy Policy.

- GrixChat is proudly developed and managed by Gothwad in support of India's Atmanirbhar Bharat initiative. If you have any concerns, please contact us. + GrixChat is proudly developed and managed by Gothwad in support of India's Atmanirbhar Bharat initiative. If you have any concerns, please contact us.
diff --git a/vercel.json b/vercel.json deleted file mode 100644 index 57d8e04..0000000 --- a/vercel.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "version": 2, - "builds": [ - { - "src": "server.ts", - "use": "@vercel/node" - }, - { - "src": "package.json", - "use": "@vercel/static-build", - "config": { "distDir": "dist" } - } - ], - "routes": [ - { - "src": "/api/(.*)", - "dest": "server.ts" - }, - { - "src": "/auth/(.*)", - "dest": "server.ts" - }, - { - "src": "/sitemap.xml", - "dest": "server.ts" - }, - { - "src": "/.well-known/(.*)", - "dest": "server.ts" - }, - { - "src": "/manifest.json", - "dest": "/manifest.json" - }, - { - "src": "/sw.js", - "dest": "/sw.js" - }, - { - "src": "/firebase-messaging-sw.js", - "dest": "/firebase-messaging-sw.js" - }, - { - "src": "/assets/(.*)", - "dest": "/assets/$1" - }, - { - "src": "/(.*)", - "dest": "/index.html" - } - ] -} diff --git a/wrangler.toml b/wrangler.toml new file mode 100644 index 0000000..0ba3800 --- /dev/null +++ b/wrangler.toml @@ -0,0 +1,25 @@ +# Cloudflare Pages project configuration. +# +# The site is served by Cloudflare Pages at https://grixchat.gothwadtech.com: +# - `dist/` is uploaded as static assets +# - `functions/` is compiled into Pages Functions and serves the API +# +# Build settings (Cloudflare dashboard → Workers & Pages → grixchat → Settings): +# Build command: npm run build +# Build output dir: dist +# Root directory: / (repo root) +# Node version: 20 (Settings → Environment variables: NODE_VERSION=20) +# +# Runtime variables go in Settings → Environment variables (Production + +# Preview). Every VITE_* value is inlined into the bundle at build time, so +# changing one requires a redeploy. See docs/DEV_SETUP.md. + +name = "grixchat" +pages_build_output_dir = "./dist" +compatibility_date = "2025-09-01" + +# No `nodejs_compat`: the API is written against the Web platform only +# (fetch, WebCrypto, FormData, Blob, atob/btoa). Nothing in `functions/` or +# `server/api.ts` imports a Node built-in — the one capability that needs the +# filesystem (the GitHub Sync Tool) is injected by the Node adapter and answers +# 501 here instead of pretending to work. From ccbafef0660c627eb81e0e8dd453c05f2d021488 Mon Sep 17 00:00:00 2001 From: GothwadTech <295316515+GothwadTech@users.noreply.github.com> Date: Sun, 11 Oct 2026 01:42:38 +0000 Subject: [PATCH 03/11] fix: match the real Cloudflare Pages project name (gtwdchat) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The PR's Cloudflare Pages check links to the project `gtwdchat`, so wrangler.toml's `name` and every doc that told you to look under 'Workers & Pages → grixchat' were pointing at the wrong project. The custom domain is unchanged (grixchat.gothwadtech.com). Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .dev.vars.example | 2 +- .env.example | 2 +- docs/DEV_SETUP.md | 11 +++++++---- docs/KNOWN_ISSUES.md | 2 +- wrangler.toml | 8 +++++--- 5 files changed, 15 insertions(+), 10 deletions(-) diff --git a/.dev.vars.example b/.dev.vars.example index 3de9a41..11c8f5c 100644 --- a/.dev.vars.example +++ b/.dev.vars.example @@ -9,7 +9,7 @@ # ones are baked into the bundle by `npm run build/`vite already. # # In production these live in the Cloudflare dashboard: -# Workers & Pages → grixchat → Settings → Environment variables +# Workers & Pages → gtwdchat → Settings → Environment variables # ───────────────────────────────────────────────────────────────────────────── # Optional: run the API without any credentials at all. diff --git a/.env.example b/.env.example index f952c78..32a9927 100644 --- a/.env.example +++ b/.env.example @@ -5,7 +5,7 @@ # # Production runs on **Cloudflare Pages** (https://grixchat.gothwadtech.com). # Every variable below goes into the Pages project: -# Cloudflare dashboard → Workers & Pages → grixchat → Settings → Environment +# Cloudflare dashboard → Workers & Pages → gtwdchat → Settings → Environment # variables (add each one to **Production** and **Preview**) # # Everything prefixed VITE_ is inlined into the browser bundle at build time — diff --git a/docs/DEV_SETUP.md b/docs/DEV_SETUP.md index 59b7424..5fc4eb2 100644 --- a/docs/DEV_SETUP.md +++ b/docs/DEV_SETUP.md @@ -162,6 +162,8 @@ exception is authentication: without `VITE_SUPABASE_URL` + ## Deploy — Cloudflare Pages **Production lives on Cloudflare Pages: ** +(Cloudflare project name: **`gtwdchat`** — that is what the dashboard calls it, +and what `wrangler.toml` declares.) A deployment is two halves that ship together from this one repository: @@ -177,7 +179,7 @@ needs porting between environments, and there is no second server to drift. ### Project settings -Cloudflare dashboard → **Workers & Pages → grixchat → Settings**: +Cloudflare dashboard → **Workers & Pages → gtwdchat → Settings**: | Setting | Value | |---|---| @@ -198,7 +200,7 @@ triggers the Pages build; the Node server bundle is not part of it (see | File | Purpose | |---|---| -| `wrangler.toml` | Pages project config (output dir, compatibility date) | +| `wrangler.toml` | Pages project config — `name = "gtwdchat"`, output dir, compatibility date | | `functions/api/[[path]].ts` | Every `/api/*` request → `server/api.ts` | | `functions/auth/[[path]].ts` | `/auth/github/callback` → the same router | | `public/_routes.json` | Scopes Functions to `/api/*` and `/auth/*` — everything else stays on the CDN and never spins up a Function | @@ -241,8 +243,9 @@ server side, `/api/*` answers `503` on purpose. ### Custom domain -Pages → **Custom domains** → add `grixchat.gothwadtech.com`. Cloudflare issues -the certificate automatically; keep `APP_URL` in sync with whatever you set. +Pages (project `gtwdchat`) → **Custom domains** → `grixchat.gothwadtech.com` is +already attached. Cloudflare issues the certificate automatically; keep `APP_URL` +in sync with whatever you set there. ### Testing the edge build locally diff --git a/docs/KNOWN_ISSUES.md b/docs/KNOWN_ISSUES.md index 1c4c886..5145992 100644 --- a/docs/KNOWN_ISSUES.md +++ b/docs/KNOWN_ISSUES.md @@ -20,7 +20,7 @@ dashboard, Supabase, or a decision. | # | Task | Where | Why it matters | |---|---|---|---| -| A | Add the **build-time** variables: `VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY`, `VITE_FIREBASE_*`, `VITE_LIVEKIT_URL`, `NODE_VERSION=20` | Cloudflare → Workers & Pages → grixchat → Settings → Environment variables (Production **and** Preview) | They are inlined into the bundle. **Without `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` the Supabase SDK is compiled out and the deployed app cannot sign in** — the build prints a loud warning. Changing one requires a redeploy. | +| A | Add the **build-time** variables: `VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY`, `VITE_FIREBASE_*`, `VITE_LIVEKIT_URL`, `NODE_VERSION=20` | Cloudflare → Workers & Pages → gtwdchat → Settings → Environment variables (Production **and** Preview) | They are inlined into the bundle. **Without `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` the Supabase SDK is compiled out and the deployed app cannot sign in** — the build prints a loud warning. Changing one requires a redeploy. | | B | Add the **runtime secrets** for the API: `GEMINI_API_KEY`, `FIREBASE_SERVICE_ACCOUNT`, `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET`, `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `SUPABASE_SERVICE_ROLE_KEY`, `APP_URL=https://grixchat.gothwadtech.com` | same screen as above | The API verifies JWTs against `VITE_SUPABASE_URL` + `VITE_SUPABASE_ANON_KEY`, so those two must be present **server-side as well**. Without any of these the matching feature returns a clear "not configured" error instead of crashing. Step-by-step: [DEV_SETUP.md](./DEV_SETUP.md#deploy--cloudflare-pages). | | C | Confirm the Pages build settings: build command `npm run build`, output `dist`, root `/`; production branch = your main branch; custom domain `grixchat.gothwadtech.com` attached | Cloudflare → the project's Settings / Custom domains | `wrangler.toml` pins the output dir and compatibility date, but the dashboard values win. | | D | Decide the fate of `call_candidates` (issue 7) | Supabase SQL editor | It is defined but unused. Drop it with:
`DROP TABLE IF EXISTS public.call_candidates CASCADE;`
or keep it and adopt the table-based signalling in `db/3_webrtc_signaling_architecture.md`. | diff --git a/wrangler.toml b/wrangler.toml index 0ba3800..73fa7ff 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -1,10 +1,12 @@ # Cloudflare Pages project configuration. # -# The site is served by Cloudflare Pages at https://grixchat.gothwadtech.com: +# The site is served by Cloudflare Pages at https://grixchat.gothwadtech.com +# (project: `gtwdchat`): # - `dist/` is uploaded as static assets # - `functions/` is compiled into Pages Functions and serves the API # -# Build settings (Cloudflare dashboard → Workers & Pages → grixchat → Settings): +# The Cloudflare Pages project is named `gtwdchat` (Workers & Pages → gtwdchat). +# Build settings (dashboard → Workers & Pages → gtwdchat → Settings): # Build command: npm run build # Build output dir: dist # Root directory: / (repo root) @@ -14,7 +16,7 @@ # Preview). Every VITE_* value is inlined into the bundle at build time, so # changing one requires a redeploy. See docs/DEV_SETUP.md. -name = "grixchat" +name = "gtwdchat" pages_build_output_dir = "./dist" compatibility_date = "2025-09-01" From d8f528c6ef285a40b02cb9b7d7ee55d48ed8ae7b Mon Sep 17 00:00:00 2001 From: GothwadTech <295316515+GothwadTech@users.noreply.github.com> Date: Sun, 11 Oct 2026 01:45:27 +0000 Subject: [PATCH 04/11] ci: build on Node 22, not 20 (wrangler 4 requires >= 22) The new 'Build Pages Functions' step failed on the runner while passing locally: wrangler@4.149.0 declares engines.node >= 22.0.0 and exits non-zero on Node 20, which the workflow pinned. Move CI to Node 22 and recommend NODE_VERSION=22 for the Pages build so the toolchain matches whatever installs the devDependencies. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .env.example | 5 +++-- .github/workflows/ci.yml | 5 ++++- docs/DEV_SETUP.md | 4 ++-- docs/KNOWN_ISSUES.md | 2 +- wrangler.toml | 3 ++- 5 files changed, 12 insertions(+), 7 deletions(-) diff --git a/.env.example b/.env.example index 32a9927..1f71465 100644 --- a/.env.example +++ b/.env.example @@ -86,8 +86,9 @@ MOCK_SUPABASE= # Port for the Node dev server. Cloudflare ignores it. PORT= -# Node version used by the Cloudflare Pages build (`20`). Set it in the Pages -# environment variables rather than here. +# Node version used by the Cloudflare Pages build (`22`). `wrangler@4` requires +# Node >= 22, and Cloudflare's build runs `npm ci`, so 22 keeps the toolchain +# consistent. Set it in the Pages environment variables rather than here. NODE_VERSION= # ── Optional ───────────────────────────────────────────────────────────────── diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 559160e..11b0b38 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,7 +33,10 @@ jobs: - name: Set up Node uses: actions/setup-node@v4 with: - node-version: 20 + # 22, not 20: `wrangler@4` requires Node >= 22 and exits non-zero on + # older runtimes. The app itself builds on 20 — this is for the + # Pages Functions bundle check below. + node-version: 22 cache: 'npm' - name: Install dependencies diff --git a/docs/DEV_SETUP.md b/docs/DEV_SETUP.md index 5fc4eb2..f15a12d 100644 --- a/docs/DEV_SETUP.md +++ b/docs/DEV_SETUP.md @@ -187,7 +187,7 @@ Cloudflare dashboard → **Workers & Pages → gtwdchat → Settings**: | Build output directory | `dist` | | Root directory | `/` (repo root) | | Framework preset | None / Vite | -| Node version | `NODE_VERSION=20` (environment variable) | +| Node version | `NODE_VERSION=22` (environment variable — `wrangler@4` needs Node ≥ 22) | | Production branch | your main branch | `wrangler.toml` pins the same output directory and the compatibility date, so @@ -230,7 +230,7 @@ redeploy), the rest is read per request by the Functions. | `SUPABASE_SERVICE_ROLE_KEY` | Push fan-out + FCM token cleanup | | `APP_URL` | `https://grixchat.gothwadtech.com` — OAuth redirect base and the CORS allowlist | | `ALLOWED_ORIGINS` | Optional extra origins | -| `NODE_VERSION` | `20` | +| `NODE_VERSION` | `22` | | `NODE_ENV` | Optional; set `production` to hide the diagnostic route (already hidden on Pages) | Missing credentials degrade gracefully — the API logs a warning and returns a diff --git a/docs/KNOWN_ISSUES.md b/docs/KNOWN_ISSUES.md index 5145992..1ab0526 100644 --- a/docs/KNOWN_ISSUES.md +++ b/docs/KNOWN_ISSUES.md @@ -20,7 +20,7 @@ dashboard, Supabase, or a decision. | # | Task | Where | Why it matters | |---|---|---|---| -| A | Add the **build-time** variables: `VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY`, `VITE_FIREBASE_*`, `VITE_LIVEKIT_URL`, `NODE_VERSION=20` | Cloudflare → Workers & Pages → gtwdchat → Settings → Environment variables (Production **and** Preview) | They are inlined into the bundle. **Without `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` the Supabase SDK is compiled out and the deployed app cannot sign in** — the build prints a loud warning. Changing one requires a redeploy. | +| A | Add the **build-time** variables: `VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY`, `VITE_FIREBASE_*`, `VITE_LIVEKIT_URL`, `NODE_VERSION=22` | Cloudflare → Workers & Pages → gtwdchat → Settings → Environment variables (Production **and** Preview) | They are inlined into the bundle. **Without `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` the Supabase SDK is compiled out and the deployed app cannot sign in** — the build prints a loud warning. Changing one requires a redeploy. | | B | Add the **runtime secrets** for the API: `GEMINI_API_KEY`, `FIREBASE_SERVICE_ACCOUNT`, `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET`, `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `SUPABASE_SERVICE_ROLE_KEY`, `APP_URL=https://grixchat.gothwadtech.com` | same screen as above | The API verifies JWTs against `VITE_SUPABASE_URL` + `VITE_SUPABASE_ANON_KEY`, so those two must be present **server-side as well**. Without any of these the matching feature returns a clear "not configured" error instead of crashing. Step-by-step: [DEV_SETUP.md](./DEV_SETUP.md#deploy--cloudflare-pages). | | C | Confirm the Pages build settings: build command `npm run build`, output `dist`, root `/`; production branch = your main branch; custom domain `grixchat.gothwadtech.com` attached | Cloudflare → the project's Settings / Custom domains | `wrangler.toml` pins the output dir and compatibility date, but the dashboard values win. | | D | Decide the fate of `call_candidates` (issue 7) | Supabase SQL editor | It is defined but unused. Drop it with:
`DROP TABLE IF EXISTS public.call_candidates CASCADE;`
or keep it and adopt the table-based signalling in `db/3_webrtc_signaling_architecture.md`. | diff --git a/wrangler.toml b/wrangler.toml index 73fa7ff..0ebbf89 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -10,7 +10,8 @@ # Build command: npm run build # Build output dir: dist # Root directory: / (repo root) -# Node version: 20 (Settings → Environment variables: NODE_VERSION=20) +# Node version: 22 (Settings → Environment variables: NODE_VERSION=22, +# because wrangler@4 requires Node >= 22) # # Runtime variables go in Settings → Environment variables (Production + # Preview). Every VITE_* value is inlined into the bundle at build time, so From a2fdef916cca46fb1d9c7473cce06bd1e60719ef Mon Sep 17 00:00:00 2001 From: GothwadTech <295316515+GothwadTech@users.noreply.github.com> Date: Sun, 11 Oct 2026 01:46:51 +0000 Subject: [PATCH 05/11] ci: bump actions to their Node 24 majors (checkout@v7, setup-node@v7) The v4 pair targets Node 20, which the runners now force onto Node 24 and flag as deprecated on every run. No behaviour change. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .github/workflows/ci.yml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 11b0b38..10adf68 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,5 +1,5 @@ # Continuous integration only — Cloudflare Pages builds and deploys the site -# itself from this repository (Workers & Pages → grixchat). +# itself from this repository (Workers & Pages → gtwdchat). # # This workflow exists to fail fast on a broken push: a type error, a failing # test or a broken bundle, before Cloudflare picks the commit up. @@ -28,10 +28,13 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 + with: + # Nothing here needs git history beyond the commit being tested. + fetch-depth: 1 - name: Set up Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v7 with: # 22, not 20: `wrangler@4` requires Node >= 22 and exits non-zero on # older runtimes. The app itself builds on 20 — this is for the From d0d8a72950c5c097f52334c67d9d114c1c13afa2 Mon Sep 17 00:00:00 2001 From: GothwadTech <295316515+GothwadTech@users.noreply.github.com> Date: Sun, 11 Oct 2026 02:29:18 +0000 Subject: [PATCH 06/11] fix(egress): stop re-downloading the chat list on every realtime event 5 GB in a month with 2-3 active users was never the messages, it was the reaction to them: every message INSERT *and* every read receipt row made each open client re-run the whole conversation list (6 queries, ~127 KB, no debounce, users(*) per participant, plus a separate newest-messages query). Client (0 bytes per message now): - useConversations patches the list row straight from the Realtime payload (preview, time, order, unread); one debounced structural refetch on mount/focus/structural changes, one channel instead of one per chat. - Conversation list = 1 round trip with CONVERSATION_LIST_SELECT: no users(*), no message rows. Measured 41 KB vs 127 KB before. - Read receipts write one row (conversation_participants.last_read_at) instead of one UPDATE per unread message; legacy path bounded by the last marker. - follows cached for 5 min; presence heartbeat 60s -> 5min; profile write throttle 45s -> 4min; photos downscaled to 1600px/JPEG 0.82 and stored with a 1-year immutable cache; TabBottom unread scan capped at 500 rows. Database (user-run, idempotent): sql/09_egress_optimizations.sql adds the read marker + the RLS UPDATE policy it needs (RLS is on and no UPDATE policy existed, so the write would have silently changed 0 rows), the last_message* sync trigger, REPLICA IDENTITY fixes (FULL only where a filtered DELETE must reach clients), indexes, an optional unread-count RPC and a retention pruner. Verified against a real Postgres: applies clean, re-runs clean, trigger fast and slow paths, RLS isolation, prune. Docs: docs/EGRESS_AUDIT.md (measurements, ranked causes, six plus two database-foundation mistakes incl. the world-readable users table and the missing UPDATE policy, caching plan, maintenance rules); AGENTS.md rules "a Realtime event patches state, never triggers a list-wide query" and "narrow selects, always"; KNOWN_ISSUES hand-off rows F/G. Tests: src/__tests__/egressBudget.test.ts (query stays narrow, message-free and under 48 KB) and src/__tests__/egressRealtime.test.tsx (an incoming message patches the visible list with zero list queries). 104/104 green. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- AGENTS.md | 40 +- dev/mock/seed.ts | 3 + docs/CONTEXT.md | 3 + docs/EGRESS_AUDIT.md | 266 +++++++++ docs/KNOWN_ISSUES.md | 24 + sql/09_egress_optimizations.sql | 369 ++++++++++++ src/__tests__/egressBudget.test.ts | 176 ++++++ src/__tests__/egressRealtime.test.tsx | 98 ++++ src/components/layout/TabBottom.tsx | 5 +- src/features/chat/hooks/useChatMessages.ts | 48 +- src/features/chat/hooks/useConversations.ts | 618 +++++++++++--------- src/providers/AuthProvider.tsx | 12 +- src/services/ImageService.ts | 42 +- src/services/SupabaseStorageService.ts | 5 +- src/services/db/userProfileService.ts | 14 +- 15 files changed, 1426 insertions(+), 297 deletions(-) create mode 100644 docs/EGRESS_AUDIT.md create mode 100644 sql/09_egress_optimizations.sql create mode 100644 src/__tests__/egressBudget.test.ts create mode 100644 src/__tests__/egressRealtime.test.tsx diff --git a/AGENTS.md b/AGENTS.md index 3dfa26f..3fe765d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -84,6 +84,40 @@ list screens. Initial loads are 20–30 rows. `ChatService.getMessages(id, limit = 50)`. +**Every list query gets a `limit`.** No exceptions — an unbounded `.select()` +is a full table download billed as egress. + +### E. A Realtime event patches state — it never triggers a list-wide query + +**A Realtime event may patch state. It may never trigger a list-wide query.** + +The payload is the data. One incoming message updates one row in the +conversation list, in place, from the event itself: + +```ts +// ❌ banned — every message re-downloads the whole conversation list +.on('postgres_changes', {event: 'INSERT', schema: 'public', table: 'messages'}, () => fetchConversations()) + +// ✅ required — the payload is enough (useConversations.patchConversationFromMessage) +.on('postgres_changes', {event: 'INSERT', ...}, (payload) => patchConversationFromMessage(payload.new)) +``` + +Refetching a whole list on individual events is what burned 5 GB/month with +three active users. Mount, focus and *structural* changes (a chat added, a +participant changed) may refetch — traffic may not. Full analysis and the +measurements: **[EGRESS_AUDIT.md](./EGRESS_AUDIT.md)**. The two rules are +machine-checked by `src/__tests__/egressBudget.test.ts` (the list query stays +narrow and message-free) and `src/__tests__/egressRealtime.test.tsx` (an +incoming message causes zero `conversations` / +`conversation_participants` queries). + +### F. Narrow selects, always + +Never `select('*')` on a shared table, and never `users(*)` for other people — +the row carries `settings`, `lock` (passcode hash), `fcm_tokens` and six +private arrays. Name the columns: the conversation list needs six of them. +Response bytes are egress, whether or not you render them. + --- ## 3. Code structure @@ -180,7 +214,7 @@ Rules: |---|---| | `npm run build` | ✅ passes | | `npm run dev` / `dev:mock` | ✅ passes | -| `npm test` | ✅ 99/99 | +| `npm test` | ✅ 104/104 | | `npm run lint` | ✅ 0 errors | | Dead code | ✅ **0 files** — 189/189 reachable. See [`docs/DEAD_CODE.md`](./docs/DEAD_CODE.md) | | Tables queried but missing from `sql/` | ✅ 0 | @@ -191,7 +225,8 @@ Rules: | Notifications inbox | ✅ written by `services/db/notificationService.ts`, read from `content` | | CI | ✅ typecheck + test + Functions bundle check + build (no deploy step) | | Pages secrets | 🧑 **check they are set in the Cloudflare dashboard** — see KNOWN_ISSUES | -| Test coverage | ⚠️ only login→chat, the notification writer and the reset route are exercised | +| Egress | ✅ list query patched from Realtime payloads, 0 bytes per message — see [`docs/EGRESS_AUDIT.md`](./docs/EGRESS_AUDIT.md) | +| Test coverage | ⚠️ only login→chat, the notification writer, the reset route and the two egress guards are exercised | Full prioritised list: **[`docs/KNOWN_ISSUES.md`](./docs/KNOWN_ISSUES.md)**. @@ -216,5 +251,6 @@ change. | [`docs/DATA_MODEL.md`](./docs/DATA_MODEL.md) | every table and RPC, and what is missing | | [`docs/ARCHITECTURE.md`](./docs/ARCHITECTURE.md) | directory map, data flow, what is reachable | | [`docs/KNOWN_ISSUES.md`](./docs/KNOWN_ISSUES.md) | prioritised bug/fix list | +| [`docs/EGRESS_AUDIT.md`](./docs/EGRESS_AUDIT.md) | Supabase egress, Realtime traffic, list-query rules | | [`docs/DEAD_CODE.md`](./docs/DEAD_CODE.md) | the deletion record — what was removed and why | | [`docs/legacy/`](./docs/legacy/) | historical — **not current guidance** | diff --git a/dev/mock/seed.ts b/dev/mock/seed.ts index 1352a15..3ec9f78 100644 --- a/dev/mock/seed.ts +++ b/dev/mock/seed.ts @@ -360,6 +360,9 @@ export function buildSeed() { id: `p${String(pIdx++).padStart(35, '0')}`, conversation_id, user_id, + // Read marker (sql/09_egress_optimizations.sql). Unread is derived from + // `last_read_at` instead of scanning every unread message row. + last_read_at: daysAgo(1), created_at: daysAgo(28), joined_at: daysAgo(28), }); diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 7f67917..37e24c3 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -163,6 +163,8 @@ The long version is in **[../AGENTS.md](../AGENTS.md)**. Short version: 1. **Never listen to a whole table.** Every `postgres_changes` subscription must carry a `filter`. Unfiltered listeners are banned for egress reasons. + And a Realtime event may **patch state, never trigger a list-wide query** — + that one habit cost 5 GB/month; see [EGRESS_AUDIT.md](./EGRESS_AUDIT.md). 2. **Transient state goes over Broadcast/Presence, not the DB.** Typing, read ticks, call signalling, presence → `channel().send()`, 0 bytes of egress. 3. **Don't import across sibling features.** `features/chat/` must not reach @@ -186,5 +188,6 @@ The long version is in **[../AGENTS.md](../AGENTS.md)**. Short version: | [DATA_MODEL.md](./DATA_MODEL.md) | you touch the database | | [ARCHITECTURE.md](./ARCHITECTURE.md) | you need to find where something lives | | [KNOWN_ISSUES.md](./KNOWN_ISSUES.md) | you want the prioritised bug/fix list | +| [EGRESS_AUDIT.md](./EGRESS_AUDIT.md) | egress is high, or you touch Realtime / list queries | | [DEAD_CODE.md](./DEAD_CODE.md) | the deletion record — what was removed and why | | [legacy/](./legacy/) | historical docs — **not current guidance** | diff --git a/docs/EGRESS_AUDIT.md b/docs/EGRESS_AUDIT.md new file mode 100644 index 0000000..398193c --- /dev/null +++ b/docs/EGRESS_AUDIT.md @@ -0,0 +1,266 @@ +# Egress Audit — why 2–3 users burned 5 GB in a month + +**Status:** the dominant cause is **found, measured and fixed in code**; the +database half needs one SQL file run by hand +([`sql/09_egress_optimizations.sql`](../sql/09_egress_optimizations.sql)). + +**Symptom:** 5 GB of Supabase egress in under a month. 2–3 active users, +2–3 hours of chatting a day, almost no files shared. 70–80 % of the bill with +almost nothing but text messages. + +**Verdict:** it was never the messages. It was the *reaction* to them. + +--- + +## 1. The one-line answer + +Every realtime event — every message, **and every row of every read receipt** — +made each open client re-download its entire conversation list: **6 round-trips, +25–130 KB per event, per client.** Read receipts are one event *per unread +message*, so opening a chat with 30 unread messages fired 30 of those refetches +at the other device. + +Measured, not estimated (see §3). One message ≈ **250 KB**, two clients ≈ +**500 KB**. At ~350 messages/day that is **~170 MB/day ≈ 5 GB/month** — the +number on the dashboard. + +--- + +## 2. Where the bytes actually went + +Ranked by impact. Line references are to the code *before* this audit's fix. + +| # | What | Where | Cost | +|---|---|---|---| +| 1 | **Full conversation-list refetch per realtime event.** `useConversations` subscribed to `messages` (`event: '*'`) and `conversations` for **every** conversation, and each handler called `fetchConversations()` — 6 queries, no debounce, no in-flight guard. | `src/features/chat/hooks/useConversations.ts` | **~250 KB per message per client** | +| 2 | **Read receipts were one UPDATE per unread message.** `markAsRead` ran `UPDATE messages SET is_read = true WHERE … is_read = false`; Postgres emits one WAL row-change per row, and Realtime broadcasts each one. | `src/features/chat/hooks/useChatMessages.ts` | **30 unread → 30 events → 30 × 127 KB** in the other client | +| 3 | **The newest-messages query.** Every refetch pulled `.limit(max(50, conversations × 5))` full message rows ordered across *all* chats — to draw a one-line preview that the `conversations.last_message` column already had. | same as #1 | 30 rows = 6.5 KB → 135 rows = **36.7 KB** | +| 4 | **`select('*')` with a nested `users(*)`.** Every participant came back as the *entire* user row — `settings` jsonb, `lock` (the passcode hash), `fcm_tokens`, six arrays. The list renders six columns. | same as #1 | **0.83 KB per participant row** vs ~0.15 KB needed | +| 5 | **`REPLICA IDENTITY FULL`** on `users`, `messages`, `conversations`, `calls`. Every UPDATE broadcasts the complete OLD row *and* the complete NEW row to every subscriber. | `sql/05_advanced_optimizations_and_realtime.sql:120-124` (5 tables, incl. `call_candidates`) | 2× payload on every update, and ships the passcode hash | +| 6 | **Unread counted by downloading messages.** `.select('conversation_id').eq('is_read', false)` — one row per unread message, uncapped, on **every** refetch, in **two** components (`useConversations` *and* `TabBottom`). | `useConversations.ts`, `src/components/layout/TabBottom.tsx` | 84 rows = 4.8 KB, unbounded with backlog | +| 7 | **Follows re-fetched every time.** The full follow graph in both directions, on every refetch, though it changes only when someone follows. | `useConversations.ts` | 60 rows = **6.4 KB per refetch** | +| 8 | **A channel per conversation.** 20 chats = 20 Realtime channels × 2 table bindings, re-created whenever the list identity changed (which the refetch itself caused). | `useConversations.ts` | connection churn, 40+ bindings | +| 9 | **Re-render → refetch loop.** `fetchConversations` depended on the `userData` *object*, and the 60 s presence heartbeat replaced that object — refetching the list and tearing down every channel once a minute. | `useConversations.ts` + `src/providers/AuthProvider.tsx` | ~24 KB/min/client ≈ 35 MB/month/client | +| 10 | **Storage with a 1-hour cache.** `cacheControl: '3600'` on upload, plus originals 3–8 MB, un-resized — a 4 MB photo rendered in a 300 px bubble, re-downloaded after every hour. | `src/services/SupabaseStorageService.ts`, `src/services/ImageService.ts` | scales with every reopen, every device | + +Two multipliers on top: **every open tab is another client**, and `markAsRead` +ran with `force` on mount, on focus and on visibility change — so the receipt +storm repeated all day long. + +--- + +## 3. The measurements + +A probe (kept as `src/__tests__/egressBudget.test.ts`) drives the mock Supabase +with a realistic account — **20 chats, 60 follow edges, 400 messages** — and +measures the exact JSON the client pulls: + +``` +fetchConversations() with 20 chats / 60 follows / 400 messages + participations 1.6 KB + conversations + participants + users(*) 77.7 KB ← users(*) 0.83 KB/row + follows (both directions) 6.4 KB + unread message rows (1 per unread msg) 4.8 KB + latest message rows (limit N*5) 36.7 KB ← 135 rows + chat_settings 0.2 KB + TOTAL 127.4 KB (6 round-trips) +``` + +And the same account answered by the **fixed** code path — one round trip, +narrow columns, no message rows: + +``` +conversation list, fixed path + TOTAL 41 KB (1 round-trip, 0 message rows) +``` + +**3× smaller per call — and it is no longer called per message.** The remaining +41 KB is the data the list genuinely renders (27 chat rows + 54 participant +rows), and it runs on mount, on focus and on structural changes only. The same +fixture is asserted in `src/__tests__/egressBudget.test.ts`, which fails if +whole user rows or message rows creep back in. + +### The arithmetic that reproduces the bill + +``` +350 messages/day (2–3 h of chatting) +× 2 refetches/message (messages INSERT + conversations UPDATE) +× ~127 KB (measured) +× 2 clients (both devices download it) += ~178 MB/day ≈ 5.3 GB/month ← matches the dashboard +``` + +After the fix the per-message cost is **0 bytes**: the list row is patched from +the realtime payload. The 41 KB fetch now happens on mount, on focus and on +structural changes — call it 10–20 times a day, ≈ 0.6 MB/day. + +Read receipts sat on top of that, unbounded by the unread backlog. + +--- + +## 4. What is fixed in code (this commit) + +> Anchors below are **function/constant names**, not line numbers — grep the +> symbol; line numbers drift with every edit. + +| Fix | File | +|---|---| +| **No network call on message traffic.** A message INSERT patches the list row (preview, time, order, unread) straight from the realtime payload. | `useConversations.ts` → `patchConversationFromMessage()` | +| **`conversations` UPDATE also patches in place** — `last_message*` is already in the payload. | `useConversations.ts` → `patchConversationFromRow()` | +| **One channel instead of N**, with `conversation_id=in.(…)` / `id=in.(…)` filters. | `useConversations.ts` → `chat-list-live-*` effect | +| **Structural events are debounced** (1.2 s) and can never overlap — one refresh in flight, bursts collapse. | `useConversations.ts` → `scheduleStructuralRefresh()` (`STRUCTURAL_DEBOUNCE_MS`) | +| **Narrow columns**: `users(id, username, full_name, photo_url, is_online, last_seen)` instead of `users(*)` — no more `settings`/`lock`/`fcm_tokens` per participant. | `useConversations.ts` → `CONVERSATION_LIST_SELECT` | +| **The newest-messages query is gone**; the list uses the denormalized `conversations.last_message*`. | `useConversations.ts` → `fetchConversations()` | +| **Follows cached for 5 minutes**, invalidated by follow events. | `useConversations.ts` → `FOLLOWS_TTL_MS` / `followsCacheKey` | +| **One round trip** for the whole list (participations → conversations → participants → users in a single embedded select). | `useConversations.ts` → `fetchConversations()` | +| **Read receipts are one row**: `conversation_participants.last_read_at`. Falls back to the old per-message update (bounded by the last marker) until the SQL is applied. | `useChatMessages.ts` → `executeUpdate` in `markAsRead` | +| **Unread is a comparison**, not a scan — exact count from messages already cached on the device. | `useConversations.ts` → the `unreadMap` builder in `fetchConversations()` | +| **Focus/visibility re-sync** replaces the "refetch on every event" habit. | `useConversations.ts` → structural effect | +| **No more re-render refetch loop**: deps use stable values; the presence heartbeat is 5 min (was 60 s) and the write throttle 4 min (was 45 s). | `AuthProvider.tsx` → `PRESENCE_HEARTBEAT_MS`, `userProfileService.ts` → `STATUS_WRITE_THROTTLE_MS` | +| **Photos are downscaled to 1600 px / JPEG 0.82 before upload**, and stored with a 1-year immutable cache (objects are already uniquely named). | `ImageService.ts` → `compressImage()`, `SupabaseStorageService.ts` → `cacheControl` | +| **Tab-bar unread scan capped** at 500 rows. | `TabBottom.tsx` → legacy unread scan | + +The app works **before and after** the SQL is applied: every read-marker call is +feature-detected once per session and falls back to the old behaviour. + +--- + +## 5. What only you can run (2 minutes) + +Supabase dashboard → **SQL Editor** → paste +[`sql/09_egress_optimizations.sql`](../sql/09_egress_optimizations.sql) → Run. +It is idempotent, and it ends with a self-check query. + +What it does: + +1. **`conversation_participants.last_read_at`** (+ index **+ a missing RLS + UPDATE policy**) — the read marker. The policy matters: RLS is enabled on + that table and `01_core_schema.sql` defines SELECT/INSERT/DELETE only, so an + UPDATE matches no policy, changes **0 rows and reports no error** — the + marker would silently never move. +2. **A trigger that maintains `conversations.last_message*`** (including + `last_message_sender_id` for ticks), so the client never re-reads messages + for a preview. +3. **`REPLICA IDENTITY DEFAULT`** on `users`, `conversations` and `calls` — + UPDATE payloads shrink to the new row + primary key, and the passcode hash / + FCM tokens stop travelling over Realtime. `FULL` **stays** on + `conversation_participants` (tiny rows, and the client must see a participant + being removed) and on `messages` (`useChatMessages` filters DELETE events by + `conversation_id`, and that column only exists in `old` under `FULL` — drop + it and "delete for everyone" silently stops propagating; the read-marker + change is what kills message UPDATE volume). +4. **Indexes** for the hot paths: `messages(conversation_id, created_at DESC)`, + `conversations(last_message_at DESC)`, a partial index for unread, and + `conversation_participants(user_id, last_read_at)`. +5. An optional **`get_unread_counts()`** RPC — exact badges without scanning. +6. An optional **`prune_old_messages(days)`** retention function (trigger + disabled for the bulk delete, affected conversations re-previewed in one + statement). + +Verified end to end against a real Postgres before shipping: the file applies +cleanly, re-applying it is a no-op, the trigger's fast and slow paths behave, +RLS lets a user move their own marker and nobody else's, `get_unread_counts()` +returns the right badges, and the self-check reports 7 × OK. + +> ⚠️ Point 3 is the one to not skip. With `REPLICA IDENTITY FULL`, Supabase +> broadcasts the whole row on both sides of every UPDATE — on `users` that +> includes the **app-lock passcode hash** and the FCM token list. + +Then, in the dashboard: **Reports → Egress** has a breakdown by Postgres / +Realtime / Storage / Functions. Re-run it a day later; the drop should be +visible per-category. + +--- + +## 6. Database foundation — the mistakes, in order + +You asked whether the schema itself is wrong. Partly yes: + +1. **Read state was modelled per message, not per participant.** `messages.is_read` + means "who read this" is answered by writing N rows, and every row is a + Realtime event. The normal model is one `last_read_at` per participant — + which also makes unread a comparison, not a scan. **This is the single + biggest design fix** and it is in `09_egress_optimizations.sql`. +2. **`REPLICA IDENTITY FULL` on hot, wide, private tables.** It was added so + DELETE/UPDATE filters would work, but it doubles every UPDATE payload and + leaks private columns. The right split is: `FULL` only where a *filtered + DELETE* must reach the client (`conversation_participants`, `messages`), + `DEFAULT` everywhere else. Advanced: `REPLICA IDENTITY USING INDEX` on a + unique `(id, conversation_id)` index gives `old` just those columns — worth + testing if message UPDATE payloads ever matter again. +3. **The chat list's data was not denormalized.** `conversations.last_message` + existed but was written only by the client's send path, so the read path + re-derived it from `messages` — 135 rows on every refresh. A trigger makes + the column authoritative. +4. **`users` mixes public profile data with private state** (`settings`, + `lock`, `fcm_tokens`, `blocked_users`…). Every "fetch a user" query therefore + drags secrets and bloat. Splitting private state into `user_private` (or at + minimum never selecting `*` for other users) is the structural fix; the code + fix applied here is to select explicit columns, always. +5. **No composite index for the actual access pattern** + (`conversation_id` + `created_at DESC`) and no partial index for unread + scans. +6. **Unbounded queries with no pagination ceiling** — the unread scan, the + newest-messages window and `users.select('*')` all grow with data volume. + Every list query now has a `limit`. + +7. **A missing RLS UPDATE policy on `conversation_participants`.** With RLS on + and no UPDATE policy, writes succeed "silently" by affecting zero rows — the + most expensive kind of bug to find. Any table the client writes to needs a + policy per verb; this one only ever had SELECT/INSERT/DELETE. Fixed in + `09_egress_optimizations.sql`. +8. **`FOR SELECT USING (true)` on `users` and `conversation_participants`.** + Every authenticated account can read every other account's `email`, `phone`, + `lock` (passcode hash), `fcm_tokens`, *and* the whole who-talks-to-whom graph. + The code fix here (never select secrets, name the columns) stops the + *egress*, not the *exposure* — hardening SQL is included as a commented block + at the end of `09_egress_optimizations.sql` because it needs a + `SECURITY DEFINER` helper before it can be switched on. + +Nothing here requires a rewrite. Items 1–3 are the ones worth doing now, while +there are 2–3 real users; item 8 is the one to read with a security hat on. + +--- + +## 7. Caching strategy — changed and recommended + +You said the cache can change freely. Current model, after this commit: + +| Layer | What it holds | Lifetime | Notes | +|---|---|---|---| +| `LocalDataCache` (memory + localStorage) | conversation list, per-chat messages, profile per user, follows | session, follows 5 min | the single source for the first paint — no spinner, no network | +| Browser HTTP cache | Storage objects (`photo_url`) | **1 year, immutable** | object names are unique, so a re-download is pure waste | +| Realtime | live patches only | — | patches state, never triggers a fetch | +| Full refetch | reconciliation | mount, focus, structural change, 1.2 s debounce | 1 round trip, 41 KB measured, never per message | + +Recommended next (not in this commit): + +- **Image transformations** (`/render/image/...?width=300&quality=75`) for + avatars and thumbnails, so the device downloads a 12 KB image instead of the + full-size original. Note: billed as Storage egress only on paid plans — + check before relying on it. +- **A `unread_count` column** maintained by trigger if you want exact badges + without the client counting from cache. +- **`get_unread_counts()`** (in the SQL file) if you prefer exact server counts. +- **Message pagination is already 20/page** — keep it that way; never "load all". + +--- + +## 8. How to keep it fixed + +1. **The rule:** a Realtime event may patch state. It may **never** trigger a + list-wide query. (Recorded in `AGENTS.md`.) +2. **Watch the ratio**, not the bytes: Supabase → Reports → Egress, and + Database → Query Performance. A jump means someone reintroduced a refetch. +3. **The regression tests** — both are in the suite and both fail if the old + shape returns: + - `src/__tests__/egressBudget.test.ts` — the conversation list query stays + under budget, selects six user columns, and carries **zero** message rows. + - `src/__tests__/egressRealtime.test.tsx` — an incoming Realtime message + patches the visible list with **zero** `conversations` / + `conversation_participants` queries. +4. **Every list query gets a `limit`.** No exceptions. +5. **No `select('*')`** outside your own profile — and never `users(*)` for + other people. +6. **Cardinality check before adding a listener:** does this event fire once per + user action, or once per *row*? Read receipts were the latter. diff --git a/docs/KNOWN_ISSUES.md b/docs/KNOWN_ISSUES.md index 1ab0526..42f2764 100644 --- a/docs/KNOWN_ISSUES.md +++ b/docs/KNOWN_ISSUES.md @@ -25,6 +25,8 @@ dashboard, Supabase, or a decision. | C | Confirm the Pages build settings: build command `npm run build`, output `dist`, root `/`; production branch = your main branch; custom domain `grixchat.gothwadtech.com` attached | Cloudflare → the project's Settings / Custom domains | `wrangler.toml` pins the output dir and compatibility date, but the dashboard values win. | | D | Decide the fate of `call_candidates` (issue 7) | Supabase SQL editor | It is defined but unused. Drop it with:
`DROP TABLE IF EXISTS public.call_candidates CASCADE;`
or keep it and adopt the table-based signalling in `db/3_webrtc_signaling_architecture.md`. | | E | Add a **Cloudflare Rate Limiting Rule** on `/api/*` (optional, but recommended before scaling) | Cloudflare → Security → WAF | The limiter in `server/api.ts` counts in memory, i.e. per isolate — a speed bump, not a hard global quota. | +| F | Run **`sql/09_egress_optimizations.sql`** (2 minutes, idempotent, ends with a self-check) | Supabase → SQL Editor | Read receipts become one row instead of one per unread message, the chat-list preview is maintained by a trigger, `REPLICA IDENTITY` stops shipping whole rows + the passcode hash, and the missing RLS UPDATE policy on `conversation_participants` gets created. Full analysis: [EGRESS_AUDIT.md](./EGRESS_AUDIT.md). | +| G | Decide whether to enable the **RLS hardening** block at the end of that same file (commented out) | Supabase → SQL Editor | Today `users` and `conversation_participants` are readable by every authenticated account: `email`, `phone`, `lock` (passcode hash), `fcm_tokens`, and the whole follow/participant graph. | Optional: set `ALLOWED_ORIGINS=https://your-domain.tld,https://your-other.tld` (comma-separated) to extend the CORS/origin allowlist beyond same-origin + @@ -226,6 +228,27 @@ a call, so `drop` rightly leaves it alone. --- +## 🟠 P0 — Egress (fixed in code; SQL is a 2-minute step) + +### 19. 5 GB of Supabase egress in a month with 2–3 users — ✅ FIXED in code, 🧑 needs one SQL run + +Every realtime event (each message *and* each individual read receipt) made each +open client re-download its **entire conversation list**: 6 queries, ~127 KB +measured, no debounce, `users(*)` per participant, plus a separate query for the +newest message rows in all chats. ~178 MB/day ≈ 5.3 GB/month, which is exactly +what the dashboard showed. + +- **In code:** the list is patched from the Realtime payload (0 bytes per + message), one channel instead of one per chat, one round trip, narrow + columns, cached follows, read-receipt writes collapsed into one row, and + photos are downscaled + cached for a year. Regression tests: + `src/__tests__/egressBudget.test.ts`, `src/__tests__/egressRealtime.test.tsx`. +- **Needs you:** run `sql/09_egress_optimizations.sql` (row F above). +- **Analysis, measurements, database-foundation mistakes, caching plan:** + [EGRESS_AUDIT.md](./EGRESS_AUDIT.md). + +--- + ## 🟢 P3 — Quality ### 15. 470 `any` usages — ❌ STILL OPEN @@ -301,3 +324,4 @@ with it: | Pages base path, no CI typecheck/test, env not wired | **#9, #10, #11 — this pass** | | 1.14 MB entry chunk, eager emoji picker, console in prod | **#12, #13, #14 — this pass** | | Stale Reels leftovers in a live screen | **#18 — this pass** | +| 5 GB/month of egress from per-event list refetches | **#19 — this pass; SQL hand-off in row F** | diff --git a/sql/09_egress_optimizations.sql b/sql/09_egress_optimizations.sql new file mode 100644 index 0000000..bb7981d --- /dev/null +++ b/sql/09_egress_optimizations.sql @@ -0,0 +1,369 @@ +-- ═══════════════════════════════════════════════════════════════════════════ +-- 09 — Egress optimizations +-- +-- Apply this in the Supabase SQL editor: Database → SQL Editor → New query. +-- It is idempotent, so running it twice is safe. +-- +-- Why: the app consumed 5 GB of egress in under a month with 2–3 active users. +-- The client-side cause (a full conversation-list refetch per realtime event) +-- is fixed in code — see docs/EGRESS_AUDIT.md. This file fixes the database +-- half, which cannot be changed from the repository: +-- +-- 1. `last_read_at` — read receipts become ONE row update instead of one per +-- unread message (each of which was broadcast to every client). +-- 2. Denormalized `last_message*` maintained by trigger, so the chat list +-- never has to fetch message rows just to draw a one-line preview. +-- 3. REPLICA IDENTITY: stop broadcasting whole rows (including the passcode +-- hash and FCM tokens in `users`) on every UPDATE. +-- 4. Indexes for the hot paths. +-- 5. Optional retention pruner for old messages. +-- ═══════════════════════════════════════════════════════════════════════════ + + +-- ── 1. Read marker ───────────────────────────────────────────────────────── +-- Unread is a comparison: conversations.last_message_at > my last_read_at. +-- One UPDATE per "I opened/read this chat" instead of one row per message. + +-- Existing rows are stamped with the moment this runs, so history starts +-- "read" and nobody gets a fake 400-message unread badge. +ALTER TABLE public.conversation_participants + ADD COLUMN IF NOT EXISTS last_read_at TIMESTAMPTZ DEFAULT NOW(); + +-- The client updates ITS OWN row to say "I have read up to here". Without this +-- policy the UPDATE matches no policy, affects 0 rows, and returns no error — +-- the read marker would silently never move. (RLS is on for this table, and +-- 01_core_schema.sql only defined SELECT/INSERT/DELETE.) +DROP POLICY IF EXISTS "Participants can update their own membership" ON public.conversation_participants; +CREATE POLICY "Participants can update their own membership" + ON public.conversation_participants + FOR UPDATE + USING (user_id = auth.uid()) + WITH CHECK (user_id = auth.uid()); + +CREATE INDEX IF NOT EXISTS idx_participants_user_last_read + ON public.conversation_participants(user_id, last_read_at DESC); + +-- Realtime: the client subscribes with `user_id=eq.` and must also receive +-- DELETEs (a participant removed from a group). DEFAULT identity only carries +-- the primary key in the `old` record, so the server cannot evaluate the filter +-- for deletes. These rows are tiny and rarely written, so FULL is cheap here. +ALTER TABLE public.conversation_participants REPLICA IDENTITY FULL; + + +-- ── 2. `last_message*` is maintained by the database ─────────────────────── +-- The chat list shows `last_message` / `last_message_at` / (for ticks) the +-- sender. Writers already set the first two; the trigger also covers edits, +-- deletes and direct SQL inserts, so the client never needs to re-read the +-- newest messages for every conversation. + +ALTER TABLE public.conversations + ADD COLUMN IF NOT EXISTS last_message_sender_id UUID; + +CREATE OR REPLACE FUNCTION public.sync_conversation_last_message() +RETURNS TRIGGER +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = public +AS $$ +DECLARE + target_conversation UUID; + newest RECORD; +BEGIN + target_conversation := COALESCE(NEW.conversation_id, OLD.conversation_id); + IF target_conversation IS NULL THEN + RETURN NULL; + END IF; + + -- Fast path: a new (or edited) message that is not older than what the + -- conversation already shows IS the newest one, so write it across without + -- looking at the table. Appends are the hot path: no extra index scan. + IF TG_OP <> 'DELETE' AND NEW.is_deleted = false THEN + UPDATE public.conversations + SET last_message = COALESCE(NEW.text, + 'Sent a ' || COALESCE(NEW.media_type, 'file')), + last_message_at = NEW.created_at, + last_message_sender_id = NEW.sender_id + WHERE id = target_conversation + AND (last_message_at IS NULL OR NEW.created_at >= last_message_at); + IF FOUND THEN + RETURN NULL; + END IF; + END IF; + + -- Slow path: a delete, a soft delete, or an edit of an older message. The + -- preview has to be re-derived from what is left. + SELECT m.text, m.media_type, m.created_at, m.sender_id, m.is_deleted + INTO newest + FROM public.messages m + WHERE m.conversation_id = target_conversation + AND m.is_deleted = false + ORDER BY m.created_at DESC + LIMIT 1; + + IF NOT FOUND THEN + UPDATE public.conversations + SET last_message = NULL, + last_message_at = NULL, + last_message_sender_id = NULL + WHERE id = target_conversation; + ELSE + UPDATE public.conversations + SET last_message = COALESCE(newest.text, + 'Sent a ' || COALESCE(newest.media_type, 'file')), + last_message_at = newest.created_at, + last_message_sender_id = newest.sender_id + WHERE id = target_conversation; + END IF; + + RETURN NULL; +END; +$$; + +DROP TRIGGER IF EXISTS trg_sync_conversation_last_message ON public.messages; +CREATE TRIGGER trg_sync_conversation_last_message + AFTER INSERT OR UPDATE OF text, media_type, is_deleted OR DELETE + ON public.messages + FOR EACH ROW + EXECUTE FUNCTION public.sync_conversation_last_message(); + +-- The fast path above needs no lookup at all; only edits/deletes of older +-- messages touch the index below, and they resolve it in one index scan. + +CREATE INDEX IF NOT EXISTS idx_messages_conv_created + ON public.messages(conversation_id, created_at DESC); + +CREATE INDEX IF NOT EXISTS idx_conversations_last_message_at + ON public.conversations(last_message_at DESC NULLS LAST); + +-- Legacy path only (used until the client detects `last_read_at`). +CREATE INDEX IF NOT EXISTS idx_messages_unread + ON public.messages(conversation_id) + WHERE is_read = false; + + +-- ── 3. Stop broadcasting whole rows on UPDATE ────────────────────────────── +-- `REPLICA IDENTITY FULL` makes every UPDATE emit the complete OLD row and the +-- complete NEW row to every subscribed client. On `users` that payload includes +-- `settings`, `lock` (passcode hash!) and `fcm_tokens`. DEFAULT sends the new +-- row plus the primary key only — smaller, and no private columns on the wire. +-- +-- `messages` is deliberately NOT in this list. `useChatMessages` listens for +-- DELETE events with a `conversation_id=eq.…` filter, and the filter column is +-- only present in the `old` record when the identity is FULL — with DEFAULT the +-- event cannot be matched and "delete for everyone" would stop propagating. +-- The read-marker change (section 1) is what removes messages UPDATE traffic; +-- deletes are rare, so FULL stays there. +-- +-- `conversations`, `users` and `calls` are only ever read via `payload.new` on +-- the client (and a conversation DELETE also removes its participant rows, which +-- ARE FULL), so DEFAULT is safe for them. Calls are status-UPDATEd, never +-- deleted (`CallProvider` zombie sweep). The pair of `FULL` entries re-asserts +-- the two tables whose filtered DELETEs the client depends on, so this file +-- leaves the database correct no matter which earlier scripts were applied. + +DO $$ +DECLARE + target RECORD; +BEGIN + FOR target IN + SELECT * FROM (VALUES + ('users', 'DEFAULT'), + ('conversations', 'DEFAULT'), + ('calls', 'DEFAULT'), + ('messages', 'FULL'), + ('conversation_participants','FULL') + ) AS t(tbl, identity) + LOOP + IF EXISTS (SELECT 1 FROM pg_class c + JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname = target.tbl) THEN + EXECUTE format('ALTER TABLE public.%I REPLICA IDENTITY %s', + target.tbl, target.identity); + END IF; + END LOOP; +END; +$$; + + +-- Advanced (optional, experimental): if messages UPDATE payloads ever matter +-- again, `ALTER TABLE public.messages REPLICA IDENTITY USING INDEX +-- messages_id_conversation_id_key;` (with a UNIQUE index on (id, +-- conversation_id)) makes the `old` record carry just those two columns. Verify +-- in the Realtime inspector that DELETE events still arrive before relying on +-- it. + +-- ── 4. Unread counts without a per-message scan (optional, recommended) ──── +-- Call: supabase.rpc('get_unread_counts') +-- Returns one row per conversation with a badge, instead of one row per unread +-- message. `last_read_at` already removes the need; this is exact and cheap. + +CREATE OR REPLACE FUNCTION public.get_unread_counts() +RETURNS TABLE (conversation_id UUID, unread_count BIGINT) +LANGUAGE sql +STABLE +SECURITY DEFINER +SET search_path = public +AS $$ + SELECT m.conversation_id, COUNT(*) AS unread_count + FROM public.messages m + JOIN public.conversation_participants cp + ON cp.conversation_id = m.conversation_id + AND cp.user_id = auth.uid() + WHERE m.sender_id <> auth.uid() + AND m.is_deleted = false + AND (cp.last_read_at IS NULL OR m.created_at > cp.last_read_at) + GROUP BY m.conversation_id; +$$; + +GRANT EXECUTE ON FUNCTION public.get_unread_counts() TO authenticated; + + +-- ── 5. Retention (run when you want it — nothing calls it automatically) ─── +-- Egress is paid on read, not on storage, but a smaller table keeps the +-- unread/latest queries from degrading. Deletes soft-deleted rows and anything +-- older than `keep_days` for conversations that are inactive. + +CREATE OR REPLACE FUNCTION public.prune_old_messages(keep_days INTEGER DEFAULT 90) +RETURNS INTEGER +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = public +AS $$ +DECLARE + removed INTEGER := 0; + affected UUID[]; +BEGIN + SELECT array_agg(DISTINCT conversation_id) INTO affected + FROM ( + SELECT m.conversation_id + FROM public.messages m + JOIN public.conversations c ON c.id = m.conversation_id + WHERE m.created_at < NOW() - make_interval(days => keep_days) + AND c.updated_at < NOW() - make_interval(days => keep_days) + ORDER BY m.created_at + LIMIT 5000 + ) t; + + IF affected IS NULL THEN + RETURN 0; + END IF; + + -- The per-row last_message trigger would fire once per deleted row (5000 + -- index scans); the last_message of these inactive conversations is + -- recomputed in one pass below instead. DDL is transactional, so this rolls + -- back with the function if anything fails. + BEGIN + ALTER TABLE public.messages DISABLE TRIGGER trg_sync_conversation_last_message; + EXCEPTION WHEN OTHERS THEN + NULL; -- not the table owner; the trigger just stays on + END; + + DELETE FROM public.messages m + USING ( + SELECT m2.id + FROM public.messages m2 + JOIN public.conversations c ON c.id = m2.conversation_id + WHERE m2.created_at < NOW() - make_interval(days => keep_days) + AND c.updated_at < NOW() - make_interval(days => keep_days) + ORDER BY m2.created_at + LIMIT 5000 + ) stale + WHERE m.id = stale.id; + + GET DIAGNOSTICS removed = ROW_COUNT; + + BEGIN + ALTER TABLE public.messages ENABLE TRIGGER trg_sync_conversation_last_message; + EXCEPTION WHEN OTHERS THEN + NULL; + END; + + UPDATE public.conversations c + SET last_message = x.text, + last_message_at = x.created_at, + last_message_sender_id = x.sender_id + FROM ( + SELECT DISTINCT ON (m.conversation_id) + m.conversation_id, m.text, m.created_at, m.sender_id + FROM public.messages m + WHERE m.conversation_id = ANY(affected) + AND m.is_deleted = false + ORDER BY m.conversation_id, m.created_at DESC + ) x + WHERE c.id = x.conversation_id; + + RETURN removed; +END; +$$; + +-- Example: keep the last 90 days. +-- SELECT public.prune_old_messages(90); +-- Scheduled (needs the pg_cron extension enabled in Dashboard → Database → +-- Extensions): +-- SELECT cron.schedule('prune-messages', '0 4 * * *', $$SELECT public.prune_old_messages(90)$$); + + +-- ── 5b. Optional hardening (commented out — read before enabling) ────────── +-- `conversation_participants` is readable by EVERY authenticated user +-- (`FOR SELECT USING (true)`), which leaks who-talks-to-whom, and `users` is +-- readable the same way, which leaks `email`, `phone`, `lock` (passcode hash!) +-- and `fcm_tokens` of every account. Neither is an egress bug, but both are +-- foundation mistakes worth closing. The membership check below needs a +-- SECURITY DEFINER helper: a policy on the table cannot query the same table +-- (Postgres raises "infinite recursion detected in policy"). +-- +-- CREATE OR REPLACE FUNCTION public.is_conversation_member(conv UUID, uid UUID) +-- RETURNS BOOLEAN LANGUAGE sql STABLE SECURITY DEFINER SET search_path = public +-- AS $$ SELECT EXISTS (SELECT 1 FROM public.conversation_participants +-- WHERE conversation_id = conv AND user_id = uid); $$; +-- +-- DROP POLICY IF EXISTS "Allow auth users to inspect participants" +-- ON public.conversation_participants; +-- CREATE POLICY "Members can inspect their conversations' participants" +-- ON public.conversation_participants FOR SELECT +-- USING (public.is_conversation_member(conversation_id, auth.uid())); +-- +-- DROP POLICY IF EXISTS "Allow public read access on profiles" ON public.users; +-- CREATE POLICY "Profiles are readable, secrets are not" ON public.users +-- FOR SELECT USING (true); -- plus a view/column grants, see +-- -- docs/EGRESS_AUDIT.md §6.4 + + +-- ── 6. Sanity check ──────────────────────────────────────────────────────── +-- Run this afterwards; every row should read like the expected value. +SELECT 'conversation_participants.last_read_at' AS what, + CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END AS state + FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'conversation_participants' + AND column_name = 'last_read_at' +UNION ALL +SELECT 'conversations.last_message_sender_id', + CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END + FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'conversations' + AND column_name = 'last_message_sender_id' +UNION ALL +SELECT 'replica identity: users', + COALESCE((SELECT CASE WHEN c.relreplident = 'f' THEN 'STILL FULL' ELSE 'OK (default)' END + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname = 'users'), 'MISSING') +UNION ALL +SELECT 'replica identity: conversations (expect default)', + COALESCE((SELECT CASE WHEN c.relreplident = 'f' THEN 'STILL FULL' ELSE 'OK (default)' END + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname = 'conversations'), 'MISSING') +UNION ALL +SELECT 'replica identity: messages (expect FULL)', + COALESCE((SELECT CASE WHEN c.relreplident = 'f' THEN 'OK (full)' ELSE 'CHANGED - deletes will stop reaching clients' END + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname = 'messages'), 'MISSING') +UNION ALL +SELECT 'sync trigger on messages', + CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END + FROM pg_trigger + WHERE tgname = 'trg_sync_conversation_last_message' +UNION ALL +SELECT 'UPDATE policy on conversation_participants', + CASE WHEN COUNT(*) FILTER (WHERE cmd = 'UPDATE') > 0 THEN 'OK' ELSE 'MISSING' END + FROM pg_policies + WHERE schemaname = 'public' AND tablename = 'conversation_participants'; diff --git a/src/__tests__/egressBudget.test.ts b/src/__tests__/egressBudget.test.ts new file mode 100644 index 0000000..b1105d4 --- /dev/null +++ b/src/__tests__/egressBudget.test.ts @@ -0,0 +1,176 @@ +/** + * Egress budget — the regression guard for the 5 GB/month bug. + * + * Background: docs/EGRESS_AUDIT.md. The conversation list used to be re-fetched + * on every realtime event (6 round-trips, ~127 KB measured) and pulled whole + * user rows plus 135 message rows. These tests fail if that shape comes back. + * + * @vitest-environment node + */ +import {beforeAll, describe, expect, it} from 'vitest'; +import {createClient} from '../../dev/mock/index'; +import {store} from '../../dev/mock/store'; +import {CONVERSATION_LIST_SELECT} from '../features/chat/hooks/useConversations'; + +const bytes = (v: unknown) => new TextEncoder().encode(JSON.stringify(v)).length; + +/** + * Budget for one conversation-list fetch, in bytes. + * Measured on the fixture below: 41 KB. The pre-fix path was 127 KB on the same + * data (plus 5 more round-trips), so this catches a regression to `users(*)` + * (+27 KB) or to fetching message rows for the preview (+37 KB). + */ +const FETCH_BUDGET = 48 * 1024; + +let supabase: any; +let myId = ''; + +let seeded = false; + +async function seedRealisticAccount() { + if (seeded) return; + seeded = true; + supabase = createClient('http://mock', 'key'); + await supabase.auth.signInWithPassword({email: 'demo@grixchat.app', password: 'grixchat'}); + myId = (await supabase.auth.getUser()).data.user.id; + + // A realistic account: 20 chats, 60 follow edges, 400 messages, users with + // the full private column set present (that is what makes `users(*)` heavy). + const users = store.table('users') as any[]; + const extra: any[] = []; + for (let i = 0; i < 40; i++) { + extra.push({ + id: `u0000000-0000-4000-8000-00000000${String(i).padStart(4, '0')}`, + email: `person${i}@grixchat.app`, + phone: `+9190000000${String(i).padStart(2, '0')}`, + full_name: `Person Number ${i}`, + username: `person_${i}`, + photo_url: 'https://cdn-icons-png.flaticon.com/512/149/149071.png', + bio: 'Available', + is_verified: false, + profile_type: 'personal', + is_online: i % 3 === 0, + last_seen: new Date().toISOString(), + updated_at: new Date().toISOString(), + created_at: new Date().toISOString(), + settings: {theme: 'dark', notifications: true, wallpaper: 'default', font_size: 14}, + lock: {enabled: true, pin_hash: 'x'.repeat(64)}, + blocked_users: [], + muted_users: [], + favorites: [], + hidden_chats: [], + archived_chats: [], + hidden_chat_settings: {secretCode: null, showMenuEntry: true}, + fcm_tokens: ['token-a', 'token-b'], + }); + } + store.setTable('users', [...users, ...extra]); + + const follows: any[] = []; + for (let i = 0; i < 30; i++) { + follows.push({id: `f1${i}`, follower_id: myId, following_id: extra[i].id, created_at: new Date().toISOString()}); + follows.push({id: `f2${i}`, follower_id: extra[i].id, following_id: myId, created_at: new Date().toISOString()}); + } + store.setTable('follows', follows); + + const convs: any[] = []; + const parts: any[] = []; + const msgs: any[] = []; + let m = 0; + for (let i = 0; i < 20; i++) { + const cid = `c0000000-0000-4000-8000-0000000000${String(i).padStart(2, '0')}`; + const other = extra[i]; + convs.push({ + id: cid, type: 'direct', name: null, photo_url: null, + last_message: 'Theek hai, kal baat karte hain', + last_message_at: new Date(Date.now() - i * 60_000).toISOString(), + updated_at: new Date(Date.now() - i * 60_000).toISOString(), + created_at: new Date().toISOString(), + }); + parts.push({id: `p1${i}`, conversation_id: cid, user_id: myId, last_read_at: new Date().toISOString(), created_at: new Date().toISOString(), joined_at: new Date().toISOString()}); + parts.push({id: `p2${i}`, conversation_id: cid, user_id: other.id, last_read_at: new Date().toISOString(), created_at: new Date().toISOString(), joined_at: new Date().toISOString()}); + for (let j = 0; j < 20; j++) { + msgs.push({ + id: `m${String(m++).padStart(35, '0')}`, + conversation_id: cid, + sender_id: j % 2 === 1 ? other.id : myId, + text: 'Arre yaar, ye message thoda lamba hai taaki payload realistic lage — chalo plan karte hain', + media_url: null, media_type: null, reply_to: null, reactions: {}, + is_read: true, is_edited: false, is_deleted: false, deleted_by: [], + created_at: new Date(Date.now() - i * 3_600_000 - j * 60_000).toISOString(), + }); + } + } + store.setTable('conversations', [...(store.table('conversations') as any[]), ...convs]); + store.setTable('conversation_participants', [...(store.table('conversation_participants') as any[]), ...parts]); + store.setTable('messages', [...(store.table('messages') as any[]), ...msgs]); +} + +/** Reads the exact query the hook runs, on the realistic fixture. */ +async function fetchConversationList() { + await seedRealisticAccount(); + return supabase + .from('conversation_participants') + .select(CONVERSATION_LIST_SELECT) + .eq('user_id', myId); +} + +describe('conversation-list egress budget', () => { + it('fetches the list in one query, under budget', async () => { + const t0 = Date.now(); + const {data, error} = await fetchConversationList(); + const elapsed = Date.now() - t0; + + expect(error).toBeFalsy(); + expect((data || []).length).toBeGreaterThanOrEqual(20); + + const size = bytes(data); + // eslint-disable-next-line no-console + console.log(`[egress] conversation list: ${(size / 1024).toFixed(1)} KB in ${elapsed} ms (budget ${FETCH_BUDGET / 1024} KB)`); + expect(size).toBeLessThan(FETCH_BUDGET); + }); + + it('never selects private user columns for other people', async () => { + const {data} = await fetchConversationList(); + + const userRows = (data || []).flatMap((r: any) => (r.conversation?.participants || []).map((p: any) => p.user)).filter(Boolean); + expect(userRows.length).toBeGreaterThan(0); + + for (const user of userRows) { + // The passcode hash, FCM tokens and private settings must never be part + // of a list payload. + expect(user).not.toHaveProperty('lock'); + expect(user).not.toHaveProperty('settings'); + expect(user).not.toHaveProperty('fcm_tokens'); + expect(user).not.toHaveProperty('blocked_users'); + expect(user).not.toHaveProperty('email'); + expect(Object.keys(user).sort()).toEqual( + ['full_name', 'id', 'is_online', 'last_seen', 'photo_url', 'username'].sort() + ); + } + }); + + it('carries no message rows — the preview comes from conversations.last_message', async () => { + const {data} = await fetchConversationList(); + + const conversation = (data || [])[0]?.conversation; + expect(conversation).toBeTruthy(); + expect(conversation.last_message).toBeTruthy(); + expect(conversation).not.toHaveProperty('messages'); + // No row in the payload may contain a message body array. + const serialized = JSON.stringify(data); + expect(serialized).not.toContain('"text":'); + }); + + it('the hook no longer selects * from users', async () => { + const fs = await import('node:fs'); + const raw = fs.readFileSync(new URL('../features/chat/hooks/useConversations.ts', import.meta.url), 'utf8'); + // Strip comments so the prose that explains the rule does not trip it. + const code = raw + .split('\n') + .filter((line) => !line.trim().startsWith('//') && !line.trim().startsWith('*')) + .join('\n'); + expect(code).not.toMatch(/users\s*\(\s*\*\s*\)/); + expect(CONVERSATION_LIST_SELECT).not.toMatch(/users\s*\(\s*\*\s*\)/); + }); +}); diff --git a/src/__tests__/egressRealtime.test.tsx b/src/__tests__/egressRealtime.test.tsx new file mode 100644 index 0000000..b060884 --- /dev/null +++ b/src/__tests__/egressRealtime.test.tsx @@ -0,0 +1,98 @@ +/** + * The regression test for the 5 GB/month bug (docs/EGRESS_AUDIT.md). + * + * Mounts the real , lands on the chat list, then delivers an incoming + * message exactly the way Supabase Realtime would. The list must update — and + * the client must not issue a single database query to do it. + * + * Before this fix, every message triggered `fetchConversations()`: 6 queries + * and ~127 KB per client, per message. + */ +import {render, screen, waitFor} from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import {describe, expect, it} from 'vitest'; +import {MemoryRouter} from 'react-router-dom'; +import App from '../App'; +import {AppProviders} from '../providers/AppProviders'; +import {getSupabase} from '../lib/supabase'; +import {store} from '../../dev/mock/store'; + +async function loginToChatList() { + const user = userEvent.setup(); + render( + + + + + , + ); + + await waitFor(() => screen.getByPlaceholderText(/Email, Phone or Username/i), {timeout: 8000}); + await user.type(screen.getByPlaceholderText(/Email, Phone or Username/i), 'demo@grixchat.app'); + await user.type(screen.getByPlaceholderText('Password'), 'grixchat'); + + const form = screen.getByPlaceholderText('Password').closest('form') as HTMLFormElement; + const submit = form.querySelector('button[type="submit"]') as HTMLButtonElement; + await waitFor(() => expect(submit).not.toBeDisabled(), {timeout: 5000}); + await user.click(submit); + + await waitFor(() => expect(screen.getByText(/mock data ready/i)).toBeInTheDocument(), {timeout: 15000}); +} + +describe('realtime traffic does not refetch the conversation list', () => { + it('patches the row from the payload instead of querying the database', async () => { + await loginToChatList(); + + const client: any = getSupabase(); + expect(client).toBeTruthy(); + + // Count every query the app makes from now on. + const queriedTables: string[] = []; + const originalFrom = client.from.bind(client); + client.from = (table: string, ...rest: any[]) => { + queriedTables.push(table); + return originalFrom(table, ...rest); + }; + + try { + // An incoming message in a chat the demo user is part of. + const conversation = (store.table('conversations') as any[]).find( + (c) => c.last_message === 'Bhai mock data ready hai, check kar le 👍', + ); + expect(conversation).toBeTruthy(); + + const otherUser = (store.table('users') as any[]).find((u) => u.username !== 'aryan_v'); + const row = { + id: `m-egress-${Date.now()}`, + conversation_id: conversation.id, + sender_id: otherUser.id, + text: 'EGRESS PATCH CHECK', + media_url: null, + media_type: null, + reply_to: null, + reactions: {}, + is_read: false, + is_edited: false, + is_deleted: false, + deleted_by: [], + created_at: new Date().toISOString(), + }; + + // Same path a real INSERT takes: write, then broadcast. + store.setTable('messages', [...(store.table('messages') as any[]), row]); + store.emit('INSERT', 'messages', row); + + // The preview updates… + await waitFor(() => expect(screen.getAllByText(/EGRESS PATCH CHECK/i).length).toBeGreaterThan(0), {timeout: 5000}); + + // …without a single query. (The chat screen may fetch its own message + // list; the *conversation list* must not.) + const listRefetches = queriedTables.filter( + (t) => t === 'conversation_participants' || t === 'conversations' || t === 'follows' || t === 'chat_settings', + ); + expect(listRefetches).toEqual([]); + } finally { + client.from = originalFrom; + } + }, 30000); +}); diff --git a/src/components/layout/TabBottom.tsx b/src/components/layout/TabBottom.tsx index e8066bd..53c75c9 100644 --- a/src/components/layout/TabBottom.tsx +++ b/src/components/layout/TabBottom.tsx @@ -92,12 +92,15 @@ export default function TabBottom() { return; } + // Capped on purpose: this returns one row per unread message and grows + // with the backlog. docs/EGRESS_AUDIT.md → `last_read_at` replaces it. const { data: messages, error: mError } = await supabase .from('messages') .select('conversation_id') .eq('is_read', false) .neq('sender_id', authUser.id) - .in('conversation_id', myConvIds); + .in('conversation_id', myConvIds) + .limit(500); if (!mError && messages) { const distinctConversations = Array.from(new Set(messages.map(m => m.conversation_id as string))); diff --git a/src/features/chat/hooks/useChatMessages.ts b/src/features/chat/hooks/useChatMessages.ts index 214b2cc..a2cfabb 100644 --- a/src/features/chat/hooks/useChatMessages.ts +++ b/src/features/chat/hooks/useChatMessages.ts @@ -3,6 +3,17 @@ import { supabase } from '../../../lib/supabase'; import { useAuth } from '../../../providers/AuthProvider.tsx'; import { LocalDataCache } from '../../../services/LocalDataCache'; +/** + * Does `conversation_participants.last_read_at` exist yet? + * `null` = untested. Read receipts used to UPDATE one row per unread message; + * with REPLICA IDENTITY FULL each of those rows was broadcast as a full + * old+new payload *and* triggered a conversation-list refetch in every client. + * One marker row replaces all of it — with a fallback until + * sql/09_egress_optimizations.sql is applied. See docs/EGRESS_AUDIT.md. + */ +let readMarkerSupported: boolean | null = null; +const readMarkerKey = (conversationId: string) => `read_at_${conversationId}`; + export const useChatMessages = (conversationId: string, initialLimit: number = 20) => { const [messages, setMessages] = useState(() => { if (conversationId) { @@ -232,18 +243,49 @@ export const useChatMessages = (conversationId: string, initialLimit: number = 2 } const executeUpdate = async () => { + const now = new Date().toISOString(); + + // Preferred path: move ONE row — this participant's read marker. Every + // other client derives "unread" by comparing it with + // `conversations.last_message_at`, so a read receipt is a single realtime + // event instead of one per unread message. + if (readMarkerSupported !== false) { + try { + const { error } = await supabase + .from('conversation_participants') + .update({ last_read_at: now } as any) + .eq('conversation_id', conversationId) + .eq('user_id', user.id); + + if (!error) { + readMarkerSupported = true; + LocalDataCache.set(readMarkerKey(conversationId), now); + return; + } + // Column not there yet — remember and fall back for this session. + readMarkerSupported = false; + } catch (err) { + readMarkerSupported = false; + } + } + + // Legacy path: mark the message rows. Bounded to messages newer than the + // last marker so re-opening a chat never rewrites its whole history. try { - const { error } = await supabase + const since = LocalDataCache.get(readMarkerKey(conversationId)); + let query: any = supabase .from('messages') .update({ is_read: true } as any) .eq('conversation_id', conversationId) .neq('sender_id', user.id) .eq('is_read', false); - + if (since) query = query.gt('created_at', since); + + const { error } = await query; if (error) { console.error('Error marking messages as read:', error); } else { - console.log('Successfully marked messages as read for conv (debounced):', conversationId); + LocalDataCache.set(readMarkerKey(conversationId), now); } } catch (err) { console.error('Failed to mark messages as read:', err); diff --git a/src/features/chat/hooks/useConversations.ts b/src/features/chat/hooks/useConversations.ts index a468d99..4a9d74d 100644 --- a/src/features/chat/hooks/useConversations.ts +++ b/src/features/chat/hooks/useConversations.ts @@ -4,6 +4,97 @@ import { useAuth } from '../../../providers/AuthProvider.tsx'; import { LocalDataCache } from '../../../services/LocalDataCache'; import { isUserOnline } from '../../../utils/presence'; +// ───────────────────────────────────────────────────────────────────────────── +// Egress guards +// +// A conversation-list refresh is 6 round-trips and ~25–130 KB (measured, see +// docs/EGRESS_AUDIT.md). It used to run on EVERY realtime event — one per +// message and one per row of every read receipt — which is what filled the +// Supabase egress quota. It now runs on mount, on focus and on *structural* +// changes only; message traffic patches the list in place from the realtime +// payload, with no network call at all. +// ───────────────────────────────────────────────────────────────────────────── + +/** Follows only change when someone follows/unfollows; cache them. */ +const FOLLOWS_TTL_MS = 5 * 60 * 1000; +/** Coalesce bursts of structural events (new chat, participant added) into one refresh. */ +const STRUCTURAL_DEBOUNCE_MS = 1200; +/** `conversation_id=in.(…)` filter length cap — beyond this, rely on focus refreshes. */ +const REALTIME_IN_FILTER_LIMIT = 60; + +/** + * Does `conversation_participants.last_read_at` exist yet? + * `null` = untested. Until sql/09_egress_optimizations.sql is applied we fall + * back to the legacy `messages.is_read` scan, so the app works either way. + */ +let participantsSupportReadMarker: boolean | null = null; + +const followsCacheKey = (myId: string) => `follows_v1_${myId}`; + +/** + * The conversation-list query. + * + * Exported so `src/__tests__/egressBudget.test.ts` can measure exactly what + * ships over the wire. Rules this string encodes (docs/EGRESS_AUDIT.md): + * - never `users(*)` — the list renders six columns, not settings/lock/tokens + * - never fetch message rows — `conversations.last_message*` is authoritative + * - one embedded select = one round trip + */ +export const CONVERSATION_LIST_SELECT = ` + conversation_id, + last_read_at, + conversation:conversations ( + id, type, name, photo_url, last_message, last_message_at, updated_at, created_at, + participants:conversation_participants ( + user_id, last_read_at, + user:users (id, username, full_name, photo_url, is_online, last_seen) + ) + ) +`; + +async function getMutualFriends(myId: string): Promise> { + const key = followsCacheKey(myId); + const cached = LocalDataCache.get<{ at: number; rows: any[] }>(key); + if (cached && cached.rows && Date.now() - (cached.at || 0) < FOLLOWS_TTL_MS) { + return buildMutualSet(cached.rows, myId); + } + if (!supabase) return new Set(); + const { data } = await supabase + .from('follows') + .select('follower_id, following_id') + .or(`follower_id.eq.${myId},following_id.eq.${myId}`); + LocalDataCache.set(key, { at: Date.now(), rows: data || [] }); + return buildMutualSet(data || [], myId); +} + +function invalidateFollows(myId: string) { + LocalDataCache.set(followsCacheKey(myId), { at: 0, rows: [] }); +} + +/** The chat list shows a one-line preview — strip the forward markers. */ +function cleanPreview(text: string): string { + if (typeof text !== 'string') return ''; + if (text.startsWith('\u200B[FWD_MANY]\u200B')) { + return '↪ Forwarded many times: ' + text.replace('\u200B[FWD_MANY]\u200B', ''); + } + if (text.startsWith('\u200B[FWD]\u200B')) { + return '↪ Forwarded: ' + text.replace('\u200B[FWD]\u200B', ''); + } + return text; +} + +function buildMutualSet(rows: any[], myId: string): Set { + const iFollow = new Set(); + const followsMe = new Set(); + (rows || []).forEach((row: any) => { + if (row.follower_id === myId) iFollow.add(row.following_id); + if (row.following_id === myId) followsMe.add(row.follower_id); + }); + const mutual = new Set(); + iFollow.forEach((id) => { if (followsMe.has(id)) mutual.add(id); }); + return mutual; +} + export const useConversations = (activeFilter: string) => { const { user, isAuthReady, userData } = useAuth(); @@ -39,6 +130,15 @@ export const useConversations = (activeFilter: string) => { const chatChannelsRef = useRef([]); const subscribedIdsRef = useRef([]); + /** Keeps a synchronous copy of the list so realtime patches never race React state. */ + const listRef = useRef(conversations); + useEffect(() => { listRef.current = conversations; }, [conversations]); + + /** Only one refresh may be in flight; bursts collapse into it. */ + const inFlightRef = useRef(false); + const structuralTimerRef = useRef(null); + const refreshRef = useRef<(() => void) | null>(null); + const formatTime = useCallback((date: Date) => { const now = new Date(); const diff = now.getTime() - date.getTime(); @@ -50,229 +150,141 @@ export const useConversations = (activeFilter: string) => { const fetchConversations = useCallback(async () => { if (!user || activeFilter === 'Calls' || !supabase || !isAuthReady) return; + if (inFlightRef.current) return; // coalesce bursts into one request + inFlightRef.current = true; + const myId = user.id; const cached = LocalDataCache.getConversations(myId) || []; - - if (isPaginating) { - setLoadingMore(true); - } else if (limit === 15) { - if (!cached || cached.length === 0) { - setLoading(true); - } - } + if (cached.length === 0) setLoading(true); + + const SELECT_MODERN = CONVERSATION_LIST_SELECT; + const SELECT_LEGACY = ` + conversation_id, + conversation:conversations ( + id, type, name, photo_url, last_message, last_message_at, updated_at, created_at, + participants:conversation_participants ( + user_id, + user:users (id, username, full_name, photo_url, is_online, last_seen) + ) + ) + `; try { - // 1. Fetch all conversation IDs the user is part of - const { data: participations, error: pError } = await supabase - .from('conversation_participants') - .select('conversation_id') - .eq('user_id', myId); - - if (pError) { - console.error('Error fetching participant IDs:', pError); - return; - } - - const convIds = (participations || []).map(p => p.conversation_id); - if (convIds.length === 0) { - setConversations([]); - setHasMore(false); - setLoading(false); - setLoadingMore(false); - setIsPaginating(false); - return; - } - - // Delta synchronization strategy to bypass massive row scans and network payload limits - let maxUpdatedAt = '1970-01-01T00:00:00.000Z'; - cached.forEach((c: any) => { - const updateTime = c.lastMsgAt || c.updated_at || c.created_at; - if (updateTime && new Date(updateTime).getTime() > new Date(maxUpdatedAt).getTime()) { - maxUpdatedAt = updateTime; - } - }); + // ── 1. ONE round trip for the whole list ─────────────────────────────── + // `users(*)` used to bring 0.8 KB per participant (settings, the passcode + // hash, FCM tokens); the list renders six columns. + let rows: any[] | null = null; + let haveReadMarker = participantsSupportReadMarker !== false; + + if (participantsSupportReadMarker !== false) { + const { data, error } = await supabase + .from('conversation_participants') + .select(SELECT_MODERN) + .eq('user_id', myId); - // Offset checkTimestamp by 10s to satisfy active clock drift in Supabase containers - const checkTimestamp = new Date(new Date(maxUpdatedAt).getTime() - 10000).toISOString(); - let changedConvIds: string[] = []; - let isDelta = cached && cached.length > 0 && !isPaginating; - - if (isDelta) { - const { data: updatedConvs, error: uError } = await supabase - .from('conversations') - .select('id') - .in('id', convIds) - .gt('updated_at', checkTimestamp); - - if (!uError && updatedConvs) { - changedConvIds = updatedConvs.map(c => c.id); - } else if (uError) { - console.error('Error fetching delta updates:', uError); - isDelta = false; // Fallback to full sync + if (!error) { + rows = data as any[]; + participantsSupportReadMarker = true; + haveReadMarker = true; + } else { + // Column not there yet (sql/09_egress_optimizations.sql not applied). + participantsSupportReadMarker = false; + haveReadMarker = false; } } - // If it's delta-sync and NO conversations have updated, complete instantly! - if (isDelta && changedConvIds.length === 0) { - console.log('[Delta Sync] Zero conversation changes found. Serving instant cached chats.'); - setLoading(false); - setLoadingMore(false); - setIsPaginating(false); - return; - } - - const idsToQuery = isDelta ? changedConvIds : convIds; - - // 2. Fetch details for required conversations, ordering by newest activity (updated_at) primarily to ensure live updates bubble to the top - const { data: convData, error: cError } = await supabase - .from('conversations') - .select(` - *, - participants:conversation_participants ( - user:users (*) - ) - `) - .in('id', idsToQuery) - .order('updated_at', { ascending: false }) - .order('last_message_at', { ascending: false }) - .limit(isDelta ? changedConvIds.length : limit + 1); - - if (cError) { - console.error('Error fetching conversations details:', cError); - return; - } - - let hasMoreData = false; - let queryData = (convData || []).map(conv => ({ conversation: conv })); - if (!isDelta && queryData.length > limit) { - hasMoreData = true; - queryData = queryData.slice(0, limit); - } - if (!isDelta) { - setHasMore(hasMoreData); - } - - // Fetch missing hidden or archived chats so they are never lost from local state - const fetchedIds = new Set(queryData.map((item: any) => item.conversation?.id).filter(Boolean)); - const missingHiddenIds = (userData?.hiddenChats || []).filter((id: string) => !fetchedIds.has(id)); - const missingArchivedIds = (userData?.archivedChats || []).filter((id: string) => !fetchedIds.has(id)); - const allMissingIds = [...missingHiddenIds, ...missingArchivedIds]; - - if (allMissingIds.length > 0) { - const { data: missingData, error: missingError } = await supabase + if (rows === null) { + const { data, error } = await supabase .from('conversation_participants') - .select(` - conversation:conversations ( - *, - participants:conversation_participants ( - user:users (*) - ) - ) - `) - .eq('user_id', myId) - .in('conversation_id', allMissingIds); - - if (!missingError && missingData && missingData.length > 0) { - queryData = [...queryData, ...missingData]; + .select(SELECT_LEGACY) + .eq('user_id', myId); + if (error) { + console.error('Error fetching conversation list:', error); + return; } + rows = data as any[]; } - // Fetch mutual follows to filter out non-friends from direct chats - const { data: followRows } = await supabase - .from('follows') - .select('follower_id, following_id') - .or(`follower_id.eq.${myId},following_id.eq.${myId}`); + const queryData = (rows || []) + .filter((r: any) => r && r.conversation) + .map((r: any) => ({ participation: r, conversation: r.conversation })); - const IFollow = new Set(); - const FollowsMe = new Set(); + if (queryData.length === 0) { + LocalDataCache.saveConversations(myId, []); + setConversations([]); + setHasMore(false); + return; + } - followRows?.forEach((row: any) => { - if (row.follower_id === myId) { - IFollow.add(row.following_id); - } - if (row.following_id === myId) { - FollowsMe.add(row.follower_id); - } - }); + const conversationIds = queryData.map((item: any) => item.conversation.id); - const mutualFriendsSet = new Set(); - IFollow.forEach(id => { - if (FollowsMe.has(id)) { - mutualFriendsSet.add(id); - } - }); + // ── 2. Mutual friends — cached for 5 minutes ─────────────────────────── + const mutualFriendsSet = await getMutualFriends(myId); - const conversationIds = queryData.map((item: any) => item.conversation?.id).filter(Boolean); + // ── 3. Unread — a comparison, not a per-message scan ─────────────────── + const unreadMap: Record = {}; - // Fetch unread messages count for all my conversations at once - let unreadData: any[] = []; - if (conversationIds.length > 0) { + if (haveReadMarker) { + queryData.forEach(({ participation, conversation }: any) => { + const seenAt = participation?.last_read_at; + const lastAt = conversation.last_message_at || conversation.updated_at || conversation.created_at; + if (!lastAt) return; + if (seenAt && new Date(lastAt) <= new Date(seenAt)) return; + + // Exact count only when the messages are already on the device. + const cachedMsgs = LocalDataCache.getMessages(conversation.id) as any[] | null; + if (cachedMsgs && cachedMsgs.length > 0) { + const n = cachedMsgs.filter((m: any) => + m && m.sender_id !== myId && (!seenAt || new Date(m.created_at) > new Date(seenAt)) + ).length; + if (n > 0) unreadMap[conversation.id] = n; + } else { + unreadMap[conversation.id] = 1; + } + }); + } else if (conversationIds.length > 0) { + // Legacy path: one row per unread message. Capped — this query grows + // with the unread backlog, which is exactly what the read marker fixes. const { data: res } = await supabase .from('messages') .select('conversation_id') .eq('is_read', false) .neq('sender_id', myId) - .in('conversation_id', conversationIds); - unreadData = res || []; - } - - const unreadMap: Record = {}; - unreadData.forEach(m => { - unreadMap[m.conversation_id] = (unreadMap[m.conversation_id] || 0) + 1; - }); - - // Fetch the actual newest message from messages table for each conversation to prevent race conditions - const latestMessagesMap: Record = {}; - const hasMessagesInDb = new Set(); - - if (conversationIds.length > 0) { - const { data: latestMsgs } = await supabase - .from('messages') - .select('conversation_id, text, media_type, created_at, sender_id, deleted_by') .in('conversation_id', conversationIds) - .order('created_at', { ascending: false }) - .limit(Math.max(50, conversationIds.length * 5)); - - latestMsgs?.forEach((m: any) => { - hasMessagesInDb.add(m.conversation_id); - // Filter out if deleted by key-user (Delete for me) - if (Array.isArray(m.deleted_by) && m.deleted_by.includes(myId)) { - return; - } - if (!latestMessagesMap[m.conversation_id]) { - latestMessagesMap[m.conversation_id] = m; - } + .limit(500); + (res || []).forEach((m: any) => { + unreadMap[m.conversation_id] = (unreadMap[m.conversation_id] || 0) + 1; }); } - // Fetch custom chat settings (nickname, custom avatar) to override globally - let chatSettingsData: any[] = []; + // ── 4. Per-chat nickname/avatar overrides ────────────────────────────── + let settingsMap: Record = {}; try { const { data: cSettings } = await supabase .from('chat_settings') .select('receiver_id, nickname, custom_photo_url') .eq('user_id', myId); - chatSettingsData = cSettings || []; + (cSettings || []).forEach((s: any) => { + if (s.receiver_id) { + settingsMap[s.receiver_id] = { + nickname: s.nickname || undefined, + customPhotoUrl: s.custom_photo_url || undefined, + }; + } + }); } catch (settingsError) { - console.warn("Error fetching all chat_settings:", settingsError); + console.warn('Error fetching all chat_settings:', settingsError); } - const settingsMap: Record = {}; - chatSettingsData.forEach((s: any) => { - if (s.receiver_id) { - settingsMap[s.receiver_id] = { - nickname: s.nickname || undefined, - customPhotoUrl: s.custom_photo_url || undefined, - }; - } - }); - + // ── 5. Shape the list. `last_message*` is maintained by the writer (and + // by a trigger once sql/09 is applied) — no message rows are fetched + // just to fill a one-line preview. const rawList = queryData .map((item: any) => { const conv = item.conversation; if (!conv) return null; const isGroup = conv.type === 'group'; - const otherParticipants = conv.participants.filter((p: any) => p?.user?.id !== myId); + const otherParticipants = (conv.participants || []).filter((p: any) => p?.user?.id !== myId); const firstOther = otherParticipants[0]?.user; if (!isGroup && !firstOther) return null; @@ -283,22 +295,20 @@ export const useConversations = (activeFilter: string) => { } const unreadCount = unreadMap[conv.id] || 0; - const latestDbMsg = latestMessagesMap[conv.id]; - - let lastMsgVal = (conv as any).last_message || 'New Conversation'; - let lastMsgAtVal = (conv as any).last_message_at || conv.updated_at || conv.created_at; - let lastMsgSenderId = (conv as any).last_message_sender_id; - - if (latestDbMsg) { - lastMsgVal = latestDbMsg.text || (latestDbMsg.media_type ? `Sent a ${latestDbMsg.media_type}` : 'Sent a file'); - lastMsgAtVal = latestDbMsg.created_at; - lastMsgSenderId = latestDbMsg.sender_id; - } else if (hasMessagesInDb.has(conv.id)) { - // All messages in this conversation were deleted/hidden for this user - lastMsgVal = 'New Conversation'; + + let lastMsgVal = conv.last_message || 'New Conversation'; + let lastMsgAtVal = conv.last_message_at || conv.updated_at || conv.created_at; + let lastMsgSenderId: string | undefined; + + // Ticks for the list row come from messages already cached on device. + const cachedMsgs = LocalDataCache.getMessages(conv.id) as any[] | null; + if (cachedMsgs && cachedMsgs.length > 0) { + const newest = cachedMsgs[cachedMsgs.length - 1]; + if (newest && (!lastMsgAtVal || new Date(newest.created_at) >= new Date(lastMsgAtVal))) { + lastMsgSenderId = newest.sender_id; + } } - // Clean any forward tagging indicators for raw display in Chat List if (typeof lastMsgVal === 'string') { if (lastMsgVal.startsWith('\u200B[FWD_MANY]\u200B')) { lastMsgVal = '↪ Forwarded many times: ' + lastMsgVal.replace('\u200B[FWD_MANY]\u200B', ''); @@ -312,10 +322,9 @@ export const useConversations = (activeFilter: string) => { lastMsgStatusVal = lastMsgSenderId === myId ? 'Sent' : 'Received'; } - // Apply nickname overrides const customSetts = isGroup ? null : settingsMap[firstOther.id]; const dynamicName = customSetts?.nickname || (isGroup ? (conv.name || 'Group') : (firstOther.full_name || firstOther.username || 'Unknown')); - const dynamicAvatar = isGroup + const dynamicAvatar = isGroup ? (conv.photo_url || `https://cdn-icons-png.flaticon.com/512/166/166258.png`) : (customSetts?.customPhotoUrl || firstOther?.photo_url || `https://cdn-icons-png.flaticon.com/512/149/149071.png`); @@ -338,29 +347,14 @@ export const useConversations = (activeFilter: string) => { }) .filter(Boolean); - let finalFormattedList: any[] = []; - if (isDelta) { - const cacheMap = new Map(); - cached.forEach((c: any) => { - if (c && c.id) cacheMap.set(c.id, c); - }); - rawList.forEach((conv: any) => { - if (conv && conv.id) cacheMap.set(conv.id, conv); - }); - finalFormattedList = Array.from(cacheMap.values()); - } else { - finalFormattedList = rawList; - } - // De-duplicate direct conversations: Keep only the one with the most recent activity / actual messages const seenDict: Record = {}; - finalFormattedList.forEach((conv: any) => { + (rawList as any[]).forEach((conv: any) => { if (conv.type !== 'direct') return; const existing = seenDict[conv.otherUserId]; if (!existing) { seenDict[conv.otherUserId] = conv; } else { - // If one has real messages and the other is empty ('New Conversation'), keep the real one const currentHasMsg = conv.lastMsg && conv.lastMsg !== 'New Conversation'; const existingHasMsg = existing.lastMsg && existing.lastMsg !== 'New Conversation'; @@ -369,7 +363,6 @@ export const useConversations = (activeFilter: string) => { } else if (!currentHasMsg && existingHasMsg) { // keep existing, do nothing } else { - // both have messages or both are empty, keep the one with the more recent lastMsgAt if (new Date(conv.lastMsgAt).getTime() > new Date(existing.lastMsgAt).getTime()) { seenDict[conv.otherUserId] = conv; } @@ -377,124 +370,179 @@ export const useConversations = (activeFilter: string) => { } }); - const formattedList = finalFormattedList + const formattedList = (rawList as any[]) .filter((conv: any) => { if (conv.type !== 'direct') return true; return seenDict[conv.otherUserId]?.id === conv.id; }) - .sort((a, b) => { - return new Date(b.lastMsgAt).getTime() - new Date(a.lastMsgAt).getTime(); - }); + .sort((a, b) => new Date(b.lastMsgAt).getTime() - new Date(a.lastMsgAt).getTime()); LocalDataCache.saveConversations(myId, formattedList); + listRef.current = formattedList; setConversations(formattedList); + setHasMore(false); } catch (err) { console.error('Crash in fetchConversations execution details:', err); } finally { + inFlightRef.current = false; setLoading(false); setLoadingMore(false); setIsPaginating(false); } - }, [user, activeFilter, isAuthReady, formatTime, limit, isPaginating, userData]); + }, [user, activeFilter, isAuthReady, formatTime]); + + useEffect(() => { refreshRef.current = fetchConversations; }, [fetchConversations]); + + /** Debounced structural refresh: new chats, new participants, follow changes. */ + const scheduleStructuralRefresh = useCallback(() => { + if (structuralTimerRef.current) return; + structuralTimerRef.current = setTimeout(() => { + structuralTimerRef.current = null; + refreshRef.current?.(); + }, STRUCTURAL_DEBOUNCE_MS); + }, []); + + /** + * Realtime message → patch the list row in place. + * This is the whole egress fix: the old code called `fetchConversations()` + * here (6 round-trips, 25–130 KB) for every message and every read receipt. + */ + const patchConversationFromMessage = useCallback((row: any) => { + if (!user?.id || !row?.conversation_id) return; + const myId = user.id; + const current = listRef.current; + const idx = current.findIndex((c) => c.id === row.conversation_id); + if (idx === -1) { + scheduleStructuralRefresh(); // a chat we do not know about yet + return; + } + + const isMine = row.sender_id === myId; + const text = cleanPreview(row.text || (row.media_type ? `Sent a ${row.media_type}` : 'Sent a file')); + const at = row.created_at || new Date().toISOString(); + const prev = current[idx]; + const updated = { + ...prev, + lastMsg: text, + lastMsgAt: at, + time: formatTime(new Date(at)), + lastMsgStatus: isMine ? 'Sent' : 'Received', + unread: isMine ? prev.unread : true, + unreadCount: isMine ? prev.unreadCount : (prev.unreadCount || 0) + 1, + }; + const next = [updated, ...current.filter((_, i) => i !== idx)]; + listRef.current = next; + setConversations(next); + LocalDataCache.saveConversations(myId, next); + }, [user?.id, formatTime, scheduleStructuralRefresh]); + + /** Realtime `conversations` UPDATE → same idea, from the denormalized columns. */ + const patchConversationFromRow = useCallback((row: any) => { + if (!user?.id || !row?.id) return; + const current = listRef.current; + const idx = current.findIndex((c) => c.id === row.id); + if (idx === -1) return; + const prev = current[idx]; + const at = row.last_message_at || row.updated_at || prev.lastMsgAt; + const updated = { + ...prev, + lastMsg: row.last_message ? cleanPreview(row.last_message) : prev.lastMsg, + lastMsgAt: at, + time: formatTime(new Date(at)), + }; + const next = [updated, ...current.filter((_, i) => i !== idx)]; + listRef.current = next; + setConversations(next); + LocalDataCache.saveConversations(user.id, next); + }, [user?.id, formatTime]); useEffect(() => { if (!user || activeFilter === 'Calls' || !supabase || !isAuthReady) return; - // Subscribe to Cache Updates for instant off-line updates + // Local cache first: instant, zero egress. const unsubscribeCache = LocalDataCache.subscribe('conversations', (updatedList) => { if (updatedList && Array.isArray(updatedList)) { + listRef.current = updatedList; setConversations(updatedList); } else { - fetchConversations(); + scheduleStructuralRefresh(); } }); - fetchConversations(); + refreshRef.current?.(); - // Subscribe to conversation updates and new participants - const channelId = `conversations-realtime-${Math.random().toString(36).substring(2, 9)}`; + // Structural events only — these mean the list itself changed shape. + // (A message arriving is NOT one of them any more: it patches in place.) + const channelId = `conversations-realtime-${user.id}`; const channel = supabase .channel(channelId) .on('postgres_changes', { event: '*', schema: 'public', table: 'conversation_participants', filter: `user_id=eq.${user.id}` }, () => { - fetchConversations(); + scheduleStructuralRefresh(); }) .on('postgres_changes', { event: '*', schema: 'public', table: 'follows', filter: `follower_id=eq.${user.id}` }, () => { - fetchConversations(); + invalidateFollows(user.id); + scheduleStructuralRefresh(); }) .on('postgres_changes', { event: '*', schema: 'public', table: 'follows', filter: `following_id=eq.${user.id}` }, () => { - fetchConversations(); + invalidateFollows(user.id); + scheduleStructuralRefresh(); }) .subscribe(); + // Coming back to the tab is the natural moment to reconcile. + const handleFocus = () => scheduleStructuralRefresh(); + window.addEventListener('focus', handleFocus); + document.addEventListener('visibilitychange', handleFocus); + return () => { supabase.removeChannel(channel); unsubscribeCache(); + window.removeEventListener('focus', handleFocus); + document.removeEventListener('visibilitychange', handleFocus); + if (structuralTimerRef.current) { + clearTimeout(structuralTimerRef.current); + structuralTimerRef.current = null; + } }; - }, [user, activeFilter, isAuthReady, fetchConversations]); + }, [user?.id, activeFilter, isAuthReady, scheduleStructuralRefresh]); - // Subscribe dynamically to new messages/conversations for all of the user's active conversations + /** + * Live traffic — ONE channel for the whole list, and every handler patches + * local state from the realtime payload. Nothing here issues a query. + */ useEffect(() => { if (!supabase || !user || conversations.length === 0) return; - const currentIds = conversations.map(c => c.id).sort(); - const prevIds = [...subscribedIdsRef.current].sort(); - - const isIdentical = currentIds.length === prevIds.length && - currentIds.every((id, idx) => id === prevIds[idx]); - - if (isIdentical) { - return; // Save resources by not re-subscribing if conversation list hasn't structurally changed - } - - // Unsubscribe from existing chat channels - chatChannelsRef.current.forEach(ch => { - try { - supabase.removeChannel(ch); - } catch (err) { - console.warn('Error removing channel:', err); - } - }); - chatChannelsRef.current = []; - - const newChannels = conversations.map(c => c.id).map(convId => { - const channelName = `sub-chat-${convId}-${Math.random().toString(36).substring(2, 7)}`; - const ch = supabase - .channel(channelName) - .on('postgres_changes', { - event: '*', - schema: 'public', - table: 'messages', - filter: `conversation_id=eq.${convId}` - }, () => { - fetchConversations(); - }) - .on('postgres_changes', { - event: '*', - schema: 'public', - table: 'conversations', - filter: `id=eq.${convId}` - }, () => { - fetchConversations(); - }) - .subscribe(); - return ch; - }); + const ids = conversations.map((c) => c.id).slice(0, REALTIME_IN_FILTER_LIMIT); + const inFilter = `(${ids.join(',')})`; + if (ids.length === 0) return; + + const channelName = `chat-list-live-${user.id}`; + const ch = supabase + .channel(channelName) + .on('postgres_changes', { + event: 'INSERT', + schema: 'public', + table: 'messages', + filter: `conversation_id=in.${inFilter}`, + }, (payload: any) => patchConversationFromMessage(payload.new)) + .on('postgres_changes', { + event: 'UPDATE', + schema: 'public', + table: 'conversations', + filter: `id=in.${inFilter}`, + }, (payload: any) => patchConversationFromRow(payload.new)) + .subscribe(); - chatChannelsRef.current = newChannels; - subscribedIdsRef.current = conversations.map(c => c.id); + chatChannelsRef.current = [ch]; + subscribedIdsRef.current = ids; return () => { - chatChannelsRef.current.forEach(ch => { - try { - supabase.removeChannel(ch); - } catch (err) { - console.warn('Error removing channel on cleanup:', err); - } - }); + try { supabase.removeChannel(ch); } catch (err) { console.warn('Error removing channel:', err); } chatChannelsRef.current = []; subscribedIdsRef.current = []; }; - }, [conversations, user?.id, supabase, fetchConversations]); + }, [conversations.map((c) => c.id).join(','), user?.id, patchConversationFromMessage, patchConversationFromRow]); // Suggested users fetch useEffect(() => { diff --git a/src/providers/AuthProvider.tsx b/src/providers/AuthProvider.tsx index 2a7f526..8daaec0 100644 --- a/src/providers/AuthProvider.tsx +++ b/src/providers/AuthProvider.tsx @@ -8,6 +8,14 @@ import { sessionService } from '../services/db/sessionService'; import { LocalDataCache } from '../services/LocalDataCache'; import { MultiAccountService } from '../services/MultiAccountService'; +/** + * How often the client re-asserts "I am online" while the tab is visible. + * Presence is Realtime Presence; this only refreshes the DB fallback columns, + * and each write re-broadcasts the whole `users` row to its subscribers. + * 300 s was 60 s before the egress work — see docs/EGRESS_AUDIT.md. + */ +const PRESENCE_HEARTBEAT_MS = 300_000; + interface CustomUser extends User { uid: string; } @@ -248,7 +256,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children updateStatus(isVisible); if (isVisible) { if (!heartbeatInterval) { - heartbeatInterval = setInterval(() => updateStatus(true), 60000); + heartbeatInterval = setInterval(() => updateStatus(true), PRESENCE_HEARTBEAT_MS); } } else if (heartbeatInterval) { clearInterval(heartbeatInterval); @@ -258,7 +266,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children updateStatus(true); if (document.visibilityState === 'visible') { - heartbeatInterval = setInterval(() => updateStatus(true), 60000); + heartbeatInterval = setInterval(() => updateStatus(true), PRESENCE_HEARTBEAT_MS); } document.addEventListener('visibilitychange', handleVisibility); diff --git a/src/services/ImageService.ts b/src/services/ImageService.ts index 6118927..3f508e6 100644 --- a/src/services/ImageService.ts +++ b/src/services/ImageService.ts @@ -12,6 +12,45 @@ export class ImageService { * @param onProgress Callback for upload progress. * @returns The public URL of the uploaded image. */ + /** + * Downscale + re-encode before upload. + * + * Photos used to go to Storage at full camera resolution (3–8 MB), and every + * recipient then downloaded that original to render a 300 px bubble. Photos + * are the one asset where the egress bill scales with the file, so shrink + * them before they ever reach the bucket. + * + * JPEG/WebP only — a PNG may carry transparency, and a decoder may not exist + * (SSR/older browsers), in which case the original is uploaded untouched. + */ + static async compressImage(file: File, maxEdge: number = 1600, quality: number = 0.82): Promise { + const compressible = file.type === 'image/jpeg' || file.type === 'image/webp'; + if (!compressible) return file; + if (typeof document === 'undefined' || typeof createImageBitmap !== 'function') return file; + + try { + const bitmap = await createImageBitmap(file); + const largestEdge = Math.max(bitmap.width, bitmap.height); + const scale = Math.min(1, maxEdge / largestEdge); + if (scale === 1 && file.size < 300 * 1024) return file; + + const canvas = document.createElement('canvas'); + canvas.width = Math.max(1, Math.round(bitmap.width * scale)); + canvas.height = Math.max(1, Math.round(bitmap.height * scale)); + const ctx = canvas.getContext('2d'); + if (!ctx) return file; + + ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height); + const blob: Blob | null = await new Promise((resolve) => canvas.toBlob(resolve, 'image/jpeg', quality)); + if (!blob || blob.size >= file.size) return file; + + const name = file.name.replace(/\.[^.]+$/, '') + '.jpg'; + return new File([blob], name, { type: 'image/jpeg' }); + } catch { + return file; + } + } + static async uploadImage( file: File, onProgress?: (progress: number) => void, @@ -19,7 +58,8 @@ export class ImageService { ): Promise { try { if (onProgress) onProgress(20); - const url = await SupabaseStorageService.uploadImage(file, onProgress, bucket); + const optimized = await ImageService.compressImage(file); + const url = await SupabaseStorageService.uploadImage(optimized, onProgress, bucket); if (onProgress) onProgress(100); return url; } catch (error) { diff --git a/src/services/SupabaseStorageService.ts b/src/services/SupabaseStorageService.ts index b10493c..3cf1868 100644 --- a/src/services/SupabaseStorageService.ts +++ b/src/services/SupabaseStorageService.ts @@ -31,7 +31,10 @@ export const SupabaseStorageService = { const { data, error: uploadError } = await supabase.storage .from(bucket) .upload(filePath, file, { - cacheControl: '3600', + // Object names are unique (`random_timestamp`), so a client that has + // the file never needs it again. A 1-hour cache meant every device + // re-downloaded the same photo all day, straight onto the egress bill. + cacheControl: '31536000', upsert: false, }); diff --git a/src/services/db/userProfileService.ts b/src/services/db/userProfileService.ts index 9535591..7dd40e1 100644 --- a/src/services/db/userProfileService.ts +++ b/src/services/db/userProfileService.ts @@ -2,6 +2,14 @@ import { supabase } from '../../lib/supabase'; import { UserProfile } from '../../types'; import { storage } from '../StorageService'; +/** + * Minimum gap between presence writes to the `users` row. Presence itself is + * carried by Realtime Presence (0 DB bytes); these columns are only the + * offline fallback. Writing them broadcasts the whole row to every subscriber + * (REPLICA IDENTITY FULL), so keep this slow. See docs/EGRESS_AUDIT.md. + */ +export const STATUS_WRITE_THROTTLE_MS = 240_000; + // Throttled update tracker to minimize DB writes on free tier (Issue 2) let lastPresenceWriteTime = 0; let lastKnownStatusState: boolean | null = null; @@ -15,8 +23,10 @@ export const userProfileService = { const timeSinceLastWrite = now - lastPresenceWriteTime; const statusChanged = lastKnownStatusState !== isOnline; - // Throttle heartbeat to once every 45-60s unless it's a critical state transition - if (!force && !statusChanged && timeSinceLastWrite < 45000) { + // Presence is carried by Realtime Presence; the DB columns are only the + // offline fallback. Writing `is_online`/`last_seen` broadcasts the whole + // user row (REPLICA IDENTITY FULL), so keep this slow. + if (!force && !statusChanged && timeSinceLastWrite < STATUS_WRITE_THROTTLE_MS) { return; // Skip write to conserve Supabase Free Tier throughput } From 76281a5406e0d9d507b289f7c5dc4dc4a0712b16 Mon Sep 17 00:00:00 2001 From: GothwadTech <295316515+GothwadTech@users.noreply.github.com> Date: Sun, 11 Oct 2026 02:58:39 +0000 Subject: [PATCH 07/11] =?UTF-8?q?fix(sql)!:=20make=20the=20entire=20Supaba?= =?UTF-8?q?se=20setup=20re-runnable=20=E2=80=94=20it=20used=20to=20wipe=20?= =?UTF-8?q?the=20database?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `01_core_schema.sql` opened with `DROP TABLE IF EXISTS public.users CASCADE;` and the same for every other core table (`02` and `03` did it for posts and tickets). Since the documented flow is "run these in order", re-running the setup to apply a schema update — the normal thing to do — silently deleted every user, message, conversation, post and ticket, while reporting zero errors. Now, for both supported scenarios: * new fork + new Supabase project -> paste sql/grixchat_full_setup.sql, done * existing project -> paste the same file again: missing tables/columns/ indexes/constraints/buckets are created, policies and functions are re-created so updates apply, existing rows are never touched - 01/02/03: no drops; CREATE TABLE IF NOT EXISTS + ADD COLUMN IF NOT EXISTS for every column an older install may lack, missing constraints added (guarded), every policy re-created via DROP POLICY IF EXISTS, NOT NULL only when the data already satisfies it. - 04: header, SET search_path on both SECURITY DEFINER functions. - 05: replica identity + publication membership as guarded DO blocks (correct values, no dependency on a table still existing), loud warning about the 40-message history cap and how to skip it. - 06: header documenting the deliberately permissive storage policies. - 09: call_candidates joins the identity list; the last_message trigger now skips the recompute when a deleted row was not the newest (the 40-message cap deletes in batches on every insert). - New sql/grixchat_full_setup.sql, generated from 01..09 by scripts/build-sql-bundle.mjs (`npm run sql:bundle`) — checked in and kept in sync, so a forker has one paste. - sql/00_master_instructions.md rewritten as the runbook: both scenarios, what each file does, a verification query block, troubleshooting, and the rules for adding migrations. - Superseded SQL parked in sql/legacy/ (grixchat_latest_db_updates, supabase_schema, supabase_posts_schema, supabase_support_tickets_schema, db/1_complete_schema, db/2_realtime_and_security) with a README explaining that they must not be run — db/1 defined public.users differently and would have broken a current project. db/3_webrtc_signaling_architecture.md moved to docs/legacy/. - src/__tests__/sqlMigrations.test.ts guards all of it: no DROP TABLE/TRUNCATE, no CREATE without IF NOT EXISTS, every policy dropped before re-created, and the bundle in sync. Verified against a real PostgreSQL: fresh install clean (9/9 files), re-run on seeded data clean with data intact (users 2->2, messages 2->2, 43 policies, 5 triggers, 2 buckets, 6 published tables unchanged), re-run again after dropping a column + index + policy + trigger (all restored), the one-file bundle clean twice, plus behaviour checks on the message cap, preview trigger, read marker RLS isolation and get_unread_counts(). 111/111 tests green. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- AGENTS.md | 2 + README.md | 7 +- docs/CONTEXT.md | 9 +- docs/DATA_MODEL.md | 14 +- docs/DEAD_CODE.md | 23 + docs/DEV_SETUP.md | 9 + docs/KNOWN_ISSUES.md | 39 +- .../3_webrtc_signaling_architecture.md | 0 package.json | 3 +- scripts/build-sql-bundle.mjs | 91 + sql/00_master_instructions.md | 240 ++- sql/01_core_schema.sql | 274 ++- sql/02_posts_and_interactions_schema.sql | 83 +- sql/03_support_tickets_schema.sql | 30 +- sql/04_triggers_functions_and_rpc.sql | 13 +- ...05_advanced_optimizations_and_realtime.sql | 137 +- sql/06_storage_configurations.sql | 16 +- sql/09_egress_optimizations.sql | 25 +- sql/grixchat_full_setup.sql | 1626 +++++++++++++++++ sql/legacy/README.md | 23 + .../grixchat_latest_db_updates.sql | 0 sql/{ => legacy}/supabase_posts_schema.sql | 0 sql/{ => legacy}/supabase_schema.sql | 0 .../supabase_support_tickets_schema.sql | 0 .../legacy/superseded_complete_schema.sql | 0 .../superseded_realtime_and_security.sql | 0 src/__tests__/sqlMigrations.test.ts | 100 + 27 files changed, 2526 insertions(+), 238 deletions(-) rename {db => docs/legacy}/3_webrtc_signaling_architecture.md (100%) create mode 100644 scripts/build-sql-bundle.mjs create mode 100644 sql/grixchat_full_setup.sql create mode 100644 sql/legacy/README.md rename sql/{ => legacy}/grixchat_latest_db_updates.sql (100%) rename sql/{ => legacy}/supabase_posts_schema.sql (100%) rename sql/{ => legacy}/supabase_schema.sql (100%) rename sql/{ => legacy}/supabase_support_tickets_schema.sql (100%) rename db/1_complete_schema.sql => sql/legacy/superseded_complete_schema.sql (100%) rename db/2_realtime_and_security.sql => sql/legacy/superseded_realtime_and_security.sql (100%) create mode 100644 src/__tests__/sqlMigrations.test.ts diff --git a/AGENTS.md b/AGENTS.md index 3fe765d..1b673dd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -217,6 +217,7 @@ Rules: | `npm test` | ✅ 104/104 | | `npm run lint` | ✅ 0 errors | | Dead code | ✅ **0 files** — 189/189 reachable. See [`docs/DEAD_CODE.md`](./docs/DEAD_CODE.md) | +| SQL migrations | ✅ re-runnable (fresh install + re-run on live data verified); `npm run sql:bundle` in sync, guarded by `src/__tests__/sqlMigrations.test.ts` | | Tables queried but missing from `sql/` | ✅ 0 | | RPCs called but missing from `sql/` | ✅ 0 | | Cloudflare Pages deploy | ✅ `dist/` + `functions/` → | @@ -252,5 +253,6 @@ change. | [`docs/ARCHITECTURE.md`](./docs/ARCHITECTURE.md) | directory map, data flow, what is reachable | | [`docs/KNOWN_ISSUES.md`](./docs/KNOWN_ISSUES.md) | prioritised bug/fix list | | [`docs/EGRESS_AUDIT.md`](./docs/EGRESS_AUDIT.md) | Supabase egress, Realtime traffic, list-query rules | +| [`sql/00_master_instructions.md`](./sql/00_master_instructions.md) | database setup, schema updates, verification | | [`docs/DEAD_CODE.md`](./docs/DEAD_CODE.md) | the deletion record — what was removed and why | | [`docs/legacy/`](./docs/legacy/) | historical — **not current guidance** | diff --git a/README.md b/README.md index e6b2d5c..af7c1c4 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,12 @@ To support more than 50,000 active users comfortably on Supabase's free tier, da - `/src/providers`: Application context singletons (Supabase `AuthProvider`, global WebRTC `CallProvider`). - `/src/features`: Modular screens broken into focus zones (`chat`, `call`, `profile`, `search`, `stories`, `github`, `grixai`). - `/src/components`: UI layouts, bottom/top navigation components, and global drop-downs. -- `/sql`: The **only** place for schema — numbered migrations `01_` … `08_`, plus `00_master_instructions.md`. Contains tables, PostgreSQL functions, triggers, row-level security and indices. +- `/sql`: The **only** place for schema — numbered migrations `01_` … `09_`, plus + `00_master_instructions.md` (the runbook) and `grixchat_full_setup.sql` (all of + them in one paste, generated by `npm run sql:bundle`). Contains tables, + PostgreSQL functions, triggers, row-level security and indices. **Every file is + safe to re-run**: nothing is dropped, missing objects are created, policies are + re-created. Superseded files live in `/sql/legacy` — never run those. - `/server/api.ts`: **The API.** Runtime-neutral (Web `Request`/`Response`), so the same file serves Cloudflare Pages Functions and the Express dev server. - `/functions`: Cloudflare Pages Functions — thin adapters that forward `/api/*` and `/auth/*` to `server/api.ts`. - `/docs`: Developer documentation — orientation, setup, testing, data model, known issues. diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 37e24c3..fb5cae3 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -169,8 +169,12 @@ The long version is in **[../AGENTS.md](../AGENTS.md)**. Short version: ticks, call signalling, presence → `channel().send()`, 0 bytes of egress. 3. **Don't import across sibling features.** `features/chat/` must not reach into `features/call/`. Go through `services/` or a provider. -4. **SQL changes go in `/sql/`, numbered.** The root-level `.sql` duplicates - have been deleted — do not recreate them. +4. **SQL changes go in `/sql/`, numbered** (`10_…`, appended to + `scripts/build-sql-bundle.mjs`, then `npm run sql:bundle`). Migrations must be + re-runnable: no `DROP TABLE`, `CREATE … IF NOT EXISTS`, `CREATE OR REPLACE`, + `DROP POLICY IF EXISTS` before every policy. Superseded files go to + `sql/legacy/` — never recreate root-level duplicates. Runbook: + [../sql/00_master_instructions.md](../sql/00_master_instructions.md). 5. **Don't reintroduce dead code.** If you add a file, wire it to a route or an importer in the same change. The scan procedure is in [DEAD_CODE.md](./DEAD_CODE.md#reproducing-the-scan). @@ -189,5 +193,6 @@ The long version is in **[../AGENTS.md](../AGENTS.md)**. Short version: | [ARCHITECTURE.md](./ARCHITECTURE.md) | you need to find where something lives | | [KNOWN_ISSUES.md](./KNOWN_ISSUES.md) | you want the prioritised bug/fix list | | [EGRESS_AUDIT.md](./EGRESS_AUDIT.md) | egress is high, or you touch Realtime / list queries | +| [../sql/00_master_instructions.md](../sql/00_master_instructions.md) | you are setting up or updating the database | | [DEAD_CODE.md](./DEAD_CODE.md) | the deletion record — what was removed and why | | [legacy/](./legacy/) | historical docs — **not current guidance** | diff --git a/docs/DATA_MODEL.md b/docs/DATA_MODEL.md index d82bf62..a244c65 100644 --- a/docs/DATA_MODEL.md +++ b/docs/DATA_MODEL.md @@ -1,7 +1,15 @@ # Data Model -> `sql/` is the **only** authoritative schema. The five stale `.sql` files that -> used to sit at the repository root have been deleted. +> `sql/` is the **only** authoritative schema: numbered migrations `01_` … `09_`, +> run in that order. Old copies are parked in [`sql/legacy/`](../sql/legacy/README.md) +> (never run them — they define the same tables differently). +> +> **Every file is re-runnable.** A new project can paste +> [`sql/grixchat_full_setup.sql`](../sql/grixchat_full_setup.sql); an existing +> project can run the same set again to pick up missing columns, indexes, +> constraints, buckets and updated policies. Nothing is ever dropped. Runbook + +> verification queries: [`sql/00_master_instructions.md`](../sql/00_master_instructions.md). +> The rule is enforced by `src/__tests__/sqlMigrations.test.ts`. --- @@ -86,7 +94,7 @@ Profile row, 1:1 with `auth.users`. ### `call_candidates` — `:135` ⚠️ defined, never queried WebRTC ICE signalling. The live calling path (`providers/CallProvider.tsx`) signals over Broadcast channels instead. Either adopt it or drop it. -`db/3_webrtc_signaling_architecture.md` describes the design that was not taken. +[`docs/legacy/3_webrtc_signaling_architecture.md`](./legacy/3_webrtc_signaling_architecture.md) describes the design that was not taken. ### `chat_settings` — `:145` Per-user chat customisation. `id`, `user_id`, `receiver_id`, `nickname`, diff --git a/docs/DEAD_CODE.md b/docs/DEAD_CODE.md index 628608e..c0da34f 100644 --- a/docs/DEAD_CODE.md +++ b/docs/DEAD_CODE.md @@ -204,3 +204,26 @@ procedure is: 3. Anything under `src/` not reached is dead. `npm test` + `npm run lint` + `npm run build` are the regression gate. + +--- + +## 2026-10-11 — SQL consolidation + +| Moved | From | Why | +|---|---|---| +| `grixchat_latest_db_updates.sql` | `sql/` | Older patch file with duplicate, differently-named policies — running it next to `01_core_schema.sql` created conflicting RLS | +| `supabase_schema.sql` | `sql/` | Superseded by `01_core_schema.sql` | +| `supabase_posts_schema.sql` | `sql/` | Superseded by `02_posts_and_interactions_schema.sql` | +| `supabase_support_tickets_schema.sql` | `sql/` | Superseded by `03_support_tickets_schema.sql` | +| `db/1_complete_schema.sql` | `db/` | Early divergent design: `users.email UNIQUE NOT NULL`, `users.status`, `group_call_participants` — **would break a current project if run** | +| `db/2_realtime_and_security.sql` | `db/` | The matching RLS pass for that design | +| `db/3_webrtc_signaling_architecture.md` | `db/` → `docs/legacy/` | Design note for signalling that was never adopted (calling uses Broadcast) | + +All seven now live in [`sql/legacy/`](../sql/legacy/README.md) — parked, not +deleted, with a README explaining that they must not be run. + +Also fixed in the same pass: `01_core_schema.sql`, `02_…` and `03_…` began with +`DROP TABLE … CASCADE`. Re-running the documented setup on a live project +therefore **deleted every user, message and post while reporting zero errors**. +The drops are gone; the files are idempotent now, and +`src/__tests__/sqlMigrations.test.ts` fails if anyone adds one back. diff --git a/docs/DEV_SETUP.md b/docs/DEV_SETUP.md index f15a12d..7454636 100644 --- a/docs/DEV_SETUP.md +++ b/docs/DEV_SETUP.md @@ -99,6 +99,15 @@ keeps the messages you sent. `__grixMock.reset()` clears it. Required for: RLS verification, multi-device realtime, actual FCM push, actual file storage. +**1. Prepare the database first.** Supabase → SQL Editor → paste +[`sql/grixchat_full_setup.sql`](../sql/grixchat_full_setup.sql) → RUN. One paste +creates every table, policy, bucket, trigger and function, and it is safe to run +again later (nothing is dropped — see +[`sql/00_master_instructions.md`](../sql/00_master_instructions.md)). Without it +the app signs in and then shows nothing. + +**2. Then run the app:** + ```bash cp .env.example .env # fill in the values diff --git a/docs/KNOWN_ISSUES.md b/docs/KNOWN_ISSUES.md index 42f2764..c18ae24 100644 --- a/docs/KNOWN_ISSUES.md +++ b/docs/KNOWN_ISSUES.md @@ -23,9 +23,9 @@ dashboard, Supabase, or a decision. | A | Add the **build-time** variables: `VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY`, `VITE_FIREBASE_*`, `VITE_LIVEKIT_URL`, `NODE_VERSION=22` | Cloudflare → Workers & Pages → gtwdchat → Settings → Environment variables (Production **and** Preview) | They are inlined into the bundle. **Without `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` the Supabase SDK is compiled out and the deployed app cannot sign in** — the build prints a loud warning. Changing one requires a redeploy. | | B | Add the **runtime secrets** for the API: `GEMINI_API_KEY`, `FIREBASE_SERVICE_ACCOUNT`, `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET`, `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `SUPABASE_SERVICE_ROLE_KEY`, `APP_URL=https://grixchat.gothwadtech.com` | same screen as above | The API verifies JWTs against `VITE_SUPABASE_URL` + `VITE_SUPABASE_ANON_KEY`, so those two must be present **server-side as well**. Without any of these the matching feature returns a clear "not configured" error instead of crashing. Step-by-step: [DEV_SETUP.md](./DEV_SETUP.md#deploy--cloudflare-pages). | | C | Confirm the Pages build settings: build command `npm run build`, output `dist`, root `/`; production branch = your main branch; custom domain `grixchat.gothwadtech.com` attached | Cloudflare → the project's Settings / Custom domains | `wrangler.toml` pins the output dir and compatibility date, but the dashboard values win. | -| D | Decide the fate of `call_candidates` (issue 7) | Supabase SQL editor | It is defined but unused. Drop it with:
`DROP TABLE IF EXISTS public.call_candidates CASCADE;`
or keep it and adopt the table-based signalling in `db/3_webrtc_signaling_architecture.md`. | +| D | Decide the fate of `call_candidates` (issue 7) | Supabase SQL editor | It is defined but unused. Drop it with:
`DROP TABLE IF EXISTS public.call_candidates CASCADE;`
or keep it and adopt the table-based signalling in [`docs/legacy/3_webrtc_signaling_architecture.md`](./legacy/3_webrtc_signaling_architecture.md). | | E | Add a **Cloudflare Rate Limiting Rule** on `/api/*` (optional, but recommended before scaling) | Cloudflare → Security → WAF | The limiter in `server/api.ts` counts in memory, i.e. per isolate — a speed bump, not a hard global quota. | -| F | Run **`sql/09_egress_optimizations.sql`** (2 minutes, idempotent, ends with a self-check) | Supabase → SQL Editor | Read receipts become one row instead of one per unread message, the chat-list preview is maintained by a trigger, `REPLICA IDENTITY` stops shipping whole rows + the passcode hash, and the missing RLS UPDATE policy on `conversation_participants` gets created. Full analysis: [EGRESS_AUDIT.md](./EGRESS_AUDIT.md). | +| F | Run **`sql/grixchat_full_setup.sql`** (2 minutes, idempotent, ends with a self-check) — or just `09_egress_optimizations.sql` if you only want the egress fixes | Supabase → SQL Editor | Creates anything missing and updates every policy/function. For the egress work specifically: read receipts become one row instead of one per unread message, the chat-list preview is maintained by a trigger, `REPLICA IDENTITY` stops shipping whole rows + the passcode hash, and the missing RLS UPDATE policy on `conversation_participants` gets created. Runbook: [`../sql/00_master_instructions.md`](../sql/00_master_instructions.md). Full analysis: [EGRESS_AUDIT.md](./EGRESS_AUDIT.md). | | G | Decide whether to enable the **RLS hardening** block at the end of that same file (commented out) | Supabase → SQL Editor | Today `users` and `conversation_participants` are readable by every authenticated account: `email`, `phone`, `lock` (passcode hash), `fcm_tokens`, and the whole follow/participant graph. | Optional: set `ALLOWED_ORIGINS=https://your-domain.tld,https://your-other.tld` @@ -228,6 +228,40 @@ a call, so `drop` rightly leaves it alone. --- +## 🔴 P0 — The SQL setup used to delete your data on a re-run — ✅ FIXED + +### 20. `01`–`03` began with `DROP TABLE … CASCADE`, so "just run it again" wiped the database + +`01_core_schema.sql` opened with `DROP TABLE IF EXISTS public.users CASCADE;` and +the same line for every other core table (`02` and `03` did it for posts and +tickets). The documented setup flow is "run these files in order", so re-running +it on a project with users — the normal way to apply a schema update — silently +deleted every user, message, conversation, post and ticket, **while reporting +zero errors**, which is exactly why nobody noticed. + +- **Fixed:** the drops are gone. Every table is `CREATE TABLE IF NOT EXISTS`, and + each file now also adds anything an older install is missing: columns + (`ADD COLUMN IF NOT EXISTS`), indexes, constraints, buckets, plus + `DROP POLICY IF EXISTS` + `CREATE POLICY` so an updated policy definition + actually replaces the old one. Existing rows are never touched. +- **One file to run:** `sql/grixchat_full_setup.sql` (generated by + `npm run sql:bundle`) — fresh project or existing one, same paste. +- **Docs:** [`../sql/00_master_instructions.md`](../sql/00_master_instructions.md) + (runbook + verification queries + troubleshooting). +- **Superseded files moved out of the way** to `sql/legacy/` — including + `db/1_complete_schema.sql`, which defined `public.users` differently and would + have broken a current project if anyone had run it. +- **Guarded by tests:** `src/__tests__/sqlMigrations.test.ts` fails on any + `DROP TABLE`/`TRUNCATE`, a non-idempotent `CREATE`, a policy without a + `DROP POLICY IF EXISTS`, or a stale bundle. +- **Verified for real:** the whole set was executed against PostgreSQL twice — + fresh install, then a re-run on seeded data (users 2→2, messages 2→2, policies, + triggers, buckets and publication membership unchanged), then again after + deliberately dropping a column, an index, a policy and a trigger (all + restored). + +--- + ## 🟠 P0 — Egress (fixed in code; SQL is a 2-minute step) ### 19. 5 GB of Supabase egress in a month with 2–3 users — ✅ FIXED in code, 🧑 needs one SQL run @@ -325,3 +359,4 @@ with it: | 1.14 MB entry chunk, eager emoji picker, console in prod | **#12, #13, #14 — this pass** | | Stale Reels leftovers in a live screen | **#18 — this pass** | | 5 GB/month of egress from per-event list refetches | **#19 — this pass; SQL hand-off in row F** | +| Re-running the setup deleted every table, with no error | **#20 — this pass; re-runnable SQL + guard tests** | diff --git a/db/3_webrtc_signaling_architecture.md b/docs/legacy/3_webrtc_signaling_architecture.md similarity index 100% rename from db/3_webrtc_signaling_architecture.md rename to docs/legacy/3_webrtc_signaling_architecture.md diff --git a/package.json b/package.json index bacba7c..ab03dee 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,8 @@ "test:watch": "vitest", "test:ui": "vitest --ui", "lint": "tsc --noEmit", - "clean": "rm -rf dist" + "clean": "rm -rf dist", + "sql:bundle": "node scripts/build-sql-bundle.mjs" }, "dependencies": { "@livekit/components-react": "^2.9.21", diff --git a/scripts/build-sql-bundle.mjs b/scripts/build-sql-bundle.mjs new file mode 100644 index 0000000..fff1950 --- /dev/null +++ b/scripts/build-sql-bundle.mjs @@ -0,0 +1,91 @@ +#!/usr/bin/env node +/** + * Builds `sql/grixchat_full_setup.sql` by concatenating the numbered migrations + * in order, so a new fork can paste ONE file into the Supabase SQL editor. + * + * The numbered files stay the source of truth. Run: + * npm run sql:bundle # regenerate + * npm run sql:bundle -- --check # fail if the bundle is stale (CI + tests) + */ +import {readFileSync, writeFileSync, existsSync} from 'node:fs'; +import {fileURLToPath} from 'node:url'; +import {dirname, join} from 'node:path'; + +const here = dirname(fileURLToPath(import.meta.url)); +const sqlDir = join(here, '..', 'sql'); +const OUT = join(sqlDir, 'grixchat_full_setup.sql'); + +const FILES = [ + '01_core_schema.sql', + '02_posts_and_interactions_schema.sql', + '03_support_tickets_schema.sql', + '04_triggers_functions_and_rpc.sql', + '05_advanced_optimizations_and_realtime.sql', + '06_storage_configurations.sql', + '07_chat_time_scheduling_migration.sql', + '08_stories_expiration_and_views.sql', + '09_egress_optimizations.sql', +]; + +const rule = '-- ' + '═'.repeat(74); + +function banner(name, index, total) { + return `${rule} +-- PART ${index}/${total} — sql/${name} +-- (generated from the file of that name; edit THAT file, then re-run +-- "npm run sql:bundle" — do not edit this bundle by hand) +${rule} +`; +} + +export function buildBundle() { + const parts = [ + `${rule} +-- GRIXCHAT — COMPLETE SUPABASE SETUP (generated, do not edit by hand) +${rule} +-- One paste for a brand-new Supabase project: +-- Supabase Dashboard -> SQL Editor -> New query -> paste ALL of this -> RUN. +-- +-- Safe to run again later, on the same project, at any time: +-- * nothing is dropped or truncated +-- * tables/columns/indexes/constraints are created only when missing +-- * policies and functions are re-created, so updated definitions apply +-- * existing rows are never modified +-- +-- Generated by: npm run sql:bundle (source: sql/01_*.sql … sql/09_*.sql) +-- Read first: sql/00_master_instructions.md +${rule} +`, + ]; + + FILES.forEach((name, i) => { + const path = join(sqlDir, name); + if (!existsSync(path)) throw new Error(`missing migration: ${name}`); + parts.push('\n' + banner(name, i + 1, FILES.length) + '\n' + readFileSync(path, 'utf8').trimEnd() + '\n'); + }); + + parts.push(`\n${rule} +-- DONE. Verify with the checklist in sql/00_master_instructions.md +${rule} +`); + return parts.join('\n'); +} + +export function readBundle() { + return existsSync(OUT) ? readFileSync(OUT, 'utf8') : null; +} + +const isCheck = process.argv.includes('--check'); +const expected = buildBundle(); +const current = readBundle(); + +if (isCheck) { + if (current !== expected) { + console.error('sql/grixchat_full_setup.sql is STALE — run: npm run sql:bundle'); + process.exit(1); + } + console.log('sql bundle is up to date'); +} else { + writeFileSync(OUT, expected); + console.log(`wrote sql/grixchat_full_setup.sql (${expected.split('\n').length} lines)`); +} diff --git a/sql/00_master_instructions.md b/sql/00_master_instructions.md index cacd6c1..0d77b0c 100644 --- a/sql/00_master_instructions.md +++ b/sql/00_master_instructions.md @@ -1,76 +1,170 @@ -# GrixChat Supabase Setup & Verification Guide 🚀 - -This master guide ensures a 100% successful, zero-error database configuration on your Supabase project. All previous updates and schema files has been compiled and ordered sequentially inside this folder to match Supabase's schema dependencies perfectly. +# GrixChat — Supabase setup (read this first) + +Everything the app needs in the database lives in this folder. There are two +supported ways to run it, and **both are safe to run on a project that already +has data** — nothing here drops a table, truncates a row, or overwrites a +column. Re-running the whole set is the supported way to pick up a schema +update. + +| You are… | Run | Time | +|---|---|---| +| **starting fresh** (new fork, new Supabase project) | [`grixchat_full_setup.sql`](./grixchat_full_setup.sql) — everything in one paste | ~30 s | +| **updating an existing project** | the same file, again. Or `01` … `09` one by one if you prefer to see each step | ~30 s | +| **verifying after a deploy** | the checklist at the bottom of this file | ~2 min | + +> Prefer the individual files? Run them **in numerical order**: +> `01_core_schema.sql` → `02_posts_and_interactions_schema.sql` → … → +> `09_egress_optimizations.sql`. The bundle is generated from exactly those +> files in that order, so the result is identical. +> +> `npm run sql:bundle` regenerates the bundle after you edit a numbered file. +> `src/__tests__/sqlMigrations.test.ts` fails if the bundle is stale — or if +> anyone reintroduces a `DROP TABLE` or a non-idempotent `CREATE`. --- -## 📌 Order of Execution Checklist - -Always execute the SQL files in the exact order below. Copy the contents of each file and run them in the **SQL Editor** of your Supabase dashboard: - -1. **`01_core_schema.sql`** - - 🛠️ Creates the primary `users`, `follows`, `conversations`, `messages`, `stories`, `calls`, `call_candidates`, `chat_settings`, and `notifications` tables. - - 🔒 Configures Row-Level Security (RLS) policies for secure client-side database querying. - - ⚡ Registers optimized b-tree database search indexes. - -2. **`02_posts_and_interactions_schema.sql`** - - 📊 Creates tables for Social Feeds: `posts`, `post_likes`, and `post_comments`. - - 🔐 Sets up full public-read & user-write RLS policies and performance indexes. - -3. **`03_support_tickets_schema.sql`** - - 🎫 Creates the `support_tickets` table for in-app contact forms, support lines, and system complaints. - - 🛡️ Adds anonymous/authenticated insert policies. - -4. **`04_triggers_functions_and_rpc.sql`** - - 🔗 Registers the `get_direct_conversation_id` database RPC function (used for lightweight, high-performance instant chat room matching instead of manual join queries). - - 👤 Provisions the native `auth.users` trigger that automatically replicates newly registered users (via email, Google or GitHub OAuth) into your public `users` table with standard defaults and safe length check values. - -5. **`05_advanced_optimizations_and_realtime.sql`** - - ⚡ Sets up efficient real-time subscription pipelines (`supabase_realtime` publication group). - - 🔋 Registers auto-pruning triggers to cap active chat messages and voice/video records at 60 active events, automatically sweeping old historical data as the table expands. This completely bypasses table bloat, maintaining a lightweight database footprint, and keeps your project 100% under Supabase's free plan threshold! - -6. **`06_storage_configurations.sql`** - - 📂 Seeds the required Supabase Storage buckets: `chat-media` (for pictures, videos, and custom voice memos) and `profiles` (for user profiles and circular thumbnails). - - 🛡️ Configures secure upload policies on `storage.objects` to ensure media files are publicly visible while restricting modifications strictly to their authenticated owners. - ---- - -## 🔍 Post-Setup Verification Checklist - -After running the scripts, you can verify they are functional with the following tests: - -### 1. Verification of Tables -Navigate to your Supabase **Table Editor**. You should see the following tables populated under the `public` schema: -- [ ] `users` -- [ ] `follows` -- [ ] `conversations` -- [ ] `conversation_participants` -- [ ] `messages` -- [ ] `stories` -- [ ] `calls` -- [ ] `call_candidates` -- [ ] `chat_settings` -- [ ] `notifications` -- [ ] `posts` -- [ ] `post_likes` -- [ ] `post_comments` -- [ ] `support_tickets` - -### 2. Verify Storage Buckets -Navigate to the **Storage** section in your Supabase dashboard. You should see two public buckets: -- [ ] `chat-media` -- [ ] `profiles` - -### 3. Verify Triggers and Database Functions -Navigate to **Database** -> **Triggers** & **Database** -> **Functions** to check if: -- [ ] Function `get_direct_conversation_id` is registered successfully. -- [ ] Trigger `on_auth_user_created` exists under `auth.users` referencing `handle_new_auth_user`. -- [ ] Live pruning triggers like `trg_prune_past_messages` exist on `public.messages`. - ---- - -## 🛠️ Troubleshooting & Support Tips - -* **Foreign Key Errors:** Run the scripts in the specified numerical order. `02_posts_and_interactions_schema.sql` depends on tables generated in `01_core_schema.sql`, and so on. -* **Storage Upload Failures:** If user uploads fail on the client-side, ensure storage policies are active and that the `chat-media` and `profiles` buckets are set to **"Public"** in the Storage configuration dashboard. -* **Realtime Sync Issues:** In some cases, Supabase Realtime requires a manual toggle check. Go to **Database** -> **Replication**, search for `supabase_realtime`, and ensure replication is toggled **Active** for the desired tables (`messages`, `conversations`, `users`, etc.). +## 1. New project (fork → deploy) + +1. Create the Supabase project, then **SQL Editor → New query**. +2. Paste **all** of [`grixchat_full_setup.sql`](./grixchat_full_setup.sql) and + press **RUN**. It is one transaction-free script: every statement is + idempotent, so a partial run just means "run it again". +3. Copy **Project URL** + **anon key** (Settings → API) into the frontend env: + `VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY`. On Cloudflare Pages these are + build-time variables — see [`../docs/DEV_SETUP.md`](../docs/DEV_SETUP.md). +4. Turn on **Authentication → Providers** (email, Google/GitHub if you use + them) and add your site URL to **Authentication → URL configuration**. +5. Run the verification checklist below. + +## 2. Existing project (schema update) + +Paste the same file again. What it does on a live database: + +* **creates** anything missing — tables, columns (`last_read_at`, + `last_message_sender_id`, `chat_time_restrictions`, `stories.views`, + `profile_type`, …), indexes, constraints, storage buckets; +* **re-creates** policies and functions, so an updated definition replaces the + old one (that is how the SQL "update" reaches a project that was set up + earlier); +* **never touches** existing rows, and never drops a table or a column. + +Two deliberate exceptions, both about *message history*, and both parts of the +app's existing design — read them before you run: +`05_advanced_optimizations_and_realtime.sql` caps every chat at the newest +**40 messages** (sections 1 and 6). If you want history kept instead, skip +those two sections and use the time-based `prune_old_messages(days)` from `09`. + +## 3. What each file does + +| File | Creates | Notes | +|---|---|---| +| `01_core_schema.sql` | `users`, `follows`, `conversations`, `conversation_participants`, `messages`, `stories`, `calls`, `call_candidates`, `chat_settings`, `notifications` + RLS + indexes | column upgrades for older installs, constraints added only when missing | +| `02_posts_and_interactions_schema.sql` | `posts`, `post_likes`, `post_comments` + RLS + indexes | | +| `03_support_tickets_schema.sql` | `support_tickets` + RLS | | +| `04_triggers_functions_and_rpc.sql` | `get_direct_conversation_id()`, `handle_new_auth_user()` + the `auth.users` → `public.users` trigger | this is what creates a profile on signup/OAuth | +| `05_advanced_optimizations_and_realtime.sql` | realtime publication membership, preview triggers, replica identity, **40-message cap** | see the warning above | +| `06_storage_configurations.sql` | `chat-media` + `profiles` buckets and their storage policies | buckets are public-read on purpose | +| `07_chat_time_scheduling_migration.sql` | `conversations.chat_time_restrictions` | | +| `08_stories_expiration_and_views.sql` | `stories.views`, `view_story()`, `cleanup_expired_stories()` | | +| `09_egress_optimizations.sql` | `conversation_participants.last_read_at` **+ its RLS UPDATE policy**, the `last_message*` trigger, replica-identity fixes, indexes, `get_unread_counts()`, `prune_old_messages()` | ends with a self-check query — see below. Full reasoning: [`../docs/EGRESS_AUDIT.md`](../docs/EGRESS_AUDIT.md) | + +## 4. Verification checklist + +Run this in the SQL editor. Every line must read `OK` (it is also the self-check +at the end of `09`): + +```sql +SELECT 'tables' AS what, + CASE WHEN COUNT(*) >= 14 THEN 'OK (' || COUNT(*) || ')' ELSE 'MISSING ' || COUNT(*) END AS state + FROM information_schema.tables + WHERE table_schema = 'public' AND table_type = 'BASE TABLE' + AND table_name IN ('users','follows','conversations','conversation_participants','messages', + 'stories','calls','call_candidates','chat_settings','notifications', + 'posts','post_likes','post_comments','support_tickets') +UNION ALL +SELECT 'columns added by later migrations', + CASE WHEN COUNT(*) = 4 THEN 'OK' ELSE 'MISSING ' || COUNT(*) END + FROM information_schema.columns + WHERE table_schema = 'public' + AND (table_name, column_name) IN ( + ('conversation_participants','last_read_at'), + ('conversations','last_message_sender_id'), + ('conversations','chat_time_restrictions'), + ('stories','views')) +UNION ALL +SELECT 'RLS policies (expect 43+)', + CASE WHEN COUNT(*) >= 43 THEN 'OK (' || COUNT(*) || ')' ELSE 'LOW ' || COUNT(*) END + FROM pg_policies WHERE schemaname = 'public' +UNION ALL +SELECT 'UPDATE policy on conversation_participants', + CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END + FROM pg_policies WHERE schemaname='public' AND tablename='conversation_participants' AND cmd='UPDATE' +UNION ALL +SELECT 'storage buckets', + CASE WHEN COUNT(*) = 2 THEN 'OK' ELSE 'MISSING ' || COUNT(*) END + FROM storage.buckets WHERE id IN ('chat-media','profiles') +UNION ALL +SELECT 'realtime publication', + CASE WHEN COUNT(*) >= 5 THEN 'OK (' || COUNT(*) || ')' ELSE 'LOW ' || COUNT(*) END + FROM pg_publication_tables WHERE pubname = 'supabase_realtime' AND schemaname = 'public' +UNION ALL +SELECT 'replica identity (messages must be FULL)', + COALESCE((SELECT CASE WHEN relreplident = 'f' THEN 'OK' ELSE 'WRONG' END + FROM pg_class WHERE oid = 'public.messages'::regclass), 'MISSING') +UNION ALL +SELECT 'signup trigger', + CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END + FROM pg_trigger WHERE tgname = 'on_auth_user_created'; +``` + +Then, in the dashboard: + +* **Table Editor** — the 14 tables above exist. +* **Storage** — buckets `chat-media` (50 MB limit) and `profiles` (5 MB). +* **Database → Replication** — `supabase_realtime` is enabled for + `messages`, `conversations`, `users`, `calls`, `conversation_participants`. + (The SQL registers the tables; the dashboard toggle is what actually streams.) +* **Authentication → Policies** — no duplicate policy names from an older file. + If you ever ran one of the files in [`legacy/`](./legacy/), read + [`legacy/README.md`](./legacy/README.md) and drop the leftovers it lists. + +### Prove it is re-runnable + +```sql +SELECT (SELECT COUNT(*) FROM public.users) AS users, + (SELECT COUNT(*) FROM public.messages) AS messages, + (SELECT COUNT(*) FROM pg_policies WHERE schemaname='public') AS policies; +``` + +Run the setup again, then run this again: `users` and `messages` must be +**identical**, `policies` must not grow (policies are replaced, never stacked). +That is exactly what `npm test` checks in `src/__tests__/sqlMigrations.test.ts`. + +## 5. Troubleshooting + +| Symptom | Cause / fix | +|---|---| +| `relation "public.users" does not exist` | files ran out of order — always `01` first | +| Foreign-key error while running `02`/`03` | same: `01` must be applied first | +| `permission denied for table storage.objects` | run `06` as the project owner (the SQL editor is fine); a non-owner role cannot create storage policies | +| Realtime updates never arrive | dashboard → Database → Replication → `supabase_realtime`; also check that the table is listed in `pg_publication_tables` (the checklist above) | +| Uploads fail with 403 | buckets exist but storage policies were not applied — re-run `06` | +| Chat history looks short | that is `05`'s 40-message cap, by design. Skip its sections 1 and 6 to keep history (see §2) | +| A policy name appears twice in the dashboard | an old file from [`legacy/`](./legacy/) was run; drop the duplicates as described there | +| `function public.get_unread_counts() does not exist` | `09` has not been applied yet | +| Everything works but egress is still high | check `last_read_at` exists (the client falls back to the old per-message read path without it) and re-read [`../docs/EGRESS_AUDIT.md`](../docs/EGRESS_AUDIT.md) | + +## 6. Rules for changing this folder + +1. **Never add a `DROP TABLE`.** Use `CREATE TABLE IF NOT EXISTS` plus + `ALTER TABLE … ADD COLUMN IF NOT EXISTS` for anything new. +2. **Never add a `CREATE` that is not idempotent** — `CREATE OR REPLACE` for + functions, `DROP POLICY IF EXISTS` + `CREATE POLICY` for policies, + `CREATE INDEX IF NOT EXISTS` for indexes, `DROP TRIGGER IF EXISTS` + + `CREATE TRIGGER` for triggers. +3. **New migrations get the next number** (`10_…`) and are appended to the file + list in `scripts/build-sql-bundle.mjs`; then run `npm run sql:bundle`. +4. **Test before committing.** The suite enforces rules 1–3; a real Postgres run + (fresh + re-run on populated data) is how the 2026-10-11 review was done. +5. Superseded files go to [`legacy/`](./legacy/) — never leave two files that + create the same table next to each other. diff --git a/sql/01_core_schema.sql b/sql/01_core_schema.sql index 17f08f9..09dcc10 100644 --- a/sql/01_core_schema.sql +++ b/sql/01_core_schema.sql @@ -1,33 +1,21 @@ -- ========================================================================= --- STEP 1: GRIXCHAT CORE SCHEMA SETUP (DATABASE BLUEPRINT) +-- STEP 1/9: GRIXCHAT CORE SCHEMA (users, chats, messages, calls, ...) -- ========================================================================= --- Instructions: --- 1. Open your Supabase Dashboard. --- 2. Navigate to "SQL Editor" on the left sidebar. --- 3. Create a "New Query". --- 4. Paste ALL contents of this script and click "RUN". +-- Supabase Dashboard -> SQL Editor -> New query -> paste -> RUN. +-- Then continue with 02, 03, ... 09 in order (see 00_master_instructions.md). +-- +-- SAFE TO RE-RUN, ON A FRESH PROJECT AND ON A LIVE ONE: +-- * nothing is dropped or truncated — no `DROP TABLE`, ever +-- * tables are created only if missing, missing columns/indexes/constraints +-- are added, policies are re-created so an updated definition replaces the +-- old one +-- * existing rows are never modified by this file -- ========================================================================= --- 1. CLEANUP PRE-EXISTING TABLES AND TRIGGERS (Ensures Fresh Start) -DROP TRIGGER IF EXISTS on_auth_user_created ON auth.users; -DROP FUNCTION IF EXISTS public.handle_new_auth_user() CASCADE; -DROP FUNCTION IF EXISTS public.get_direct_conversation_id(UUID, UUID) CASCADE; - -DROP TABLE IF EXISTS public.chat_settings CASCADE; -DROP TABLE IF EXISTS public.notifications CASCADE; -DROP TABLE IF EXISTS public.call_candidates CASCADE; -DROP TABLE IF EXISTS public.calls CASCADE; -DROP TABLE IF EXISTS public.stories CASCADE; -DROP TABLE IF EXISTS public.messages CASCADE; -DROP TABLE IF EXISTS public.conversation_participants CASCADE; -DROP TABLE IF EXISTS public.conversations CASCADE; -DROP TABLE IF EXISTS public.follows CASCADE; -DROP TABLE IF EXISTS public.users CASCADE; - --- 2. CREATE DATABASE TABLES +-- 2. TABLES (created only if missing) -- User Profiles (Integrated with auth.users) -CREATE TABLE public.users ( +CREATE TABLE IF NOT EXISTS public.users ( id UUID PRIMARY KEY REFERENCES auth.users ON DELETE CASCADE, email TEXT, phone TEXT, @@ -53,7 +41,7 @@ CREATE TABLE public.users ( ); -- Connections / Followers / Friends -CREATE TABLE public.follows ( +CREATE TABLE IF NOT EXISTS public.follows ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), follower_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, following_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, @@ -62,7 +50,7 @@ CREATE TABLE public.follows ( ); -- Conversation Rooms (Direct & Group chats) -CREATE TABLE public.conversations ( +CREATE TABLE IF NOT EXISTS public.conversations ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), type TEXT NOT NULL CHECK (type IN ('direct', 'group')), name TEXT, @@ -77,7 +65,7 @@ CREATE TABLE public.conversations ( ); -- Conversation Roster / Members -CREATE TABLE public.conversation_participants ( +CREATE TABLE IF NOT EXISTS public.conversation_participants ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), conversation_id UUID REFERENCES public.conversations(id) ON DELETE CASCADE NOT NULL, user_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, @@ -87,7 +75,7 @@ CREATE TABLE public.conversation_participants ( ); -- Chat Messages -CREATE TABLE public.messages ( +CREATE TABLE IF NOT EXISTS public.messages ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), conversation_id UUID REFERENCES public.conversations(id) ON DELETE CASCADE NOT NULL, sender_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, @@ -104,7 +92,7 @@ CREATE TABLE public.messages ( ); -- Stories & Status Updates -CREATE TABLE public.stories ( +CREATE TABLE IF NOT EXISTS public.stories ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, media_url TEXT, @@ -119,7 +107,7 @@ CREATE TABLE public.stories ( ); -- Voice / Video Calls -CREATE TABLE public.calls ( +CREATE TABLE IF NOT EXISTS public.calls ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), caller_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, receiver_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, @@ -132,7 +120,7 @@ CREATE TABLE public.calls ( ); -- WebRTC ICE Candidates Signaling -CREATE TABLE public.call_candidates ( +CREATE TABLE IF NOT EXISTS public.call_candidates ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), call_id UUID REFERENCES public.calls(id) ON DELETE CASCADE NOT NULL, user_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, @@ -142,7 +130,7 @@ CREATE TABLE public.call_candidates ( ); -- Personalized Chat Settings & Customizations -CREATE TABLE public.chat_settings ( +CREATE TABLE IF NOT EXISTS public.chat_settings ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, receiver_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, @@ -154,7 +142,7 @@ CREATE TABLE public.chat_settings ( ); -- System & Interaction Notifications -CREATE TABLE public.notifications ( +CREATE TABLE IF NOT EXISTS public.notifications ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, from_user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, @@ -166,7 +154,190 @@ CREATE TABLE public.notifications ( created_at TIMESTAMPTZ DEFAULT NOW() ); --- 3. ENABLE ROW LEVEL SECURITY (RLS) FOR CORE PRIVACY +-- 3. COLUMN UPGRADES +-- --------------------------------------------------------------------------- +-- A project created from an older version of this file can be missing columns +-- that were added later. `ADD COLUMN IF NOT EXISTS` makes every install converge +-- on the same shape without touching a single existing row. +-- --------------------------------------------------------------------------- + +ALTER TABLE public.users + ADD COLUMN IF NOT EXISTS email TEXT, + ADD COLUMN IF NOT EXISTS phone TEXT, + ADD COLUMN IF NOT EXISTS full_name TEXT, + ADD COLUMN IF NOT EXISTS username TEXT, + ADD COLUMN IF NOT EXISTS photo_url TEXT DEFAULT 'https://cdn-icons-png.flaticon.com/512/149/149071.png', + ADD COLUMN IF NOT EXISTS bio TEXT DEFAULT 'Available', + ADD COLUMN IF NOT EXISTS is_verified BOOLEAN DEFAULT FALSE, + ADD COLUMN IF NOT EXISTS profile_type TEXT DEFAULT 'personal', + ADD COLUMN IF NOT EXISTS is_online BOOLEAN DEFAULT FALSE, + ADD COLUMN IF NOT EXISTS last_seen TIMESTAMPTZ DEFAULT NOW(), + ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT NOW(), + ADD COLUMN IF NOT EXISTS settings JSONB DEFAULT '{}'::jsonb, + ADD COLUMN IF NOT EXISTS lock JSONB DEFAULT NULL, + ADD COLUMN IF NOT EXISTS blocked_users TEXT[] DEFAULT '{}'::text[], + ADD COLUMN IF NOT EXISTS muted_users TEXT[] DEFAULT '{}'::text[], + ADD COLUMN IF NOT EXISTS favorites TEXT[] DEFAULT '{}'::text[], + ADD COLUMN IF NOT EXISTS hidden_chats TEXT[] DEFAULT '{}'::text[], + ADD COLUMN IF NOT EXISTS archived_chats TEXT[] DEFAULT '{}'::text[], + ADD COLUMN IF NOT EXISTS hidden_chat_settings JSONB DEFAULT '{"secretCode": null, "showMenuEntry": true}'::jsonb, + ADD COLUMN IF NOT EXISTS fcm_tokens TEXT[] DEFAULT '{}'::text[]; + +ALTER TABLE public.follows + ADD COLUMN IF NOT EXISTS follower_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS following_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); + +ALTER TABLE public.conversations + ADD COLUMN IF NOT EXISTS type TEXT, + ADD COLUMN IF NOT EXISTS name TEXT, + ADD COLUMN IF NOT EXISTS photo_url TEXT, + ADD COLUMN IF NOT EXISTS admins UUID[] DEFAULT '{}'::uuid[], + ADD COLUMN IF NOT EXISTS watch_video_url TEXT, + ADD COLUMN IF NOT EXISTS watch_state JSONB DEFAULT '{}'::jsonb, + ADD COLUMN IF NOT EXISTS last_message TEXT, + ADD COLUMN IF NOT EXISTS last_message_at TIMESTAMPTZ, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(), + ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT NOW(); + +ALTER TABLE public.conversation_participants + ADD COLUMN IF NOT EXISTS conversation_id UUID REFERENCES public.conversations(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(), + ADD COLUMN IF NOT EXISTS joined_at TIMESTAMPTZ DEFAULT NOW(); + +ALTER TABLE public.messages + ADD COLUMN IF NOT EXISTS conversation_id UUID REFERENCES public.conversations(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS sender_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS text TEXT, + ADD COLUMN IF NOT EXISTS media_url TEXT, + ADD COLUMN IF NOT EXISTS media_type TEXT, + ADD COLUMN IF NOT EXISTS reply_to UUID REFERENCES public.messages(id) ON DELETE SET NULL, + ADD COLUMN IF NOT EXISTS reactions JSONB DEFAULT '{}'::jsonb, + ADD COLUMN IF NOT EXISTS is_read BOOLEAN DEFAULT FALSE, + ADD COLUMN IF NOT EXISTS is_edited BOOLEAN DEFAULT FALSE, + ADD COLUMN IF NOT EXISTS is_deleted BOOLEAN DEFAULT FALSE, + ADD COLUMN IF NOT EXISTS deleted_by UUID[] DEFAULT '{}'::UUID[], + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); + +ALTER TABLE public.stories + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS media_url TEXT, + ADD COLUMN IF NOT EXISTS type TEXT DEFAULT 'image', + ADD COLUMN IF NOT EXISTS text_content TEXT, + ADD COLUMN IF NOT EXISTS bg_color TEXT, + ADD COLUMN IF NOT EXISTS music_title TEXT, + ADD COLUMN IF NOT EXISTS music_artist TEXT, + ADD COLUMN IF NOT EXISTS music_url TEXT, + ADD COLUMN IF NOT EXISTS filter_applied TEXT, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); + +ALTER TABLE public.calls + ADD COLUMN IF NOT EXISTS caller_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS receiver_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS type TEXT, + ADD COLUMN IF NOT EXISTS status TEXT DEFAULT 'ringing', + ADD COLUMN IF NOT EXISTS offer JSONB, + ADD COLUMN IF NOT EXISTS answer JSONB, + ADD COLUMN IF NOT EXISTS is_missed BOOLEAN DEFAULT FALSE, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); + +ALTER TABLE public.call_candidates + ADD COLUMN IF NOT EXISTS call_id UUID REFERENCES public.calls(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS candidate JSONB, + ADD COLUMN IF NOT EXISTS type TEXT, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); + +ALTER TABLE public.chat_settings + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS receiver_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS nickname TEXT, + ADD COLUMN IF NOT EXISTS custom_photo_url TEXT, + ADD COLUMN IF NOT EXISTS is_muted BOOLEAN DEFAULT FALSE, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); + +ALTER TABLE public.notifications + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS from_user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS type TEXT, + ADD COLUMN IF NOT EXISTS title TEXT, + ADD COLUMN IF NOT EXISTS content TEXT, + ADD COLUMN IF NOT EXISTS is_read BOOLEAN DEFAULT FALSE, + ADD COLUMN IF NOT EXISTS post_id TEXT, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); + +-- NOT NULL is enforced only when the data already satisfies it, so an old table +-- with stray NULLs never makes this script abort. +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM public.users WHERE username IS NULL) THEN + ALTER TABLE public.users ALTER COLUMN username SET NOT NULL; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.follows WHERE follower_id IS NULL OR following_id IS NULL) THEN + ALTER TABLE public.follows ALTER COLUMN follower_id SET NOT NULL; + ALTER TABLE public.follows ALTER COLUMN following_id SET NOT NULL; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.conversations WHERE type IS NULL) THEN + ALTER TABLE public.conversations ALTER COLUMN type SET NOT NULL; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.conversation_participants WHERE conversation_id IS NULL OR user_id IS NULL) THEN + ALTER TABLE public.conversation_participants ALTER COLUMN conversation_id SET NOT NULL; + ALTER TABLE public.conversation_participants ALTER COLUMN user_id SET NOT NULL; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.messages WHERE conversation_id IS NULL OR sender_id IS NULL) THEN + ALTER TABLE public.messages ALTER COLUMN conversation_id SET NOT NULL; + ALTER TABLE public.messages ALTER COLUMN sender_id SET NOT NULL; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.stories WHERE user_id IS NULL) THEN + ALTER TABLE public.stories ALTER COLUMN user_id SET NOT NULL; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.calls WHERE caller_id IS NULL OR receiver_id IS NULL OR type IS NULL) THEN + ALTER TABLE public.calls ALTER COLUMN caller_id SET NOT NULL; + ALTER TABLE public.calls ALTER COLUMN receiver_id SET NOT NULL; + ALTER TABLE public.calls ALTER COLUMN type SET NOT NULL; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.chat_settings WHERE user_id IS NULL OR receiver_id IS NULL) THEN + ALTER TABLE public.chat_settings ALTER COLUMN user_id SET NOT NULL; + ALTER TABLE public.chat_settings ALTER COLUMN receiver_id SET NOT NULL; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.notifications WHERE user_id IS NULL OR type IS NULL) THEN + ALTER TABLE public.notifications ALTER COLUMN user_id SET NOT NULL; + ALTER TABLE public.notifications ALTER COLUMN type SET NOT NULL; + END IF; +END $$; + +-- 4. CONSTRAINTS +-- Added only when absent; a duplicate row in an old table produces a NOTICE +-- (never an abort) so the rest of the script still runs. +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint + WHERE conname = 'username_length_check' + AND conrelid = 'public.users'::regclass) THEN + ALTER TABLE public.users ADD CONSTRAINT username_length_check CHECK (char_length(username) <= 15); + END IF; + IF NOT EXISTS (SELECT 1 FROM pg_constraint + WHERE conname = 'follows_unique_pair' + AND conrelid = 'public.follows'::regclass) THEN + ALTER TABLE public.follows ADD CONSTRAINT follows_unique_pair UNIQUE (follower_id, following_id); + END IF; + IF NOT EXISTS (SELECT 1 FROM pg_constraint + WHERE conname = 'conversation_participants_unique_pair' + AND conrelid = 'public.conversation_participants'::regclass) THEN + ALTER TABLE public.conversation_participants ADD CONSTRAINT conversation_participants_unique_pair UNIQUE (conversation_id, user_id); + END IF; + IF NOT EXISTS (SELECT 1 FROM pg_constraint + WHERE conname = 'chat_settings_unique_pair' + AND conrelid = 'public.chat_settings'::regclass) THEN + ALTER TABLE public.chat_settings ADD CONSTRAINT chat_settings_unique_pair UNIQUE (user_id, receiver_id); + END IF; +EXCEPTION WHEN OTHERS THEN + RAISE NOTICE 'Constraint skipped (%): existing rows violate it', SQLERRM; +END $$; + +-- 5. ENABLE ROW LEVEL SECURITY (CORE PRIVACY) + ALTER TABLE public.users ENABLE ROW LEVEL SECURITY; ALTER TABLE public.follows ENABLE ROW LEVEL SECURITY; ALTER TABLE public.conversations ENABLE ROW LEVEL SECURITY; @@ -178,20 +349,28 @@ ALTER TABLE public.call_candidates ENABLE ROW LEVEL SECURITY; ALTER TABLE public.chat_settings ENABLE ROW LEVEL SECURITY; ALTER TABLE public.notifications ENABLE ROW LEVEL SECURITY; --- 4. CREATE RLS SECURE POLICIES +-- 6. RLS POLICIES (re-created on every run, so edits apply) -- profiles +DROP POLICY IF EXISTS "Allow public read access on profiles" ON public.users; CREATE POLICY "Allow public read access on profiles" ON public.users FOR SELECT USING (true); +DROP POLICY IF EXISTS "Allow users to update own profile" ON public.users; CREATE POLICY "Allow users to update own profile" ON public.users FOR UPDATE USING (auth.uid() = id) WITH CHECK (auth.uid() = id); +DROP POLICY IF EXISTS "Allow users to insert own profile" ON public.users; CREATE POLICY "Allow users to insert own profile" ON public.users FOR INSERT WITH CHECK (auth.uid() = id); -- connections +DROP POLICY IF EXISTS "Allow users to view all follows" ON public.follows; CREATE POLICY "Allow users to view all follows" ON public.follows FOR SELECT USING (true); +DROP POLICY IF EXISTS "Allow users to follow others" ON public.follows; CREATE POLICY "Allow users to follow others" ON public.follows FOR INSERT WITH CHECK (auth.uid() = follower_id); +DROP POLICY IF EXISTS "Allow users to unfollow others" ON public.follows; CREATE POLICY "Allow users to unfollow others" ON public.follows FOR DELETE USING (auth.uid() = follower_id); -- conversations +DROP POLICY IF EXISTS "Allow auth users to make conversations" ON public.conversations; CREATE POLICY "Allow auth users to make conversations" ON public.conversations FOR INSERT WITH CHECK (auth.role() = 'authenticated'); +DROP POLICY IF EXISTS "Allow members to see conversations" ON public.conversations; CREATE POLICY "Allow members to see conversations" ON public.conversations FOR SELECT USING ( EXISTS ( SELECT 1 FROM public.conversation_participants @@ -199,6 +378,7 @@ CREATE POLICY "Allow members to see conversations" ON public.conversations FOR S AND conversation_participants.user_id = auth.uid() ) ); +DROP POLICY IF EXISTS "Allow participants to edit conversations" ON public.conversations; CREATE POLICY "Allow participants to edit conversations" ON public.conversations FOR UPDATE USING ( EXISTS ( SELECT 1 FROM public.conversation_participants @@ -206,6 +386,7 @@ CREATE POLICY "Allow participants to edit conversations" ON public.conversations AND conversation_participants.user_id = auth.uid() ) ); +DROP POLICY IF EXISTS "Allow participants to delete conversations" ON public.conversations; CREATE POLICY "Allow participants to delete conversations" ON public.conversations FOR DELETE USING ( EXISTS ( SELECT 1 FROM public.conversation_participants @@ -215,11 +396,15 @@ CREATE POLICY "Allow participants to delete conversations" ON public.conversatio ); -- members +DROP POLICY IF EXISTS "Allow auth users to inspect participants" ON public.conversation_participants; CREATE POLICY "Allow auth users to inspect participants" ON public.conversation_participants FOR SELECT USING (true); +DROP POLICY IF EXISTS "Allow members to join rooms" ON public.conversation_participants; CREATE POLICY "Allow members to join rooms" ON public.conversation_participants FOR INSERT WITH CHECK (auth.role() = 'authenticated'); +DROP POLICY IF EXISTS "Allow participants to leave rooms" ON public.conversation_participants; CREATE POLICY "Allow participants to leave rooms" ON public.conversation_participants FOR DELETE USING (auth.role() = 'authenticated'); -- messages +DROP POLICY IF EXISTS "Allow conversation members to view messages" ON public.messages; CREATE POLICY "Allow conversation members to view messages" ON public.messages FOR SELECT USING ( EXISTS ( SELECT 1 FROM public.conversation_participants @@ -227,6 +412,7 @@ CREATE POLICY "Allow conversation members to view messages" ON public.messages F AND conversation_participants.user_id = auth.uid() ) ); +DROP POLICY IF EXISTS "Allow active members to insert messages" ON public.messages; CREATE POLICY "Allow active members to insert messages" ON public.messages FOR INSERT WITH CHECK ( auth.uid() = sender_id AND EXISTS ( @@ -235,6 +421,7 @@ CREATE POLICY "Allow active members to insert messages" ON public.messages FOR I AND conversation_participants.user_id = auth.uid() ) ); +DROP POLICY IF EXISTS "Allow participants to update messages" ON public.messages; CREATE POLICY "Allow participants to update messages" ON public.messages FOR UPDATE USING ( EXISTS ( SELECT 1 FROM public.conversation_participants @@ -242,6 +429,7 @@ CREATE POLICY "Allow participants to update messages" ON public.messages FOR UPD AND conversation_participants.user_id = auth.uid() ) ); +DROP POLICY IF EXISTS "Allow participants to delete messages" ON public.messages; CREATE POLICY "Allow participants to delete messages" ON public.messages FOR DELETE USING ( EXISTS ( SELECT 1 FROM public.conversation_participants @@ -251,16 +439,23 @@ CREATE POLICY "Allow participants to delete messages" ON public.messages FOR DEL ); -- stories +DROP POLICY IF EXISTS "Allow auth users to view stories" ON public.stories; CREATE POLICY "Allow auth users to view stories" ON public.stories FOR SELECT USING (auth.role() = 'authenticated'); +DROP POLICY IF EXISTS "Allow owners to publish stories" ON public.stories; CREATE POLICY "Allow owners to publish stories" ON public.stories FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Allow owners to delete stories" ON public.stories; CREATE POLICY "Allow owners to delete stories" ON public.stories FOR DELETE USING (auth.uid() = user_id); -- calling +DROP POLICY IF EXISTS "Allow view access to call records" ON public.calls; CREATE POLICY "Allow view access to call records" ON public.calls FOR SELECT USING (auth.uid() = caller_id OR auth.uid() = receiver_id); +DROP POLICY IF EXISTS "Allow calls insertion to caller" ON public.calls; CREATE POLICY "Allow calls insertion to caller" ON public.calls FOR INSERT WITH CHECK (auth.uid() = caller_id); +DROP POLICY IF EXISTS "Allow call updates on participants" ON public.calls; CREATE POLICY "Allow call updates on participants" ON public.calls FOR UPDATE USING (auth.uid() = caller_id OR auth.uid() = receiver_id); -- signaling Candidates +DROP POLICY IF EXISTS "Allow select on candidates to call members" ON public.call_candidates; CREATE POLICY "Allow select on candidates to call members" ON public.call_candidates FOR SELECT USING ( EXISTS ( SELECT 1 FROM public.calls @@ -268,6 +463,7 @@ CREATE POLICY "Allow select on candidates to call members" ON public.call_candid AND (calls.caller_id = auth.uid() OR calls.receiver_id = auth.uid()) ) ); +DROP POLICY IF EXISTS "Allow call participants to insert candidates" ON public.call_candidates; CREATE POLICY "Allow call participants to insert candidates" ON public.call_candidates FOR INSERT WITH CHECK ( auth.uid() = user_id AND EXISTS ( @@ -278,16 +474,22 @@ CREATE POLICY "Allow call participants to insert candidates" ON public.call_cand ); -- custom chat settings +DROP POLICY IF EXISTS "Allow users to read own chat settings" ON public.chat_settings; CREATE POLICY "Allow users to read own chat settings" ON public.chat_settings FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Allow users to modify own chat settings" ON public.chat_settings; CREATE POLICY "Allow users to modify own chat settings" ON public.chat_settings FOR ALL USING (auth.uid() = user_id); -- user notifications +DROP POLICY IF EXISTS "Allow users to read own notifications" ON public.notifications; CREATE POLICY "Allow users to read own notifications" ON public.notifications FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Allow auth users system to insert notifications" ON public.notifications; CREATE POLICY "Allow auth users system to insert notifications" ON public.notifications FOR INSERT WITH CHECK (auth.role() = 'authenticated'); +DROP POLICY IF EXISTS "Allow users to update own notifications" ON public.notifications; CREATE POLICY "Allow users to update own notifications" ON public.notifications FOR UPDATE USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Allow users to delete own notifications" ON public.notifications; CREATE POLICY "Allow users to delete own notifications" ON public.notifications FOR DELETE USING (auth.uid() = user_id); --- 5. PERFORMANCE AND SEARCH INDEXES +-- 7. PERFORMANCE AND SEARCH INDEXES CREATE INDEX IF NOT EXISTS idx_messages_conversation ON public.messages(conversation_id); CREATE INDEX IF NOT EXISTS idx_messages_created_at ON public.messages(created_at DESC); CREATE INDEX IF NOT EXISTS idx_participants_user ON public.conversation_participants(user_id); diff --git a/sql/02_posts_and_interactions_schema.sql b/sql/02_posts_and_interactions_schema.sql index 68dfa6a..5e3aaf0 100644 --- a/sql/02_posts_and_interactions_schema.sql +++ b/sql/02_posts_and_interactions_schema.sql @@ -1,17 +1,13 @@ -- ========================================================================= --- STEP 2: GRIXCHAT POSTS, LIKES, AND COMMENTS SCHEMAS +-- STEP 2/9: POSTS, LIKES AND COMMENTS -- ========================================================================= --- Instructions: --- 1. Execute this file in your Supabase SQL Editor AFTER running Step 1. +-- Run in the Supabase SQL Editor after 01_core_schema.sql. +-- Safe to re-run: nothing is dropped, missing tables/columns/policies are +-- created, existing rows are untouched. -- ========================================================================= --- Clear existing tables if recreating -DROP TABLE IF EXISTS public.post_comments CASCADE; -DROP TABLE IF EXISTS public.post_likes CASCADE; -DROP TABLE IF EXISTS public.posts CASCADE; - -- 1. Create Posts Table -CREATE TABLE public.posts ( +CREATE TABLE IF NOT EXISTS public.posts ( id UUID DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, image_url TEXT NOT NULL, @@ -23,21 +19,21 @@ CREATE TABLE public.posts ( ALTER TABLE public.posts ENABLE ROW LEVEL SECURITY; -- Post Policies -CREATE POLICY "Allow public read access for posts" -ON public.posts FOR SELECT +DROP POLICY IF EXISTS "Allow public read access for posts" ON public.posts; +CREATE POLICY "Allow public read access for posts" ON public.posts FOR SELECT USING (true); -CREATE POLICY "Allow authenticated insert for posts" -ON public.posts FOR INSERT +DROP POLICY IF EXISTS "Allow authenticated insert for posts" ON public.posts; +CREATE POLICY "Allow authenticated insert for posts" ON public.posts FOR INSERT WITH CHECK (auth.uid() = user_id); -CREATE POLICY "Allow users to delete their own posts" -ON public.posts FOR DELETE +DROP POLICY IF EXISTS "Allow users to delete their own posts" ON public.posts; +CREATE POLICY "Allow users to delete their own posts" ON public.posts FOR DELETE USING (auth.uid() = user_id); -- 2. Create Post Likes Table (Tracking active likes) -CREATE TABLE public.post_likes ( +CREATE TABLE IF NOT EXISTS public.post_likes ( post_id UUID REFERENCES public.posts(id) ON DELETE CASCADE, user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL, @@ -48,21 +44,21 @@ CREATE TABLE public.post_likes ( ALTER TABLE public.post_likes ENABLE ROW LEVEL SECURITY; -- Post Likes Policies -CREATE POLICY "Allow public read access for post likes" -ON public.post_likes FOR SELECT +DROP POLICY IF EXISTS "Allow public read access for post likes" ON public.post_likes; +CREATE POLICY "Allow public read access for post likes" ON public.post_likes FOR SELECT USING (true); -CREATE POLICY "Allow authenticated insert for post likes" -ON public.post_likes FOR INSERT +DROP POLICY IF EXISTS "Allow authenticated insert for post likes" ON public.post_likes; +CREATE POLICY "Allow authenticated insert for post likes" ON public.post_likes FOR INSERT WITH CHECK (auth.uid() = user_id); -CREATE POLICY "Allow users to remove their likes" -ON public.post_likes FOR DELETE +DROP POLICY IF EXISTS "Allow users to remove their likes" ON public.post_likes; +CREATE POLICY "Allow users to remove their likes" ON public.post_likes FOR DELETE USING (auth.uid() = user_id); -- 3. Create Post Comments Table -CREATE TABLE public.post_comments ( +CREATE TABLE IF NOT EXISTS public.post_comments ( id UUID DEFAULT gen_random_uuid() PRIMARY KEY, post_id UUID REFERENCES public.posts(id) ON DELETE CASCADE, user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, @@ -74,16 +70,16 @@ CREATE TABLE public.post_comments ( ALTER TABLE public.post_comments ENABLE ROW LEVEL SECURITY; -- Post Comments Policies -CREATE POLICY "Allow public read access for post comments" -ON public.post_comments FOR SELECT +DROP POLICY IF EXISTS "Allow public read access for post comments" ON public.post_comments; +CREATE POLICY "Allow public read access for post comments" ON public.post_comments FOR SELECT USING (true); -CREATE POLICY "Allow authenticated insert for post comments" -ON public.post_comments FOR INSERT +DROP POLICY IF EXISTS "Allow authenticated insert for post comments" ON public.post_comments; +CREATE POLICY "Allow authenticated insert for post comments" ON public.post_comments FOR INSERT WITH CHECK (auth.uid() = user_id); -CREATE POLICY "Allow users to delete their own comments" -ON public.post_comments FOR DELETE +DROP POLICY IF EXISTS "Allow users to delete their own comments" ON public.post_comments; +CREATE POLICY "Allow users to delete their own comments" ON public.post_comments FOR DELETE USING (auth.uid() = user_id); -- Performance Indexes @@ -91,5 +87,34 @@ CREATE INDEX IF NOT EXISTS idx_posts_user_id ON public.posts(user_id); CREATE INDEX IF NOT EXISTS idx_post_likes_post_id ON public.post_likes(post_id); CREATE INDEX IF NOT EXISTS idx_post_comments_post_id ON public.post_comments(post_id); +-- Column upgrades: a project created from an older version of this file may be +-- missing columns added later. No existing row is touched. +ALTER TABLE public.posts + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS image_url TEXT, + ADD COLUMN IF NOT EXISTS caption TEXT, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()); + +ALTER TABLE public.post_likes + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()); + +ALTER TABLE public.post_comments + ADD COLUMN IF NOT EXISTS post_id UUID REFERENCES public.posts(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS text TEXT, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()); + +-- Primary key of post_likes is (post_id, user_id); add it only if it is absent. +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint + WHERE conname = 'post_likes_pkey' + AND conrelid = 'public.post_likes'::regclass) THEN + ALTER TABLE public.post_likes ADD CONSTRAINT post_likes_pkey PRIMARY KEY (post_id, user_id); + END IF; +EXCEPTION WHEN OTHERS THEN + RAISE NOTICE 'post_likes primary key skipped: %', SQLERRM; +END $$; + -- Reload Schema NOTIFY pgrst, 'reload schema'; diff --git a/sql/03_support_tickets_schema.sql b/sql/03_support_tickets_schema.sql index 7f74e3c..596ce2c 100644 --- a/sql/03_support_tickets_schema.sql +++ b/sql/03_support_tickets_schema.sql @@ -1,15 +1,12 @@ -- ========================================================================= --- STEP 3: GRIXCHAT SUPPORT AND BACKSIDE CONTACT TICKETS +-- STEP 3/9: SUPPORT TICKETS -- ========================================================================= --- Instructions: --- 1. Execute this file in your Supabase SQL Editor AFTER running Step 2. +-- Run in the Supabase SQL Editor after 02_posts_and_interactions_schema.sql. +-- Safe to re-run: nothing is dropped, existing tickets are kept. -- ========================================================================= --- Clear existing table -DROP TABLE IF EXISTS public.support_tickets CASCADE; - -- Create support tickets Table -CREATE TABLE public.support_tickets ( +CREATE TABLE IF NOT EXISTS public.support_tickets ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID REFERENCES public.users(id) ON DELETE SET NULL, email TEXT NOT NULL, @@ -21,18 +18,29 @@ CREATE TABLE public.support_tickets ( updated_at TIMESTAMPTZ DEFAULT NOW() ); +-- Column upgrades for older installs (no existing row is touched). +ALTER TABLE public.support_tickets + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE SET NULL, + ADD COLUMN IF NOT EXISTS email TEXT, + ADD COLUMN IF NOT EXISTS category TEXT, + ADD COLUMN IF NOT EXISTS subject TEXT, + ADD COLUMN IF NOT EXISTS message TEXT, + ADD COLUMN IF NOT EXISTS status TEXT DEFAULT 'open', + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(), + ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT NOW(); + -- Enable Row Level Security (RLS) ALTER TABLE public.support_tickets ENABLE ROW LEVEL SECURITY; -- 1. Anonymous and Authenticated submittals -CREATE POLICY "Allow anonymous and authenticated ticket insertion" - ON public.support_tickets +DROP POLICY IF EXISTS "Allow anonymous and authenticated ticket insertion" ON public.support_tickets; +CREATE POLICY "Allow anonymous and authenticated ticket insertion" ON public.support_tickets FOR INSERT WITH CHECK (true); -- 2. Fetch logged tickets -CREATE POLICY "Allow users to view own tickets" - ON public.support_tickets +DROP POLICY IF EXISTS "Allow users to view own tickets" ON public.support_tickets; +CREATE POLICY "Allow users to view own tickets" ON public.support_tickets FOR SELECT USING (auth.uid() = user_id); diff --git a/sql/04_triggers_functions_and_rpc.sql b/sql/04_triggers_functions_and_rpc.sql index 31c2df9..7fdcf20 100644 --- a/sql/04_triggers_functions_and_rpc.sql +++ b/sql/04_triggers_functions_and_rpc.sql @@ -1,8 +1,11 @@ -- ========================================================================= --- STEP 4: DATABASE SYSTEMS - RPC FUNCTIONS, TRIGGERS & PROFILES AUTO-SYNC +-- STEP 4/9: RPC FUNCTIONS, TRIGGERS & AUTH -> PROFILE AUTO-SYNC -- ========================================================================= --- Instructions: --- 1. Execute this file in your Supabase SQL Editor AFTER running Step 3. +-- Run in the Supabase SQL Editor after 03_support_tickets_schema.sql. +-- Safe to re-run: the trigger and the functions are dropped and re-created, so +-- an updated definition always replaces the old one. No row is ever deleted. +-- (`DROP FUNCTION` cannot lose the trigger's target: the trigger is dropped +-- first, in the same run.) -- ========================================================================= -- Clear existing Triggers & Functions @@ -29,7 +32,7 @@ BEGIN RETURN conv_id; END; -$$ LANGUAGE plpgsql SECURITY DEFINER; +$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public; -- 2. Auth to Public user profiles sync (Essential for Signup and OAuth sign-in) @@ -84,7 +87,7 @@ BEGIN RETURN NEW; END; -$$ LANGUAGE plpgsql SECURITY DEFINER; +$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public; -- Bind trigger on auth.users (Runs completely on auth signup) CREATE TRIGGER on_auth_user_created diff --git a/sql/05_advanced_optimizations_and_realtime.sql b/sql/05_advanced_optimizations_and_realtime.sql index 6986b83..eea628e 100644 --- a/sql/05_advanced_optimizations_and_realtime.sql +++ b/sql/05_advanced_optimizations_and_realtime.sql @@ -1,10 +1,15 @@ -- ========================================================================= --- STEP 5: PERFORMANCE OPTIMIZATION, REAL-TIME QUEUES, AND AUTOMATED PRUNING +-- STEP 5/9: REALTIME PUBLICATION, PREVIEW TRIGGERS, HISTORY CAP -- ========================================================================= --- Instructions: --- 1. Execute this file in your Supabase SQL Editor AFTER running Step 4. --- 2. This step guarantees that your Supabase databases remain lightweight, --- enables immediate push updates, and cleans up historical records. +-- Run in the Supabase SQL Editor after 04_triggers_functions_and_rpc.sql. +-- Safe to re-run: functions are CREATE OR REPLACE, triggers are dropped first, +-- replica identity and publication membership are re-asserted. +-- +-- ⚠️ READ THIS BEFORE RUNNING — sections 1 and 6 DELETE MESSAGE HISTORY: +-- every chat is capped at 60 rows, pruned back to the newest 40, on every +-- insert. It keeps a free-tier project small, but it also means chat history +-- is not kept. To keep history instead: do NOT run sections 1 and 6, and use +-- the time-based pruner in 09_egress_optimizations.sql (`prune_old_messages`). -- ========================================================================= -- 1. MESSAGE CAP PRUNER (LIMITS ROOMS TO LAST 60 MESSAGES - PRUNES TO 40) @@ -116,73 +121,79 @@ FOR EACH ROW EXECUTE FUNCTION prune_past_calls(); --- 4. REAL-TIME MULTICAST CHANNEL IDENTITY ENABLEMENTS -ALTER TABLE public.users REPLICA IDENTITY FULL; -ALTER TABLE public.messages REPLICA IDENTITY FULL; -ALTER TABLE public.conversations REPLICA IDENTITY FULL; -ALTER TABLE public.calls REPLICA IDENTITY FULL; -ALTER TABLE public.call_candidates REPLICA IDENTITY FULL; - - --- 5. SUPABASE WebSocket Realtime Publication Bindings +-- 4. REPLICA IDENTITY +-- --------------------------------------------------------------------------- +-- FULL is only needed where the client filters DELETEs by a non-key column +-- (`conversation_id=eq.…` on messages and conversation_participants). Everywhere +-- else DEFAULT keeps UPDATE payloads to "new row + primary key", which stops +-- whole rows — including `users.lock`, the app-lock passcode hash, and +-- `fcm_tokens` — from being broadcast to every subscribed client. +-- 09_egress_optimizations.sql re-asserts the same values, so either file leaves +-- the database in this state. +-- --------------------------------------------------------------------------- DO $$ +DECLARE + target RECORD; BEGIN - -- Check and drop pre-existing tables from the publication to prevent duplicate key errors - IF EXISTS ( - SELECT 1 FROM pg_publication_tables - WHERE pubname = 'supabase_realtime' - AND schemaname = 'public' - AND tablename = 'messages' - ) THEN - ALTER PUBLICATION supabase_realtime DROP TABLE public.messages; - END IF; + FOR target IN + SELECT * FROM (VALUES + ('users', 'DEFAULT'), + ('conversations', 'DEFAULT'), + ('calls', 'DEFAULT'), + ('call_candidates', 'DEFAULT'), + ('messages', 'FULL'), + ('conversation_participants','FULL') + ) AS t(tbl, identity) + LOOP + IF EXISTS (SELECT 1 FROM pg_class c + JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname = target.tbl) THEN + EXECUTE format('ALTER TABLE public.%I REPLICA IDENTITY %s', target.tbl, target.identity); + END IF; + END LOOP; +END; +$$; - IF EXISTS ( - SELECT 1 FROM pg_publication_tables - WHERE pubname = 'supabase_realtime' - AND schemaname = 'public' - AND tablename = 'conversations' - ) THEN - ALTER PUBLICATION supabase_realtime DROP TABLE public.conversations; - END IF; - IF EXISTS ( - SELECT 1 FROM pg_publication_tables - WHERE pubname = 'supabase_realtime' - AND schemaname = 'public' - AND tablename = 'users' - ) THEN - ALTER PUBLICATION supabase_realtime DROP TABLE public.users; - END IF; - - IF EXISTS ( - SELECT 1 FROM pg_publication_tables - WHERE pubname = 'supabase_realtime' - AND schemaname = 'public' - AND tablename = 'calls' - ) THEN - ALTER PUBLICATION supabase_realtime DROP TABLE public.calls; +-- 5. SUPABASE REALTIME PUBLICATION MEMBERSHIP +-- --------------------------------------------------------------------------- +-- Only the tables the client actually subscribes to. Membership is idempotent: +-- a table is added only when it exists and is not already published, so a run +-- over an existing project changes nothing and a fork that dropped a table +-- (e.g. call_candidates) does not abort the script. +-- --------------------------------------------------------------------------- +DO $$ +DECLARE + tbl TEXT; +BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_publication WHERE pubname = 'supabase_realtime') THEN + CREATE PUBLICATION supabase_realtime; END IF; - IF EXISTS ( - SELECT 1 FROM pg_publication_tables - WHERE pubname = 'supabase_realtime' - AND schemaname = 'public' - AND tablename = 'call_candidates' - ) THEN - ALTER PUBLICATION supabase_realtime DROP TABLE public.call_candidates; - END IF; -END $$; + FOREACH tbl IN ARRAY ARRAY[ + 'messages', 'conversations', 'users', 'calls', + 'call_candidates', 'conversation_participants' + ] LOOP + IF to_regclass('public.' || tbl) IS NOT NULL + AND NOT EXISTS (SELECT 1 FROM pg_publication_tables + WHERE pubname = 'supabase_realtime' + AND schemaname = 'public' + AND tablename = tbl) THEN + EXECUTE format('ALTER PUBLICATION supabase_realtime ADD TABLE public.%I', tbl); + END IF; + END LOOP; +END; +$$; --- Enable Realtime for key instant replication tables -ALTER PUBLICATION supabase_realtime ADD TABLE public.messages; -ALTER PUBLICATION supabase_realtime ADD TABLE public.conversations; -ALTER PUBLICATION supabase_realtime ADD TABLE public.users; -ALTER PUBLICATION supabase_realtime ADD TABLE public.calls; -ALTER PUBLICATION supabase_realtime ADD TABLE public.call_candidates; +-- Also enable Realtime in the dashboard for these tables: +-- Database -> Replication -> supabase_realtime +-- The SQL above registers the tables; the dashboard toggle is what actually +-- streams them. --- 6. RETROACTIVE SWEEP (Instantly trims pre-existing high-volume tables down to 40 records) +-- 6. RETROACTIVE SWEEP (trims pre-existing high-volume tables down to 40 rows) +-- Same policy as section 1: it keeps the newest 40 messages per chat and the +-- newest 40 calls per user. Skip this section if you skipped section 1. DO $$ DECLARE u_rec RECORD; diff --git a/sql/06_storage_configurations.sql b/sql/06_storage_configurations.sql index ae8025a..4849265 100644 --- a/sql/06_storage_configurations.sql +++ b/sql/06_storage_configurations.sql @@ -1,11 +1,15 @@ -- ========================================================================= --- STEP 6: SUPABASE STORAGE BUCKETS SETUP AND SECURITY POLICIES +-- STEP 6/9: STORAGE BUCKETS (chat-media, profiles) AND THEIR POLICIES -- ========================================================================= --- Instructions: --- 1. Execute this file in your Supabase SQL Editor AFTER running Step 5. --- 2. This step registers 'chat-media' and 'profiles' buckets and sets up --- Row-Level Security (RLS) on storage.objects, allowing authenticated --- users to upload and delete media while permitting public access. +-- Run in the Supabase SQL Editor after 05_advanced_optimizations_and_realtime.sql. +-- Safe to re-run: buckets are inserted with ON CONFLICT DO NOTHING and every +-- policy is dropped and re-created, so an updated definition always wins. +-- +-- ⚠️ These policies are deliberately permissive (public read, any authenticated +-- user may upload/update/delete in these buckets) because the app uploads to +-- `chat-media/images/_.` — paths carry no user id, so +-- ownership cannot be checked from the path. Hardening notes: +-- docs/EGRESS_AUDIT.md §6 and the commented block in 09_egress_optimizations.sql. -- ========================================================================= -- 1. PROVISION BUCKETS (If they do not already exist) diff --git a/sql/09_egress_optimizations.sql b/sql/09_egress_optimizations.sql index bb7981d..f027502 100644 --- a/sql/09_egress_optimizations.sql +++ b/sql/09_egress_optimizations.sql @@ -90,8 +90,20 @@ BEGIN END IF; END IF; - -- Slow path: a delete, a soft delete, or an edit of an older message. The - -- preview has to be re-derived from what is left. + -- Fast skip for DELETEs: if the conversation already shows something newer, + -- removing an older row cannot change the preview. This is the common case + -- for the 40-message history cap in 05, which deletes a batch per insert. + IF TG_OP = 'DELETE' AND EXISTS ( + SELECT 1 FROM public.conversations + WHERE id = target_conversation + AND last_message_at IS NOT NULL + AND last_message_at > OLD.created_at + ) THEN + RETURN NULL; + END IF; + + -- Slow path: a delete of the newest row, a soft delete, or an edit of an + -- older message. The preview has to be re-derived from what is left. SELECT m.text, m.media_type, m.created_at, m.sender_id, m.is_deleted INTO newest FROM public.messages m @@ -167,10 +179,11 @@ DECLARE BEGIN FOR target IN SELECT * FROM (VALUES - ('users', 'DEFAULT'), - ('conversations', 'DEFAULT'), - ('calls', 'DEFAULT'), - ('messages', 'FULL'), + ('users', 'DEFAULT'), + ('conversations', 'DEFAULT'), + ('calls', 'DEFAULT'), + ('call_candidates', 'DEFAULT'), + ('messages', 'FULL'), ('conversation_participants','FULL') ) AS t(tbl, identity) LOOP diff --git a/sql/grixchat_full_setup.sql b/sql/grixchat_full_setup.sql new file mode 100644 index 0000000..172fac1 --- /dev/null +++ b/sql/grixchat_full_setup.sql @@ -0,0 +1,1626 @@ +-- ══════════════════════════════════════════════════════════════════════════ +-- GRIXCHAT — COMPLETE SUPABASE SETUP (generated, do not edit by hand) +-- ══════════════════════════════════════════════════════════════════════════ +-- One paste for a brand-new Supabase project: +-- Supabase Dashboard -> SQL Editor -> New query -> paste ALL of this -> RUN. +-- +-- Safe to run again later, on the same project, at any time: +-- * nothing is dropped or truncated +-- * tables/columns/indexes/constraints are created only when missing +-- * policies and functions are re-created, so updated definitions apply +-- * existing rows are never modified +-- +-- Generated by: npm run sql:bundle (source: sql/01_*.sql … sql/09_*.sql) +-- Read first: sql/00_master_instructions.md +-- ══════════════════════════════════════════════════════════════════════════ + + +-- ══════════════════════════════════════════════════════════════════════════ +-- PART 1/9 — sql/01_core_schema.sql +-- (generated from the file of that name; edit THAT file, then re-run +-- "npm run sql:bundle" — do not edit this bundle by hand) +-- ══════════════════════════════════════════════════════════════════════════ + +-- ========================================================================= +-- STEP 1/9: GRIXCHAT CORE SCHEMA (users, chats, messages, calls, ...) +-- ========================================================================= +-- Supabase Dashboard -> SQL Editor -> New query -> paste -> RUN. +-- Then continue with 02, 03, ... 09 in order (see 00_master_instructions.md). +-- +-- SAFE TO RE-RUN, ON A FRESH PROJECT AND ON A LIVE ONE: +-- * nothing is dropped or truncated — no `DROP TABLE`, ever +-- * tables are created only if missing, missing columns/indexes/constraints +-- are added, policies are re-created so an updated definition replaces the +-- old one +-- * existing rows are never modified by this file +-- ========================================================================= + +-- 2. TABLES (created only if missing) + +-- User Profiles (Integrated with auth.users) +CREATE TABLE IF NOT EXISTS public.users ( + id UUID PRIMARY KEY REFERENCES auth.users ON DELETE CASCADE, + email TEXT, + phone TEXT, + full_name TEXT, + username TEXT UNIQUE NOT NULL, + photo_url TEXT DEFAULT 'https://cdn-icons-png.flaticon.com/512/149/149071.png', + bio TEXT DEFAULT 'Available', + is_verified BOOLEAN DEFAULT FALSE, + profile_type TEXT DEFAULT 'personal', + is_online BOOLEAN DEFAULT FALSE, + last_seen TIMESTAMPTZ DEFAULT NOW(), + updated_at TIMESTAMPTZ DEFAULT NOW(), + settings JSONB DEFAULT '{}'::jsonb, + lock JSONB DEFAULT NULL, -- Passcode lock hash & configuration + blocked_users TEXT[] DEFAULT '{}'::text[], + muted_users TEXT[] DEFAULT '{}'::text[], + favorites TEXT[] DEFAULT '{}'::text[], + hidden_chats TEXT[] DEFAULT '{}'::text[], + archived_chats TEXT[] DEFAULT '{}'::text[], + hidden_chat_settings JSONB DEFAULT '{"secretCode": null, "showMenuEntry": true}'::jsonb, + fcm_tokens TEXT[] DEFAULT '{}'::text[], + CONSTRAINT username_length_check CHECK (char_length(username) <= 15) +); + +-- Connections / Followers / Friends +CREATE TABLE IF NOT EXISTS public.follows ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + follower_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, + following_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, + created_at TIMESTAMPTZ DEFAULT NOW(), + CONSTRAINT follows_unique_pair UNIQUE (follower_id, following_id) +); + +-- Conversation Rooms (Direct & Group chats) +CREATE TABLE IF NOT EXISTS public.conversations ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + type TEXT NOT NULL CHECK (type IN ('direct', 'group')), + name TEXT, + photo_url TEXT, + admins UUID[] DEFAULT '{}'::uuid[], + watch_video_url TEXT, + watch_state JSONB DEFAULT '{}'::jsonb, + last_message TEXT, + last_message_at TIMESTAMPTZ, + created_at TIMESTAMPTZ DEFAULT NOW(), + updated_at TIMESTAMPTZ DEFAULT NOW() +); + +-- Conversation Roster / Members +CREATE TABLE IF NOT EXISTS public.conversation_participants ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + conversation_id UUID REFERENCES public.conversations(id) ON DELETE CASCADE NOT NULL, + user_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, + created_at TIMESTAMPTZ DEFAULT NOW(), + joined_at TIMESTAMPTZ DEFAULT NOW(), + CONSTRAINT conversation_participants_unique_pair UNIQUE (conversation_id, user_id) +); + +-- Chat Messages +CREATE TABLE IF NOT EXISTS public.messages ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + conversation_id UUID REFERENCES public.conversations(id) ON DELETE CASCADE NOT NULL, + sender_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, + text TEXT, + media_url TEXT, + media_type TEXT, + reply_to UUID REFERENCES public.messages(id) ON DELETE SET NULL, + reactions JSONB DEFAULT '{}'::jsonb, + is_read BOOLEAN DEFAULT FALSE, + is_edited BOOLEAN DEFAULT FALSE, + is_deleted BOOLEAN DEFAULT FALSE, + deleted_by UUID[] DEFAULT '{}'::UUID[], -- Tracks delete for me IDs + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- Stories & Status Updates +CREATE TABLE IF NOT EXISTS public.stories ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, + media_url TEXT, + type TEXT DEFAULT 'image', -- 'image', 'text', 'video' + text_content TEXT, + bg_color TEXT, + music_title TEXT, + music_artist TEXT, + music_url TEXT, + filter_applied TEXT, + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- Voice / Video Calls +CREATE TABLE IF NOT EXISTS public.calls ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + caller_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, + receiver_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, + type TEXT CHECK (type IN ('audio', 'video')) NOT NULL, + status TEXT DEFAULT 'ringing' CHECK (status IN ('ringing', 'accepted', 'rejected', 'ended', 'error')), + offer JSONB, + answer JSONB, + is_missed BOOLEAN DEFAULT FALSE, + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- WebRTC ICE Candidates Signaling +CREATE TABLE IF NOT EXISTS public.call_candidates ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + call_id UUID REFERENCES public.calls(id) ON DELETE CASCADE NOT NULL, + user_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, + candidate JSONB NOT NULL, + type TEXT NOT NULL, -- 'offer' or 'answer' candidate + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- Personalized Chat Settings & Customizations +CREATE TABLE IF NOT EXISTS public.chat_settings ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, + receiver_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, + nickname TEXT, + custom_photo_url TEXT, + is_muted BOOLEAN DEFAULT FALSE, + created_at TIMESTAMPTZ DEFAULT NOW(), + CONSTRAINT chat_settings_unique_pair UNIQUE (user_id, receiver_id) +); + +-- System & Interaction Notifications +CREATE TABLE IF NOT EXISTS public.notifications ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, + from_user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + type TEXT NOT NULL, + title TEXT, + content TEXT, + is_read BOOLEAN DEFAULT FALSE, + post_id TEXT, + created_at TIMESTAMPTZ DEFAULT NOW() +); + +-- 3. COLUMN UPGRADES +-- --------------------------------------------------------------------------- +-- A project created from an older version of this file can be missing columns +-- that were added later. `ADD COLUMN IF NOT EXISTS` makes every install converge +-- on the same shape without touching a single existing row. +-- --------------------------------------------------------------------------- + +ALTER TABLE public.users + ADD COLUMN IF NOT EXISTS email TEXT, + ADD COLUMN IF NOT EXISTS phone TEXT, + ADD COLUMN IF NOT EXISTS full_name TEXT, + ADD COLUMN IF NOT EXISTS username TEXT, + ADD COLUMN IF NOT EXISTS photo_url TEXT DEFAULT 'https://cdn-icons-png.flaticon.com/512/149/149071.png', + ADD COLUMN IF NOT EXISTS bio TEXT DEFAULT 'Available', + ADD COLUMN IF NOT EXISTS is_verified BOOLEAN DEFAULT FALSE, + ADD COLUMN IF NOT EXISTS profile_type TEXT DEFAULT 'personal', + ADD COLUMN IF NOT EXISTS is_online BOOLEAN DEFAULT FALSE, + ADD COLUMN IF NOT EXISTS last_seen TIMESTAMPTZ DEFAULT NOW(), + ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT NOW(), + ADD COLUMN IF NOT EXISTS settings JSONB DEFAULT '{}'::jsonb, + ADD COLUMN IF NOT EXISTS lock JSONB DEFAULT NULL, + ADD COLUMN IF NOT EXISTS blocked_users TEXT[] DEFAULT '{}'::text[], + ADD COLUMN IF NOT EXISTS muted_users TEXT[] DEFAULT '{}'::text[], + ADD COLUMN IF NOT EXISTS favorites TEXT[] DEFAULT '{}'::text[], + ADD COLUMN IF NOT EXISTS hidden_chats TEXT[] DEFAULT '{}'::text[], + ADD COLUMN IF NOT EXISTS archived_chats TEXT[] DEFAULT '{}'::text[], + ADD COLUMN IF NOT EXISTS hidden_chat_settings JSONB DEFAULT '{"secretCode": null, "showMenuEntry": true}'::jsonb, + ADD COLUMN IF NOT EXISTS fcm_tokens TEXT[] DEFAULT '{}'::text[]; + +ALTER TABLE public.follows + ADD COLUMN IF NOT EXISTS follower_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS following_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); + +ALTER TABLE public.conversations + ADD COLUMN IF NOT EXISTS type TEXT, + ADD COLUMN IF NOT EXISTS name TEXT, + ADD COLUMN IF NOT EXISTS photo_url TEXT, + ADD COLUMN IF NOT EXISTS admins UUID[] DEFAULT '{}'::uuid[], + ADD COLUMN IF NOT EXISTS watch_video_url TEXT, + ADD COLUMN IF NOT EXISTS watch_state JSONB DEFAULT '{}'::jsonb, + ADD COLUMN IF NOT EXISTS last_message TEXT, + ADD COLUMN IF NOT EXISTS last_message_at TIMESTAMPTZ, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(), + ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT NOW(); + +ALTER TABLE public.conversation_participants + ADD COLUMN IF NOT EXISTS conversation_id UUID REFERENCES public.conversations(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(), + ADD COLUMN IF NOT EXISTS joined_at TIMESTAMPTZ DEFAULT NOW(); + +ALTER TABLE public.messages + ADD COLUMN IF NOT EXISTS conversation_id UUID REFERENCES public.conversations(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS sender_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS text TEXT, + ADD COLUMN IF NOT EXISTS media_url TEXT, + ADD COLUMN IF NOT EXISTS media_type TEXT, + ADD COLUMN IF NOT EXISTS reply_to UUID REFERENCES public.messages(id) ON DELETE SET NULL, + ADD COLUMN IF NOT EXISTS reactions JSONB DEFAULT '{}'::jsonb, + ADD COLUMN IF NOT EXISTS is_read BOOLEAN DEFAULT FALSE, + ADD COLUMN IF NOT EXISTS is_edited BOOLEAN DEFAULT FALSE, + ADD COLUMN IF NOT EXISTS is_deleted BOOLEAN DEFAULT FALSE, + ADD COLUMN IF NOT EXISTS deleted_by UUID[] DEFAULT '{}'::UUID[], + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); + +ALTER TABLE public.stories + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS media_url TEXT, + ADD COLUMN IF NOT EXISTS type TEXT DEFAULT 'image', + ADD COLUMN IF NOT EXISTS text_content TEXT, + ADD COLUMN IF NOT EXISTS bg_color TEXT, + ADD COLUMN IF NOT EXISTS music_title TEXT, + ADD COLUMN IF NOT EXISTS music_artist TEXT, + ADD COLUMN IF NOT EXISTS music_url TEXT, + ADD COLUMN IF NOT EXISTS filter_applied TEXT, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); + +ALTER TABLE public.calls + ADD COLUMN IF NOT EXISTS caller_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS receiver_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS type TEXT, + ADD COLUMN IF NOT EXISTS status TEXT DEFAULT 'ringing', + ADD COLUMN IF NOT EXISTS offer JSONB, + ADD COLUMN IF NOT EXISTS answer JSONB, + ADD COLUMN IF NOT EXISTS is_missed BOOLEAN DEFAULT FALSE, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); + +ALTER TABLE public.call_candidates + ADD COLUMN IF NOT EXISTS call_id UUID REFERENCES public.calls(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS candidate JSONB, + ADD COLUMN IF NOT EXISTS type TEXT, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); + +ALTER TABLE public.chat_settings + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS receiver_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS nickname TEXT, + ADD COLUMN IF NOT EXISTS custom_photo_url TEXT, + ADD COLUMN IF NOT EXISTS is_muted BOOLEAN DEFAULT FALSE, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); + +ALTER TABLE public.notifications + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS from_user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS type TEXT, + ADD COLUMN IF NOT EXISTS title TEXT, + ADD COLUMN IF NOT EXISTS content TEXT, + ADD COLUMN IF NOT EXISTS is_read BOOLEAN DEFAULT FALSE, + ADD COLUMN IF NOT EXISTS post_id TEXT, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); + +-- NOT NULL is enforced only when the data already satisfies it, so an old table +-- with stray NULLs never makes this script abort. +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM public.users WHERE username IS NULL) THEN + ALTER TABLE public.users ALTER COLUMN username SET NOT NULL; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.follows WHERE follower_id IS NULL OR following_id IS NULL) THEN + ALTER TABLE public.follows ALTER COLUMN follower_id SET NOT NULL; + ALTER TABLE public.follows ALTER COLUMN following_id SET NOT NULL; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.conversations WHERE type IS NULL) THEN + ALTER TABLE public.conversations ALTER COLUMN type SET NOT NULL; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.conversation_participants WHERE conversation_id IS NULL OR user_id IS NULL) THEN + ALTER TABLE public.conversation_participants ALTER COLUMN conversation_id SET NOT NULL; + ALTER TABLE public.conversation_participants ALTER COLUMN user_id SET NOT NULL; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.messages WHERE conversation_id IS NULL OR sender_id IS NULL) THEN + ALTER TABLE public.messages ALTER COLUMN conversation_id SET NOT NULL; + ALTER TABLE public.messages ALTER COLUMN sender_id SET NOT NULL; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.stories WHERE user_id IS NULL) THEN + ALTER TABLE public.stories ALTER COLUMN user_id SET NOT NULL; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.calls WHERE caller_id IS NULL OR receiver_id IS NULL OR type IS NULL) THEN + ALTER TABLE public.calls ALTER COLUMN caller_id SET NOT NULL; + ALTER TABLE public.calls ALTER COLUMN receiver_id SET NOT NULL; + ALTER TABLE public.calls ALTER COLUMN type SET NOT NULL; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.chat_settings WHERE user_id IS NULL OR receiver_id IS NULL) THEN + ALTER TABLE public.chat_settings ALTER COLUMN user_id SET NOT NULL; + ALTER TABLE public.chat_settings ALTER COLUMN receiver_id SET NOT NULL; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.notifications WHERE user_id IS NULL OR type IS NULL) THEN + ALTER TABLE public.notifications ALTER COLUMN user_id SET NOT NULL; + ALTER TABLE public.notifications ALTER COLUMN type SET NOT NULL; + END IF; +END $$; + +-- 4. CONSTRAINTS +-- Added only when absent; a duplicate row in an old table produces a NOTICE +-- (never an abort) so the rest of the script still runs. +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint + WHERE conname = 'username_length_check' + AND conrelid = 'public.users'::regclass) THEN + ALTER TABLE public.users ADD CONSTRAINT username_length_check CHECK (char_length(username) <= 15); + END IF; + IF NOT EXISTS (SELECT 1 FROM pg_constraint + WHERE conname = 'follows_unique_pair' + AND conrelid = 'public.follows'::regclass) THEN + ALTER TABLE public.follows ADD CONSTRAINT follows_unique_pair UNIQUE (follower_id, following_id); + END IF; + IF NOT EXISTS (SELECT 1 FROM pg_constraint + WHERE conname = 'conversation_participants_unique_pair' + AND conrelid = 'public.conversation_participants'::regclass) THEN + ALTER TABLE public.conversation_participants ADD CONSTRAINT conversation_participants_unique_pair UNIQUE (conversation_id, user_id); + END IF; + IF NOT EXISTS (SELECT 1 FROM pg_constraint + WHERE conname = 'chat_settings_unique_pair' + AND conrelid = 'public.chat_settings'::regclass) THEN + ALTER TABLE public.chat_settings ADD CONSTRAINT chat_settings_unique_pair UNIQUE (user_id, receiver_id); + END IF; +EXCEPTION WHEN OTHERS THEN + RAISE NOTICE 'Constraint skipped (%): existing rows violate it', SQLERRM; +END $$; + +-- 5. ENABLE ROW LEVEL SECURITY (CORE PRIVACY) + +ALTER TABLE public.users ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.follows ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.conversations ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.conversation_participants ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.messages ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.stories ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.calls ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.call_candidates ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.chat_settings ENABLE ROW LEVEL SECURITY; +ALTER TABLE public.notifications ENABLE ROW LEVEL SECURITY; + +-- 6. RLS POLICIES (re-created on every run, so edits apply) + +-- profiles +DROP POLICY IF EXISTS "Allow public read access on profiles" ON public.users; +CREATE POLICY "Allow public read access on profiles" ON public.users FOR SELECT USING (true); +DROP POLICY IF EXISTS "Allow users to update own profile" ON public.users; +CREATE POLICY "Allow users to update own profile" ON public.users FOR UPDATE USING (auth.uid() = id) WITH CHECK (auth.uid() = id); +DROP POLICY IF EXISTS "Allow users to insert own profile" ON public.users; +CREATE POLICY "Allow users to insert own profile" ON public.users FOR INSERT WITH CHECK (auth.uid() = id); + +-- connections +DROP POLICY IF EXISTS "Allow users to view all follows" ON public.follows; +CREATE POLICY "Allow users to view all follows" ON public.follows FOR SELECT USING (true); +DROP POLICY IF EXISTS "Allow users to follow others" ON public.follows; +CREATE POLICY "Allow users to follow others" ON public.follows FOR INSERT WITH CHECK (auth.uid() = follower_id); +DROP POLICY IF EXISTS "Allow users to unfollow others" ON public.follows; +CREATE POLICY "Allow users to unfollow others" ON public.follows FOR DELETE USING (auth.uid() = follower_id); + +-- conversations +DROP POLICY IF EXISTS "Allow auth users to make conversations" ON public.conversations; +CREATE POLICY "Allow auth users to make conversations" ON public.conversations FOR INSERT WITH CHECK (auth.role() = 'authenticated'); +DROP POLICY IF EXISTS "Allow members to see conversations" ON public.conversations; +CREATE POLICY "Allow members to see conversations" ON public.conversations FOR SELECT USING ( + EXISTS ( + SELECT 1 FROM public.conversation_participants + WHERE conversation_participants.conversation_id = conversations.id + AND conversation_participants.user_id = auth.uid() + ) +); +DROP POLICY IF EXISTS "Allow participants to edit conversations" ON public.conversations; +CREATE POLICY "Allow participants to edit conversations" ON public.conversations FOR UPDATE USING ( + EXISTS ( + SELECT 1 FROM public.conversation_participants + WHERE conversation_participants.conversation_id = conversations.id + AND conversation_participants.user_id = auth.uid() + ) +); +DROP POLICY IF EXISTS "Allow participants to delete conversations" ON public.conversations; +CREATE POLICY "Allow participants to delete conversations" ON public.conversations FOR DELETE USING ( + EXISTS ( + SELECT 1 FROM public.conversation_participants + WHERE conversation_participants.conversation_id = conversations.id + AND conversation_participants.user_id = auth.uid() + ) +); + +-- members +DROP POLICY IF EXISTS "Allow auth users to inspect participants" ON public.conversation_participants; +CREATE POLICY "Allow auth users to inspect participants" ON public.conversation_participants FOR SELECT USING (true); +DROP POLICY IF EXISTS "Allow members to join rooms" ON public.conversation_participants; +CREATE POLICY "Allow members to join rooms" ON public.conversation_participants FOR INSERT WITH CHECK (auth.role() = 'authenticated'); +DROP POLICY IF EXISTS "Allow participants to leave rooms" ON public.conversation_participants; +CREATE POLICY "Allow participants to leave rooms" ON public.conversation_participants FOR DELETE USING (auth.role() = 'authenticated'); + +-- messages +DROP POLICY IF EXISTS "Allow conversation members to view messages" ON public.messages; +CREATE POLICY "Allow conversation members to view messages" ON public.messages FOR SELECT USING ( + EXISTS ( + SELECT 1 FROM public.conversation_participants + WHERE conversation_participants.conversation_id = messages.conversation_id + AND conversation_participants.user_id = auth.uid() + ) +); +DROP POLICY IF EXISTS "Allow active members to insert messages" ON public.messages; +CREATE POLICY "Allow active members to insert messages" ON public.messages FOR INSERT WITH CHECK ( + auth.uid() = sender_id + AND EXISTS ( + SELECT 1 FROM public.conversation_participants + WHERE conversation_participants.conversation_id = messages.conversation_id + AND conversation_participants.user_id = auth.uid() + ) +); +DROP POLICY IF EXISTS "Allow participants to update messages" ON public.messages; +CREATE POLICY "Allow participants to update messages" ON public.messages FOR UPDATE USING ( + EXISTS ( + SELECT 1 FROM public.conversation_participants + WHERE conversation_participants.conversation_id = messages.conversation_id + AND conversation_participants.user_id = auth.uid() + ) +); +DROP POLICY IF EXISTS "Allow participants to delete messages" ON public.messages; +CREATE POLICY "Allow participants to delete messages" ON public.messages FOR DELETE USING ( + EXISTS ( + SELECT 1 FROM public.conversation_participants + WHERE conversation_participants.conversation_id = messages.conversation_id + AND conversation_participants.user_id = auth.uid() + ) +); + +-- stories +DROP POLICY IF EXISTS "Allow auth users to view stories" ON public.stories; +CREATE POLICY "Allow auth users to view stories" ON public.stories FOR SELECT USING (auth.role() = 'authenticated'); +DROP POLICY IF EXISTS "Allow owners to publish stories" ON public.stories; +CREATE POLICY "Allow owners to publish stories" ON public.stories FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Allow owners to delete stories" ON public.stories; +CREATE POLICY "Allow owners to delete stories" ON public.stories FOR DELETE USING (auth.uid() = user_id); + +-- calling +DROP POLICY IF EXISTS "Allow view access to call records" ON public.calls; +CREATE POLICY "Allow view access to call records" ON public.calls FOR SELECT USING (auth.uid() = caller_id OR auth.uid() = receiver_id); +DROP POLICY IF EXISTS "Allow calls insertion to caller" ON public.calls; +CREATE POLICY "Allow calls insertion to caller" ON public.calls FOR INSERT WITH CHECK (auth.uid() = caller_id); +DROP POLICY IF EXISTS "Allow call updates on participants" ON public.calls; +CREATE POLICY "Allow call updates on participants" ON public.calls FOR UPDATE USING (auth.uid() = caller_id OR auth.uid() = receiver_id); + +-- signaling Candidates +DROP POLICY IF EXISTS "Allow select on candidates to call members" ON public.call_candidates; +CREATE POLICY "Allow select on candidates to call members" ON public.call_candidates FOR SELECT USING ( + EXISTS ( + SELECT 1 FROM public.calls + WHERE calls.id = call_candidates.call_id + AND (calls.caller_id = auth.uid() OR calls.receiver_id = auth.uid()) + ) +); +DROP POLICY IF EXISTS "Allow call participants to insert candidates" ON public.call_candidates; +CREATE POLICY "Allow call participants to insert candidates" ON public.call_candidates FOR INSERT WITH CHECK ( + auth.uid() = user_id + AND EXISTS ( + SELECT 1 FROM public.calls + WHERE calls.id = call_candidates.call_id + AND (calls.caller_id = auth.uid() OR calls.receiver_id = auth.uid()) + ) +); + +-- custom chat settings +DROP POLICY IF EXISTS "Allow users to read own chat settings" ON public.chat_settings; +CREATE POLICY "Allow users to read own chat settings" ON public.chat_settings FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Allow users to modify own chat settings" ON public.chat_settings; +CREATE POLICY "Allow users to modify own chat settings" ON public.chat_settings FOR ALL USING (auth.uid() = user_id); + +-- user notifications +DROP POLICY IF EXISTS "Allow users to read own notifications" ON public.notifications; +CREATE POLICY "Allow users to read own notifications" ON public.notifications FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Allow auth users system to insert notifications" ON public.notifications; +CREATE POLICY "Allow auth users system to insert notifications" ON public.notifications FOR INSERT WITH CHECK (auth.role() = 'authenticated'); +DROP POLICY IF EXISTS "Allow users to update own notifications" ON public.notifications; +CREATE POLICY "Allow users to update own notifications" ON public.notifications FOR UPDATE USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Allow users to delete own notifications" ON public.notifications; +CREATE POLICY "Allow users to delete own notifications" ON public.notifications FOR DELETE USING (auth.uid() = user_id); + +-- 7. PERFORMANCE AND SEARCH INDEXES +CREATE INDEX IF NOT EXISTS idx_messages_conversation ON public.messages(conversation_id); +CREATE INDEX IF NOT EXISTS idx_messages_created_at ON public.messages(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_participants_user ON public.conversation_participants(user_id); +CREATE INDEX IF NOT EXISTS idx_participants_conversation ON public.conversation_participants(conversation_id); +CREATE INDEX IF NOT EXISTS idx_users_username_lowered ON public.users(LOWER(username)); +CREATE INDEX IF NOT EXISTS idx_follows_follower ON public.follows(follower_id); +CREATE INDEX IF NOT EXISTS idx_follows_following ON public.follows(following_id); +CREATE INDEX IF NOT EXISTS idx_stories_user ON public.stories(user_id); +CREATE INDEX IF NOT EXISTS idx_calls_participants ON public.calls(caller_id, receiver_id); +CREATE INDEX IF NOT EXISTS idx_chat_settings_user ON public.chat_settings(user_id); +CREATE INDEX IF NOT EXISTS idx_notifications_user ON public.notifications(user_id); + +-- Notification sound configuration +NOTIFY pgrst, 'reload schema'; + + +-- ══════════════════════════════════════════════════════════════════════════ +-- PART 2/9 — sql/02_posts_and_interactions_schema.sql +-- (generated from the file of that name; edit THAT file, then re-run +-- "npm run sql:bundle" — do not edit this bundle by hand) +-- ══════════════════════════════════════════════════════════════════════════ + +-- ========================================================================= +-- STEP 2/9: POSTS, LIKES AND COMMENTS +-- ========================================================================= +-- Run in the Supabase SQL Editor after 01_core_schema.sql. +-- Safe to re-run: nothing is dropped, missing tables/columns/policies are +-- created, existing rows are untouched. +-- ========================================================================= + +-- 1. Create Posts Table +CREATE TABLE IF NOT EXISTS public.posts ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + image_url TEXT NOT NULL, + caption TEXT, + created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL +); + +-- Enable RLS for public.posts +ALTER TABLE public.posts ENABLE ROW LEVEL SECURITY; + +-- Post Policies +DROP POLICY IF EXISTS "Allow public read access for posts" ON public.posts; +CREATE POLICY "Allow public read access for posts" ON public.posts FOR SELECT +USING (true); + +DROP POLICY IF EXISTS "Allow authenticated insert for posts" ON public.posts; +CREATE POLICY "Allow authenticated insert for posts" ON public.posts FOR INSERT +WITH CHECK (auth.uid() = user_id); + +DROP POLICY IF EXISTS "Allow users to delete their own posts" ON public.posts; +CREATE POLICY "Allow users to delete their own posts" ON public.posts FOR DELETE +USING (auth.uid() = user_id); + + +-- 2. Create Post Likes Table (Tracking active likes) +CREATE TABLE IF NOT EXISTS public.post_likes ( + post_id UUID REFERENCES public.posts(id) ON DELETE CASCADE, + user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL, + PRIMARY KEY (post_id, user_id) +); + +-- Enable RLS for public.post_likes +ALTER TABLE public.post_likes ENABLE ROW LEVEL SECURITY; + +-- Post Likes Policies +DROP POLICY IF EXISTS "Allow public read access for post likes" ON public.post_likes; +CREATE POLICY "Allow public read access for post likes" ON public.post_likes FOR SELECT +USING (true); + +DROP POLICY IF EXISTS "Allow authenticated insert for post likes" ON public.post_likes; +CREATE POLICY "Allow authenticated insert for post likes" ON public.post_likes FOR INSERT +WITH CHECK (auth.uid() = user_id); + +DROP POLICY IF EXISTS "Allow users to remove their likes" ON public.post_likes; +CREATE POLICY "Allow users to remove their likes" ON public.post_likes FOR DELETE +USING (auth.uid() = user_id); + + +-- 3. Create Post Comments Table +CREATE TABLE IF NOT EXISTS public.post_comments ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + post_id UUID REFERENCES public.posts(id) ON DELETE CASCADE, + user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + text TEXT NOT NULL, + created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL +); + +-- Enable RLS for public.post_comments +ALTER TABLE public.post_comments ENABLE ROW LEVEL SECURITY; + +-- Post Comments Policies +DROP POLICY IF EXISTS "Allow public read access for post comments" ON public.post_comments; +CREATE POLICY "Allow public read access for post comments" ON public.post_comments FOR SELECT +USING (true); + +DROP POLICY IF EXISTS "Allow authenticated insert for post comments" ON public.post_comments; +CREATE POLICY "Allow authenticated insert for post comments" ON public.post_comments FOR INSERT +WITH CHECK (auth.uid() = user_id); + +DROP POLICY IF EXISTS "Allow users to delete their own comments" ON public.post_comments; +CREATE POLICY "Allow users to delete their own comments" ON public.post_comments FOR DELETE +USING (auth.uid() = user_id); + +-- Performance Indexes +CREATE INDEX IF NOT EXISTS idx_posts_user_id ON public.posts(user_id); +CREATE INDEX IF NOT EXISTS idx_post_likes_post_id ON public.post_likes(post_id); +CREATE INDEX IF NOT EXISTS idx_post_comments_post_id ON public.post_comments(post_id); + +-- Column upgrades: a project created from an older version of this file may be +-- missing columns added later. No existing row is touched. +ALTER TABLE public.posts + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS image_url TEXT, + ADD COLUMN IF NOT EXISTS caption TEXT, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()); + +ALTER TABLE public.post_likes + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()); + +ALTER TABLE public.post_comments + ADD COLUMN IF NOT EXISTS post_id UUID REFERENCES public.posts(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS text TEXT, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()); + +-- Primary key of post_likes is (post_id, user_id); add it only if it is absent. +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint + WHERE conname = 'post_likes_pkey' + AND conrelid = 'public.post_likes'::regclass) THEN + ALTER TABLE public.post_likes ADD CONSTRAINT post_likes_pkey PRIMARY KEY (post_id, user_id); + END IF; +EXCEPTION WHEN OTHERS THEN + RAISE NOTICE 'post_likes primary key skipped: %', SQLERRM; +END $$; + +-- Reload Schema +NOTIFY pgrst, 'reload schema'; + + +-- ══════════════════════════════════════════════════════════════════════════ +-- PART 3/9 — sql/03_support_tickets_schema.sql +-- (generated from the file of that name; edit THAT file, then re-run +-- "npm run sql:bundle" — do not edit this bundle by hand) +-- ══════════════════════════════════════════════════════════════════════════ + +-- ========================================================================= +-- STEP 3/9: SUPPORT TICKETS +-- ========================================================================= +-- Run in the Supabase SQL Editor after 02_posts_and_interactions_schema.sql. +-- Safe to re-run: nothing is dropped, existing tickets are kept. +-- ========================================================================= + +-- Create support tickets Table +CREATE TABLE IF NOT EXISTS public.support_tickets ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID REFERENCES public.users(id) ON DELETE SET NULL, + email TEXT NOT NULL, + category TEXT NOT NULL, + subject TEXT NOT NULL, + message TEXT NOT NULL, + status TEXT DEFAULT 'open' CHECK (status IN ('open', 'in_progress', 'resolved')), + created_at TIMESTAMPTZ DEFAULT NOW(), + updated_at TIMESTAMPTZ DEFAULT NOW() +); + +-- Column upgrades for older installs (no existing row is touched). +ALTER TABLE public.support_tickets + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE SET NULL, + ADD COLUMN IF NOT EXISTS email TEXT, + ADD COLUMN IF NOT EXISTS category TEXT, + ADD COLUMN IF NOT EXISTS subject TEXT, + ADD COLUMN IF NOT EXISTS message TEXT, + ADD COLUMN IF NOT EXISTS status TEXT DEFAULT 'open', + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(), + ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT NOW(); + +-- Enable Row Level Security (RLS) +ALTER TABLE public.support_tickets ENABLE ROW LEVEL SECURITY; + +-- 1. Anonymous and Authenticated submittals +DROP POLICY IF EXISTS "Allow anonymous and authenticated ticket insertion" ON public.support_tickets; +CREATE POLICY "Allow anonymous and authenticated ticket insertion" ON public.support_tickets + FOR INSERT + WITH CHECK (true); + +-- 2. Fetch logged tickets +DROP POLICY IF EXISTS "Allow users to view own tickets" ON public.support_tickets; +CREATE POLICY "Allow users to view own tickets" ON public.support_tickets + FOR SELECT + USING (auth.uid() = user_id); + +-- Performance Indexing +CREATE INDEX IF NOT EXISTS idx_support_tickets_user_id ON public.support_tickets(user_id); + +-- Reload Schema Cache +NOTIFY pgrst, 'reload schema'; + + +-- ══════════════════════════════════════════════════════════════════════════ +-- PART 4/9 — sql/04_triggers_functions_and_rpc.sql +-- (generated from the file of that name; edit THAT file, then re-run +-- "npm run sql:bundle" — do not edit this bundle by hand) +-- ══════════════════════════════════════════════════════════════════════════ + +-- ========================================================================= +-- STEP 4/9: RPC FUNCTIONS, TRIGGERS & AUTH -> PROFILE AUTO-SYNC +-- ========================================================================= +-- Run in the Supabase SQL Editor after 03_support_tickets_schema.sql. +-- Safe to re-run: the trigger and the functions are dropped and re-created, so +-- an updated definition always replaces the old one. No row is ever deleted. +-- (`DROP FUNCTION` cannot lose the trigger's target: the trigger is dropped +-- first, in the same run.) +-- ========================================================================= + +-- Clear existing Triggers & Functions +DROP TRIGGER IF EXISTS on_auth_user_created ON auth.users; +DROP FUNCTION IF EXISTS public.handle_new_auth_user(); +DROP FUNCTION IF EXISTS public.get_direct_conversation_id(UUID, UUID); + +-- 1. Direct Conversation Match RPC (Guarantees Instant Room Lookups) +CREATE OR REPLACE FUNCTION public.get_direct_conversation_id(u1 UUID, u2 UUID) +RETURNS UUID AS $$ +DECLARE + conv_id UUID; +BEGIN + SELECT cp1.conversation_id INTO conv_id + FROM public.conversation_participants cp1 + JOIN public.conversation_participants cp2 + ON cp1.conversation_id = cp2.conversation_id + JOIN public.conversations c + ON cp1.conversation_id = c.id + WHERE cp1.user_id = u1 + AND cp2.user_id = u2 + AND c.type = 'direct' + LIMIT 1; + + RETURN conv_id; +END; +$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public; + + +-- 2. Auth to Public user profiles sync (Essential for Signup and OAuth sign-in) +CREATE OR REPLACE FUNCTION public.handle_new_auth_user() +RETURNS TRIGGER AS $$ +DECLARE + username_val TEXT; + full_name_val TEXT; +BEGIN + -- Extract values safely from raw_user_meta_data or default to email split-part + username_val := COALESCE( + new.raw_user_meta_data->>'username', + split_part(new.email, '@', 1) + ); + full_name_val := COALESCE( + new.raw_user_meta_data->>'full_name', + split_part(new.email, '@', 1) + ); + + -- Clean the username values to be under 15 characters + username_val := SUBSTRING(username_val, 1, 15); + + -- Ensure uniqueness of username, append unique IDs if a duplicate is found + IF EXISTS (SELECT 1 FROM public.users WHERE username = username_val) THEN + username_val := SUBSTRING(username_val, 1, 9) || '_' || substring(new.id::text, 1, 5); + END IF; + + -- Insert profile safely + INSERT INTO public.users ( + id, + email, + phone, + full_name, + username, + photo_url, + bio + ) + VALUES ( + new.id, + new.email, + COALESCE(new.raw_user_meta_data->>'phone', ''), + full_name_val, + LOWER(username_val), + COALESCE(new.raw_user_meta_data->>'avatar_url', 'https://cdn-icons-png.flaticon.com/512/149/149071.png'), + 'Available' + ) + ON CONFLICT (id) DO UPDATE SET + email = EXCLUDED.email, + phone = COALESCE(public.users.phone, EXCLUDED.phone), + full_name = COALESCE(public.users.full_name, EXCLUDED.full_name), + username = COALESCE(public.users.username, EXCLUDED.username); + + RETURN NEW; +END; +$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public; + +-- Bind trigger on auth.users (Runs completely on auth signup) +CREATE TRIGGER on_auth_user_created + AFTER INSERT ON auth.users + FOR EACH ROW EXECUTE FUNCTION public.handle_new_auth_user(); + +-- Clear Schema cache +NOTIFY pgrst, 'reload schema'; + + +-- ══════════════════════════════════════════════════════════════════════════ +-- PART 5/9 — sql/05_advanced_optimizations_and_realtime.sql +-- (generated from the file of that name; edit THAT file, then re-run +-- "npm run sql:bundle" — do not edit this bundle by hand) +-- ══════════════════════════════════════════════════════════════════════════ + +-- ========================================================================= +-- STEP 5/9: REALTIME PUBLICATION, PREVIEW TRIGGERS, HISTORY CAP +-- ========================================================================= +-- Run in the Supabase SQL Editor after 04_triggers_functions_and_rpc.sql. +-- Safe to re-run: functions are CREATE OR REPLACE, triggers are dropped first, +-- replica identity and publication membership are re-asserted. +-- +-- ⚠️ READ THIS BEFORE RUNNING — sections 1 and 6 DELETE MESSAGE HISTORY: +-- every chat is capped at 60 rows, pruned back to the newest 40, on every +-- insert. It keeps a free-tier project small, but it also means chat history +-- is not kept. To keep history instead: do NOT run sections 1 and 6, and use +-- the time-based pruner in 09_egress_optimizations.sql (`prune_old_messages`). +-- ========================================================================= + +-- 1. MESSAGE CAP PRUNER (LIMITS ROOMS TO LAST 60 MESSAGES - PRUNES TO 40) +CREATE OR REPLACE FUNCTION prune_past_messages() +RETURNS TRIGGER AS $$ +DECLARE + msg_count INT; +BEGIN + SELECT COUNT(*) INTO msg_count + FROM public.messages + WHERE conversation_id = NEW.conversation_id; + + IF msg_count >= 60 THEN + DELETE FROM public.messages + WHERE conversation_id = NEW.conversation_id + AND id NOT IN ( + SELECT subquery.id FROM ( + SELECT id FROM public.messages + WHERE conversation_id = NEW.conversation_id + ORDER BY created_at DESC, id DESC + LIMIT 40 + ) subquery + ); + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql SECURITY DEFINER; + +DROP TRIGGER IF EXISTS trg_prune_past_messages ON public.messages; +CREATE TRIGGER trg_prune_past_messages +AFTER INSERT ON public.messages +FOR EACH ROW +EXECUTE FUNCTION prune_past_messages(); + + +-- 2. AUTOMATICALLY SYNC NEW MESSAGES WITH CONVERSATIONS PREVIEWS +CREATE OR REPLACE FUNCTION update_conversation_timestamp_and_last_message() +RETURNS TRIGGER AS $$ +BEGIN + UPDATE public.conversations + SET + updated_at = NEW.created_at, + last_message = COALESCE(NEW.text, CASE WHEN NEW.media_type IS NOT NULL THEN 'Sent a ' || NEW.media_type ELSE 'Sent an attachment' END), + last_message_at = NEW.created_at + WHERE id = NEW.conversation_id; + RETURN NEW; +END; +$$ LANGUAGE plpgsql SECURITY DEFINER; + +DROP TRIGGER IF EXISTS trg_update_conversation_on_message ON public.messages; +CREATE TRIGGER trg_update_conversation_on_message +AFTER INSERT ON public.messages +FOR EACH ROW +EXECUTE FUNCTION update_conversation_timestamp_and_last_message(); + + +-- 3. INTERACTIVE CALLS RECUPERATOR PRUNER (LIMITS CHRONO CALLS TO LAST 60) +CREATE OR REPLACE FUNCTION prune_past_calls() +RETURNS TRIGGER AS $$ +DECLARE + caller_call_count INT; + receiver_call_count INT; +BEGIN + SELECT COUNT(*) INTO caller_call_count + FROM public.calls + WHERE caller_id = NEW.caller_id OR receiver_id = NEW.caller_id; + + IF caller_call_count >= 60 THEN + DELETE FROM public.calls + WHERE (caller_id = NEW.caller_id OR receiver_id = NEW.caller_id) + AND id NOT IN ( + SELECT subquery.id FROM ( + SELECT id FROM public.calls + WHERE caller_id = NEW.caller_id OR receiver_id = NEW.caller_id + ORDER BY created_at DESC, id DESC + LIMIT 40 + ) subquery + ); + END IF; + + IF NEW.receiver_id IS NOT NULL AND NEW.receiver_id <> NEW.caller_id THEN + SELECT COUNT(*) INTO receiver_call_count + FROM public.calls + WHERE caller_id = NEW.receiver_id OR receiver_id = NEW.receiver_id; + + IF receiver_call_count >= 60 THEN + DELETE FROM public.calls + WHERE (caller_id = NEW.receiver_id OR receiver_id = NEW.receiver_id) + AND id NOT IN ( + SELECT subquery.id FROM ( + SELECT id FROM public.calls + WHERE caller_id = NEW.receiver_id OR receiver_id = NEW.receiver_id + ORDER BY created_at DESC, id DESC + LIMIT 40 + ) subquery + ); + END IF; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql SECURITY DEFINER; + +DROP TRIGGER IF EXISTS trg_prune_past_calls ON public.calls; +CREATE TRIGGER trg_prune_past_calls +AFTER INSERT ON public.calls +FOR EACH ROW +EXECUTE FUNCTION prune_past_calls(); + + +-- 4. REPLICA IDENTITY +-- --------------------------------------------------------------------------- +-- FULL is only needed where the client filters DELETEs by a non-key column +-- (`conversation_id=eq.…` on messages and conversation_participants). Everywhere +-- else DEFAULT keeps UPDATE payloads to "new row + primary key", which stops +-- whole rows — including `users.lock`, the app-lock passcode hash, and +-- `fcm_tokens` — from being broadcast to every subscribed client. +-- 09_egress_optimizations.sql re-asserts the same values, so either file leaves +-- the database in this state. +-- --------------------------------------------------------------------------- +DO $$ +DECLARE + target RECORD; +BEGIN + FOR target IN + SELECT * FROM (VALUES + ('users', 'DEFAULT'), + ('conversations', 'DEFAULT'), + ('calls', 'DEFAULT'), + ('call_candidates', 'DEFAULT'), + ('messages', 'FULL'), + ('conversation_participants','FULL') + ) AS t(tbl, identity) + LOOP + IF EXISTS (SELECT 1 FROM pg_class c + JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname = target.tbl) THEN + EXECUTE format('ALTER TABLE public.%I REPLICA IDENTITY %s', target.tbl, target.identity); + END IF; + END LOOP; +END; +$$; + + +-- 5. SUPABASE REALTIME PUBLICATION MEMBERSHIP +-- --------------------------------------------------------------------------- +-- Only the tables the client actually subscribes to. Membership is idempotent: +-- a table is added only when it exists and is not already published, so a run +-- over an existing project changes nothing and a fork that dropped a table +-- (e.g. call_candidates) does not abort the script. +-- --------------------------------------------------------------------------- +DO $$ +DECLARE + tbl TEXT; +BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_publication WHERE pubname = 'supabase_realtime') THEN + CREATE PUBLICATION supabase_realtime; + END IF; + + FOREACH tbl IN ARRAY ARRAY[ + 'messages', 'conversations', 'users', 'calls', + 'call_candidates', 'conversation_participants' + ] LOOP + IF to_regclass('public.' || tbl) IS NOT NULL + AND NOT EXISTS (SELECT 1 FROM pg_publication_tables + WHERE pubname = 'supabase_realtime' + AND schemaname = 'public' + AND tablename = tbl) THEN + EXECUTE format('ALTER PUBLICATION supabase_realtime ADD TABLE public.%I', tbl); + END IF; + END LOOP; +END; +$$; + +-- Also enable Realtime in the dashboard for these tables: +-- Database -> Replication -> supabase_realtime +-- The SQL above registers the tables; the dashboard toggle is what actually +-- streams them. + + +-- 6. RETROACTIVE SWEEP (trims pre-existing high-volume tables down to 40 rows) +-- Same policy as section 1: it keeps the newest 40 messages per chat and the +-- newest 40 calls per user. Skip this section if you skipped section 1. +DO $$ +DECLARE + u_rec RECORD; + conv_rec RECORD; +BEGIN + -- Prune existing calls back to newest 40 for every user + FOR u_rec IN (SELECT DISTINCT id FROM public.users) LOOP + DELETE FROM public.calls + WHERE (caller_id = u_rec.id OR receiver_id = u_rec.id) + AND id NOT IN ( + SELECT subquery.id FROM ( + SELECT id FROM public.calls + WHERE caller_id = u_rec.id OR receiver_id = u_rec.id + ORDER BY created_at DESC, id DESC + LIMIT 40 + ) subquery + ); + END LOOP; + + -- Prune existing messages back to newest 40 for every conversation room + FOR conv_rec IN (SELECT DISTINCT id FROM public.conversations) LOOP + DELETE FROM public.messages + WHERE conversation_id = conv_rec.id + AND id NOT IN ( + SELECT subquery.id FROM ( + SELECT id FROM public.messages + WHERE conversation_id = conv_rec.id + ORDER BY created_at DESC, id DESC + LIMIT 40 + ) subquery + ); + END LOOP; +END; +$$; + +-- Reload Schema and notify PostgREST +NOTIFY pgrst, 'reload schema'; + + +-- ══════════════════════════════════════════════════════════════════════════ +-- PART 6/9 — sql/06_storage_configurations.sql +-- (generated from the file of that name; edit THAT file, then re-run +-- "npm run sql:bundle" — do not edit this bundle by hand) +-- ══════════════════════════════════════════════════════════════════════════ + +-- ========================================================================= +-- STEP 6/9: STORAGE BUCKETS (chat-media, profiles) AND THEIR POLICIES +-- ========================================================================= +-- Run in the Supabase SQL Editor after 05_advanced_optimizations_and_realtime.sql. +-- Safe to re-run: buckets are inserted with ON CONFLICT DO NOTHING and every +-- policy is dropped and re-created, so an updated definition always wins. +-- +-- ⚠️ These policies are deliberately permissive (public read, any authenticated +-- user may upload/update/delete in these buckets) because the app uploads to +-- `chat-media/images/_.` — paths carry no user id, so +-- ownership cannot be checked from the path. Hardening notes: +-- docs/EGRESS_AUDIT.md §6 and the commented block in 09_egress_optimizations.sql. +-- ========================================================================= + +-- 1. PROVISION BUCKETS (If they do not already exist) +INSERT INTO storage.buckets (id, name, public, file_size_limit, allowed_mime_types) +VALUES + ('chat-media', 'chat-media', true, 52428800, NULL), -- 50 MB limit + ('profiles', 'profiles', true, 5242880, ARRAY['image/jpeg', 'image/png', 'image/gif', 'image/webp']) -- 5 MB limit +ON CONFLICT (id) DO NOTHING; + + +-- 2. RE-ENABLE AND RESET STRATEGIC POLICIES FOR STORAGE OBJECTS +-- Clean up any conflicting pre-existing policies for these buckets +DROP POLICY IF EXISTS "Public Access to chat-media" ON storage.objects; +DROP POLICY IF EXISTS "Authenticated Users can upload to chat-media" ON storage.objects; +DROP POLICY IF EXISTS "Owners can update their own chat-media objects" ON storage.objects; +DROP POLICY IF EXISTS "Owners can delete their own chat-media objects" ON storage.objects; + +DROP POLICY IF EXISTS "Public Access to profiles" ON storage.objects; +DROP POLICY IF EXISTS "Authenticated Users can upload to profiles" ON storage.objects; +DROP POLICY IF EXISTS "Owners can update their own profiles" ON storage.objects; +DROP POLICY IF EXISTS "Owners can delete their own profiles" ON storage.objects; + + +-- 3. APPLY SECURITY POLICIES FOR 'chat-media' BUCKET + +-- Read Policy: Anyone can read media (Publicly accessible) +CREATE POLICY "Public Access to chat-media" +ON storage.objects FOR SELECT +TO public +USING (bucket_id = 'chat-media'); + +-- Write Policy: Authenticated users can insert files +CREATE POLICY "Authenticated Users can upload to chat-media" +ON storage.objects FOR INSERT +TO authenticated +WITH CHECK (bucket_id = 'chat-media' AND (auth.uid()::text = (storage.foldername(name))[1] OR true)); + +-- Update Policy: Authenticated owners can update files +CREATE POLICY "Owners can update their own chat-media objects" +ON storage.objects FOR UPDATE +TO authenticated +USING (bucket_id = 'chat-media') +WITH CHECK (bucket_id = 'chat-media'); + +-- Delete Policy: Authenticated users can delete files they own +CREATE POLICY "Owners can delete their own chat-media objects" +ON storage.objects FOR DELETE +TO authenticated +USING (bucket_id = 'chat-media'); + + +-- 4. APPLY SECURITY POLICIES FOR 'profiles' BUCKET + +-- Read Policy: Anyone can read profiles photos (Publicly accessible) +CREATE POLICY "Public Access to profiles" +ON storage.objects FOR SELECT +TO public +USING (bucket_id = 'profiles'); + +-- Write Policy: Authenticated users can upload profile icons +CREATE POLICY "Authenticated Users can upload to profiles" +ON storage.objects FOR INSERT +TO authenticated +WITH CHECK (bucket_id = 'profiles'); + +-- Update Policy: Authenticated users can replace profile icons +CREATE POLICY "Owners can update their own profiles" +ON storage.objects FOR UPDATE +TO authenticated +USING (bucket_id = 'profiles') +WITH CHECK (bucket_id = 'profiles'); + +-- Delete Policy: Authenticated users can delete profile icons +CREATE POLICY "Owners can delete their own profiles" +ON storage.objects FOR DELETE +TO authenticated +USING (bucket_id = 'profiles'); + + +-- 5. RELOAD POSTGRES SCHEMA CACHE +NOTIFY pgrst, 'reload schema'; + + +-- ══════════════════════════════════════════════════════════════════════════ +-- PART 7/9 — sql/07_chat_time_scheduling_migration.sql +-- (generated from the file of that name; edit THAT file, then re-run +-- "npm run sql:bundle" — do not edit this bundle by hand) +-- ══════════════════════════════════════════════════════════════════════════ + +-- Incremental Migration for Chat Time Scheduling +-- Purpose: Add support for custom chat times, allowing users of direct chats to set allowed days/times. +-- Integrates directly inside public.conversations table under watch_state JSONB field, with defensive fallback. + +ALTER TABLE public.conversations ADD COLUMN IF NOT EXISTS chat_time_restrictions JSONB DEFAULT NULL; + +-- Keep Row Level Security enabled for access constraints +-- Triggers a reload of PostgREST schema cache to make column visible +NOTIFY pgrst, 'reload schema'; + + +-- ══════════════════════════════════════════════════════════════════════════ +-- PART 8/9 — sql/08_stories_expiration_and_views.sql +-- (generated from the file of that name; edit THAT file, then re-run +-- "npm run sql:bundle" — do not edit this bundle by hand) +-- ══════════════════════════════════════════════════════════════════════════ + +-- Incremental Migration for Stories Expiration (24h) and Views tracking +-- Purpose: Adds views column to stories table, adds view_story RPC, and adds cleanup_expired_stories RPC. + +-- 1. Add views JSONb column to stories table +ALTER TABLE public.stories ADD COLUMN IF NOT EXISTS views JSONB DEFAULT '[]'::JSONB NOT NULL; + +-- 2. Create RPC to register a view securely without exposing direct update permissions +-- This is written in the simplest possible form to avoid any PL/pgSQL parsing issues. +CREATE OR REPLACE FUNCTION public.view_story( + story_id_param UUID, + viewer_id_param UUID, + viewer_username_param TEXT, + viewer_fullname_param TEXT, + viewer_photo_url_param TEXT +) +RETURNS VOID AS $$ +BEGIN + UPDATE public.stories + SET views = COALESCE(views, '[]'::JSONB) || jsonb_build_array( + jsonb_build_object( + 'id', viewer_id_param, + 'username', viewer_username_param, + 'full_name', viewer_fullname_param, + 'photo_url', viewer_photo_url_param, + 'viewed_at', NOW() + ) + ) + WHERE id = story_id_param + AND NOT (COALESCE(views, '[]'::JSONB) @> jsonb_build_array(jsonb_build_object('id', viewer_id_param::text))); +END; +$$ LANGUAGE plpgsql SECURITY DEFINER; + +-- 3. Create RPC to clean up stories older than 24 hours +CREATE OR REPLACE FUNCTION public.cleanup_expired_stories() +RETURNS VOID AS $$ +BEGIN + DELETE FROM public.stories WHERE created_at < NOW() - INTERVAL '24 hours'; +END; +$$ LANGUAGE plpgsql SECURITY DEFINER; + +-- Trigger schema reload +NOTIFY pgrst, 'reload schema'; + + +-- ══════════════════════════════════════════════════════════════════════════ +-- PART 9/9 — sql/09_egress_optimizations.sql +-- (generated from the file of that name; edit THAT file, then re-run +-- "npm run sql:bundle" — do not edit this bundle by hand) +-- ══════════════════════════════════════════════════════════════════════════ + +-- ═══════════════════════════════════════════════════════════════════════════ +-- 09 — Egress optimizations +-- +-- Apply this in the Supabase SQL editor: Database → SQL Editor → New query. +-- It is idempotent, so running it twice is safe. +-- +-- Why: the app consumed 5 GB of egress in under a month with 2–3 active users. +-- The client-side cause (a full conversation-list refetch per realtime event) +-- is fixed in code — see docs/EGRESS_AUDIT.md. This file fixes the database +-- half, which cannot be changed from the repository: +-- +-- 1. `last_read_at` — read receipts become ONE row update instead of one per +-- unread message (each of which was broadcast to every client). +-- 2. Denormalized `last_message*` maintained by trigger, so the chat list +-- never has to fetch message rows just to draw a one-line preview. +-- 3. REPLICA IDENTITY: stop broadcasting whole rows (including the passcode +-- hash and FCM tokens in `users`) on every UPDATE. +-- 4. Indexes for the hot paths. +-- 5. Optional retention pruner for old messages. +-- ═══════════════════════════════════════════════════════════════════════════ + + +-- ── 1. Read marker ───────────────────────────────────────────────────────── +-- Unread is a comparison: conversations.last_message_at > my last_read_at. +-- One UPDATE per "I opened/read this chat" instead of one row per message. + +-- Existing rows are stamped with the moment this runs, so history starts +-- "read" and nobody gets a fake 400-message unread badge. +ALTER TABLE public.conversation_participants + ADD COLUMN IF NOT EXISTS last_read_at TIMESTAMPTZ DEFAULT NOW(); + +-- The client updates ITS OWN row to say "I have read up to here". Without this +-- policy the UPDATE matches no policy, affects 0 rows, and returns no error — +-- the read marker would silently never move. (RLS is on for this table, and +-- 01_core_schema.sql only defined SELECT/INSERT/DELETE.) +DROP POLICY IF EXISTS "Participants can update their own membership" ON public.conversation_participants; +CREATE POLICY "Participants can update their own membership" + ON public.conversation_participants + FOR UPDATE + USING (user_id = auth.uid()) + WITH CHECK (user_id = auth.uid()); + +CREATE INDEX IF NOT EXISTS idx_participants_user_last_read + ON public.conversation_participants(user_id, last_read_at DESC); + +-- Realtime: the client subscribes with `user_id=eq.` and must also receive +-- DELETEs (a participant removed from a group). DEFAULT identity only carries +-- the primary key in the `old` record, so the server cannot evaluate the filter +-- for deletes. These rows are tiny and rarely written, so FULL is cheap here. +ALTER TABLE public.conversation_participants REPLICA IDENTITY FULL; + + +-- ── 2. `last_message*` is maintained by the database ─────────────────────── +-- The chat list shows `last_message` / `last_message_at` / (for ticks) the +-- sender. Writers already set the first two; the trigger also covers edits, +-- deletes and direct SQL inserts, so the client never needs to re-read the +-- newest messages for every conversation. + +ALTER TABLE public.conversations + ADD COLUMN IF NOT EXISTS last_message_sender_id UUID; + +CREATE OR REPLACE FUNCTION public.sync_conversation_last_message() +RETURNS TRIGGER +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = public +AS $$ +DECLARE + target_conversation UUID; + newest RECORD; +BEGIN + target_conversation := COALESCE(NEW.conversation_id, OLD.conversation_id); + IF target_conversation IS NULL THEN + RETURN NULL; + END IF; + + -- Fast path: a new (or edited) message that is not older than what the + -- conversation already shows IS the newest one, so write it across without + -- looking at the table. Appends are the hot path: no extra index scan. + IF TG_OP <> 'DELETE' AND NEW.is_deleted = false THEN + UPDATE public.conversations + SET last_message = COALESCE(NEW.text, + 'Sent a ' || COALESCE(NEW.media_type, 'file')), + last_message_at = NEW.created_at, + last_message_sender_id = NEW.sender_id + WHERE id = target_conversation + AND (last_message_at IS NULL OR NEW.created_at >= last_message_at); + IF FOUND THEN + RETURN NULL; + END IF; + END IF; + + -- Fast skip for DELETEs: if the conversation already shows something newer, + -- removing an older row cannot change the preview. This is the common case + -- for the 40-message history cap in 05, which deletes a batch per insert. + IF TG_OP = 'DELETE' AND EXISTS ( + SELECT 1 FROM public.conversations + WHERE id = target_conversation + AND last_message_at IS NOT NULL + AND last_message_at > OLD.created_at + ) THEN + RETURN NULL; + END IF; + + -- Slow path: a delete of the newest row, a soft delete, or an edit of an + -- older message. The preview has to be re-derived from what is left. + SELECT m.text, m.media_type, m.created_at, m.sender_id, m.is_deleted + INTO newest + FROM public.messages m + WHERE m.conversation_id = target_conversation + AND m.is_deleted = false + ORDER BY m.created_at DESC + LIMIT 1; + + IF NOT FOUND THEN + UPDATE public.conversations + SET last_message = NULL, + last_message_at = NULL, + last_message_sender_id = NULL + WHERE id = target_conversation; + ELSE + UPDATE public.conversations + SET last_message = COALESCE(newest.text, + 'Sent a ' || COALESCE(newest.media_type, 'file')), + last_message_at = newest.created_at, + last_message_sender_id = newest.sender_id + WHERE id = target_conversation; + END IF; + + RETURN NULL; +END; +$$; + +DROP TRIGGER IF EXISTS trg_sync_conversation_last_message ON public.messages; +CREATE TRIGGER trg_sync_conversation_last_message + AFTER INSERT OR UPDATE OF text, media_type, is_deleted OR DELETE + ON public.messages + FOR EACH ROW + EXECUTE FUNCTION public.sync_conversation_last_message(); + +-- The fast path above needs no lookup at all; only edits/deletes of older +-- messages touch the index below, and they resolve it in one index scan. + +CREATE INDEX IF NOT EXISTS idx_messages_conv_created + ON public.messages(conversation_id, created_at DESC); + +CREATE INDEX IF NOT EXISTS idx_conversations_last_message_at + ON public.conversations(last_message_at DESC NULLS LAST); + +-- Legacy path only (used until the client detects `last_read_at`). +CREATE INDEX IF NOT EXISTS idx_messages_unread + ON public.messages(conversation_id) + WHERE is_read = false; + + +-- ── 3. Stop broadcasting whole rows on UPDATE ────────────────────────────── +-- `REPLICA IDENTITY FULL` makes every UPDATE emit the complete OLD row and the +-- complete NEW row to every subscribed client. On `users` that payload includes +-- `settings`, `lock` (passcode hash!) and `fcm_tokens`. DEFAULT sends the new +-- row plus the primary key only — smaller, and no private columns on the wire. +-- +-- `messages` is deliberately NOT in this list. `useChatMessages` listens for +-- DELETE events with a `conversation_id=eq.…` filter, and the filter column is +-- only present in the `old` record when the identity is FULL — with DEFAULT the +-- event cannot be matched and "delete for everyone" would stop propagating. +-- The read-marker change (section 1) is what removes messages UPDATE traffic; +-- deletes are rare, so FULL stays there. +-- +-- `conversations`, `users` and `calls` are only ever read via `payload.new` on +-- the client (and a conversation DELETE also removes its participant rows, which +-- ARE FULL), so DEFAULT is safe for them. Calls are status-UPDATEd, never +-- deleted (`CallProvider` zombie sweep). The pair of `FULL` entries re-asserts +-- the two tables whose filtered DELETEs the client depends on, so this file +-- leaves the database correct no matter which earlier scripts were applied. + +DO $$ +DECLARE + target RECORD; +BEGIN + FOR target IN + SELECT * FROM (VALUES + ('users', 'DEFAULT'), + ('conversations', 'DEFAULT'), + ('calls', 'DEFAULT'), + ('call_candidates', 'DEFAULT'), + ('messages', 'FULL'), + ('conversation_participants','FULL') + ) AS t(tbl, identity) + LOOP + IF EXISTS (SELECT 1 FROM pg_class c + JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname = target.tbl) THEN + EXECUTE format('ALTER TABLE public.%I REPLICA IDENTITY %s', + target.tbl, target.identity); + END IF; + END LOOP; +END; +$$; + + +-- Advanced (optional, experimental): if messages UPDATE payloads ever matter +-- again, `ALTER TABLE public.messages REPLICA IDENTITY USING INDEX +-- messages_id_conversation_id_key;` (with a UNIQUE index on (id, +-- conversation_id)) makes the `old` record carry just those two columns. Verify +-- in the Realtime inspector that DELETE events still arrive before relying on +-- it. + +-- ── 4. Unread counts without a per-message scan (optional, recommended) ──── +-- Call: supabase.rpc('get_unread_counts') +-- Returns one row per conversation with a badge, instead of one row per unread +-- message. `last_read_at` already removes the need; this is exact and cheap. + +CREATE OR REPLACE FUNCTION public.get_unread_counts() +RETURNS TABLE (conversation_id UUID, unread_count BIGINT) +LANGUAGE sql +STABLE +SECURITY DEFINER +SET search_path = public +AS $$ + SELECT m.conversation_id, COUNT(*) AS unread_count + FROM public.messages m + JOIN public.conversation_participants cp + ON cp.conversation_id = m.conversation_id + AND cp.user_id = auth.uid() + WHERE m.sender_id <> auth.uid() + AND m.is_deleted = false + AND (cp.last_read_at IS NULL OR m.created_at > cp.last_read_at) + GROUP BY m.conversation_id; +$$; + +GRANT EXECUTE ON FUNCTION public.get_unread_counts() TO authenticated; + + +-- ── 5. Retention (run when you want it — nothing calls it automatically) ─── +-- Egress is paid on read, not on storage, but a smaller table keeps the +-- unread/latest queries from degrading. Deletes soft-deleted rows and anything +-- older than `keep_days` for conversations that are inactive. + +CREATE OR REPLACE FUNCTION public.prune_old_messages(keep_days INTEGER DEFAULT 90) +RETURNS INTEGER +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = public +AS $$ +DECLARE + removed INTEGER := 0; + affected UUID[]; +BEGIN + SELECT array_agg(DISTINCT conversation_id) INTO affected + FROM ( + SELECT m.conversation_id + FROM public.messages m + JOIN public.conversations c ON c.id = m.conversation_id + WHERE m.created_at < NOW() - make_interval(days => keep_days) + AND c.updated_at < NOW() - make_interval(days => keep_days) + ORDER BY m.created_at + LIMIT 5000 + ) t; + + IF affected IS NULL THEN + RETURN 0; + END IF; + + -- The per-row last_message trigger would fire once per deleted row (5000 + -- index scans); the last_message of these inactive conversations is + -- recomputed in one pass below instead. DDL is transactional, so this rolls + -- back with the function if anything fails. + BEGIN + ALTER TABLE public.messages DISABLE TRIGGER trg_sync_conversation_last_message; + EXCEPTION WHEN OTHERS THEN + NULL; -- not the table owner; the trigger just stays on + END; + + DELETE FROM public.messages m + USING ( + SELECT m2.id + FROM public.messages m2 + JOIN public.conversations c ON c.id = m2.conversation_id + WHERE m2.created_at < NOW() - make_interval(days => keep_days) + AND c.updated_at < NOW() - make_interval(days => keep_days) + ORDER BY m2.created_at + LIMIT 5000 + ) stale + WHERE m.id = stale.id; + + GET DIAGNOSTICS removed = ROW_COUNT; + + BEGIN + ALTER TABLE public.messages ENABLE TRIGGER trg_sync_conversation_last_message; + EXCEPTION WHEN OTHERS THEN + NULL; + END; + + UPDATE public.conversations c + SET last_message = x.text, + last_message_at = x.created_at, + last_message_sender_id = x.sender_id + FROM ( + SELECT DISTINCT ON (m.conversation_id) + m.conversation_id, m.text, m.created_at, m.sender_id + FROM public.messages m + WHERE m.conversation_id = ANY(affected) + AND m.is_deleted = false + ORDER BY m.conversation_id, m.created_at DESC + ) x + WHERE c.id = x.conversation_id; + + RETURN removed; +END; +$$; + +-- Example: keep the last 90 days. +-- SELECT public.prune_old_messages(90); +-- Scheduled (needs the pg_cron extension enabled in Dashboard → Database → +-- Extensions): +-- SELECT cron.schedule('prune-messages', '0 4 * * *', $$SELECT public.prune_old_messages(90)$$); + + +-- ── 5b. Optional hardening (commented out — read before enabling) ────────── +-- `conversation_participants` is readable by EVERY authenticated user +-- (`FOR SELECT USING (true)`), which leaks who-talks-to-whom, and `users` is +-- readable the same way, which leaks `email`, `phone`, `lock` (passcode hash!) +-- and `fcm_tokens` of every account. Neither is an egress bug, but both are +-- foundation mistakes worth closing. The membership check below needs a +-- SECURITY DEFINER helper: a policy on the table cannot query the same table +-- (Postgres raises "infinite recursion detected in policy"). +-- +-- CREATE OR REPLACE FUNCTION public.is_conversation_member(conv UUID, uid UUID) +-- RETURNS BOOLEAN LANGUAGE sql STABLE SECURITY DEFINER SET search_path = public +-- AS $$ SELECT EXISTS (SELECT 1 FROM public.conversation_participants +-- WHERE conversation_id = conv AND user_id = uid); $$; +-- +-- DROP POLICY IF EXISTS "Allow auth users to inspect participants" +-- ON public.conversation_participants; +-- CREATE POLICY "Members can inspect their conversations' participants" +-- ON public.conversation_participants FOR SELECT +-- USING (public.is_conversation_member(conversation_id, auth.uid())); +-- +-- DROP POLICY IF EXISTS "Allow public read access on profiles" ON public.users; +-- CREATE POLICY "Profiles are readable, secrets are not" ON public.users +-- FOR SELECT USING (true); -- plus a view/column grants, see +-- -- docs/EGRESS_AUDIT.md §6.4 + + +-- ── 6. Sanity check ──────────────────────────────────────────────────────── +-- Run this afterwards; every row should read like the expected value. +SELECT 'conversation_participants.last_read_at' AS what, + CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END AS state + FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'conversation_participants' + AND column_name = 'last_read_at' +UNION ALL +SELECT 'conversations.last_message_sender_id', + CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END + FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'conversations' + AND column_name = 'last_message_sender_id' +UNION ALL +SELECT 'replica identity: users', + COALESCE((SELECT CASE WHEN c.relreplident = 'f' THEN 'STILL FULL' ELSE 'OK (default)' END + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname = 'users'), 'MISSING') +UNION ALL +SELECT 'replica identity: conversations (expect default)', + COALESCE((SELECT CASE WHEN c.relreplident = 'f' THEN 'STILL FULL' ELSE 'OK (default)' END + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname = 'conversations'), 'MISSING') +UNION ALL +SELECT 'replica identity: messages (expect FULL)', + COALESCE((SELECT CASE WHEN c.relreplident = 'f' THEN 'OK (full)' ELSE 'CHANGED - deletes will stop reaching clients' END + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname = 'messages'), 'MISSING') +UNION ALL +SELECT 'sync trigger on messages', + CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END + FROM pg_trigger + WHERE tgname = 'trg_sync_conversation_last_message' +UNION ALL +SELECT 'UPDATE policy on conversation_participants', + CASE WHEN COUNT(*) FILTER (WHERE cmd = 'UPDATE') > 0 THEN 'OK' ELSE 'MISSING' END + FROM pg_policies + WHERE schemaname = 'public' AND tablename = 'conversation_participants'; + + +-- ══════════════════════════════════════════════════════════════════════════ +-- DONE. Verify with the checklist in sql/00_master_instructions.md +-- ══════════════════════════════════════════════════════════════════════════ diff --git a/sql/legacy/README.md b/sql/legacy/README.md new file mode 100644 index 0000000..21c2486 --- /dev/null +++ b/sql/legacy/README.md @@ -0,0 +1,23 @@ +# Superseded SQL — **do not run these** + +Everything in this folder was replaced by the numbered files in `sql/` +(`01_core_schema.sql` … `09_egress_optimizations.sql`). It is kept only as a +record of what the database used to look like. + +| File | What it is | Why it is here | +|---|---|---| +| `grixchat_latest_db_updates.sql` | An older "run me" patch file with its own copies of the pruners, the `last_message` trigger and profiles policies | Its policies have different names from `01_core_schema.sql`; running both creates **duplicate, conflicting policies**. | +| `supabase_schema.sql` | The original all-in-one schema (create tables + RLS + indexes) | Byte-for-byte superseded by `01_core_schema.sql` + `04_triggers_functions_and_rpc.sql`. | +| `supabase_posts_schema.sql` | Original posts/likes/comments schema | Superseded by `02_posts_and_interactions_schema.sql`. | +| `supabase_support_tickets_schema.sql` | Original support-ticket schema | Superseded by `03_support_tickets_schema.sql`. | +| `superseded_complete_schema.sql` | `db/1_complete_schema.sql` — an early, divergent design (`users.email UNIQUE NOT NULL`, `users.status`, `group_call_participants`, `uuid-ossp`) | **Actively dangerous**: it defines `public.users` differently from `01_core_schema.sql`, so running it on a current project breaks the app. | +| `superseded_realtime_and_security.sql` | `db/2_realtime_and_security.sql` — the matching RLS/realtime pass for that early design | Same reason. | + +Rules that came out of this cleanup: + +1. **`sql/` has exactly one source of truth**: the numbered files, in order. +2. The numbered files are **re-runnable**: they never `DROP TABLE`, and every + `CREATE` is `IF NOT EXISTS` or preceded by `DROP ... IF EXISTS`. +3. Superseded files get moved here, never left next to the live ones — a fork + that runs the wrong file is how a project ends up with two conflicting + schemas. diff --git a/sql/grixchat_latest_db_updates.sql b/sql/legacy/grixchat_latest_db_updates.sql similarity index 100% rename from sql/grixchat_latest_db_updates.sql rename to sql/legacy/grixchat_latest_db_updates.sql diff --git a/sql/supabase_posts_schema.sql b/sql/legacy/supabase_posts_schema.sql similarity index 100% rename from sql/supabase_posts_schema.sql rename to sql/legacy/supabase_posts_schema.sql diff --git a/sql/supabase_schema.sql b/sql/legacy/supabase_schema.sql similarity index 100% rename from sql/supabase_schema.sql rename to sql/legacy/supabase_schema.sql diff --git a/sql/supabase_support_tickets_schema.sql b/sql/legacy/supabase_support_tickets_schema.sql similarity index 100% rename from sql/supabase_support_tickets_schema.sql rename to sql/legacy/supabase_support_tickets_schema.sql diff --git a/db/1_complete_schema.sql b/sql/legacy/superseded_complete_schema.sql similarity index 100% rename from db/1_complete_schema.sql rename to sql/legacy/superseded_complete_schema.sql diff --git a/db/2_realtime_and_security.sql b/sql/legacy/superseded_realtime_and_security.sql similarity index 100% rename from db/2_realtime_and_security.sql rename to sql/legacy/superseded_realtime_and_security.sql diff --git a/src/__tests__/sqlMigrations.test.ts b/src/__tests__/sqlMigrations.test.ts new file mode 100644 index 0000000..d81f6da --- /dev/null +++ b/src/__tests__/sqlMigrations.test.ts @@ -0,0 +1,100 @@ +/** + * Guards for the database setup files in `sql/`. + * + * These are the rules that keep the two supported scenarios true: + * 1. a brand-new Supabase project can run the whole set and end up complete + * 2. an existing project can run the SAME set again, at any time, without an + * error and without losing data + * + * Rule 2 was broken for a long time: `01_core_schema.sql` began with + * `DROP TABLE … CASCADE` for every core table, so re-running "the setup" on a + * live database silently deleted every user, message and post (it reported zero + * errors while doing it). There is a test for that now. + * + * @vitest-environment node + */ +import {execFileSync} from 'node:child_process'; +import {readFileSync, readdirSync} from 'node:fs'; +import {fileURLToPath} from 'node:url'; +import {dirname, join} from 'node:path'; +import {describe, expect, it} from 'vitest'; + +const here = dirname(fileURLToPath(import.meta.url)); +const sqlDir = join(here, '..', '..', 'sql'); +const repoRoot = join(here, '..', '..'); + +/** Every numbered migration, in execution order. */ +const migrations = readdirSync(sqlDir) + .filter((f) => /^0\d_.+\.sql$/.test(f)) + .sort(); + +const sqlOf = (name: string) => readFileSync(join(sqlDir, name), 'utf8'); + +/** SQL with line/block comments removed, so prose about a rule cannot trip it. */ +function code(sql: string) { + return sql.replace(/\/\*[\s\S]*?\*\//g, '').replace(/--[^\n]*/g, ''); +} + +describe('sql/ migrations', () => { + it('covers 01 through 09 and nothing else is left loose', () => { + expect(migrations.map((f) => f.slice(0, 2))).toEqual( + ['01', '02', '03', '04', '05', '06', '07', '08', '09'], + ); + }); + + it('never drops or truncates a table — re-running must not delete data', () => { + const offenders: string[] = []; + for (const file of migrations) { + const body = code(sqlOf(file)); + for (const pattern of [/DROP\s+TABLE/i, /TRUNCATE\s+/i, /DROP\s+SCHEMA/i, /DROP\s+COLUMN/i]) { + if (pattern.test(body)) offenders.push(`${file}: ${pattern}`); + } + } + expect(offenders).toEqual([]); + }); + + it('creates tables idempotently', () => { + for (const file of migrations) { + const creates = code(sqlOf(file)).match(/CREATE\s+TABLE\s+(?!IF\s+NOT\s+EXISTS)/gi) || []; + expect(creates, `${file} has a CREATE TABLE without IF NOT EXISTS`).toEqual([]); + } + }); + + it('drops every policy before re-creating it, so definitions can change', () => { + for (const file of migrations) { + const body = code(sqlOf(file)); + const created = body.match(/CREATE\s+POLICY\s+"([^"]+)"/gi) || []; + const dropped = body.match(/DROP\s+POLICY\s+IF\s+EXISTS\s+"([^"]+)"/gi) || []; + // 01/02/03/06/09 own policies; each CREATE must have a matching DROP IF EXISTS. + expect(created.length, `${file}: more CREATE POLICY than DROP POLICY IF EXISTS`).toBeLessThanOrEqual( + dropped.length, + ); + } + }); + + it('indexes are created with IF NOT EXISTS', () => { + for (const file of migrations) { + const creates = code(sqlOf(file)).match(/CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?!IF\s+NOT\s+EXISTS)/gi) || []; + expect(creates, `${file} has a CREATE INDEX without IF NOT EXISTS`).toEqual([]); + } + }); + + it('the generated one-file bundle is in sync (npm run sql:bundle)', () => { + // Throws (non-zero exit) when the bundle is stale. + const out = execFileSync(process.execPath, [join(repoRoot, 'scripts', 'build-sql-bundle.mjs'), '--check'], { + cwd: repoRoot, + encoding: 'utf8', + }); + expect(out).toMatch(/up to date/); + }); + + it('the bundle contains every migration, in order', () => { + const bundle = readFileSync(join(sqlDir, 'grixchat_full_setup.sql'), 'utf8'); + let cursor = -1; + for (const file of migrations) { + const at = bundle.indexOf(`-- PART ${String(Number(file.slice(0, 2)))}/${migrations.length} — sql/${file}`); + expect(at, `${file} missing from the bundle`).toBeGreaterThan(cursor); + cursor = at; + } + }); +}); From a8f78948c091e71f0b2a47d81eb8cbb17b3cbbd5 Mon Sep 17 00:00:00 2001 From: GothwadTech <295316515+GothwadTech@users.noreply.github.com> Date: Sun, 11 Oct 2026 03:10:22 +0000 Subject: [PATCH 08/11] refactor(sql): 9 setup files -> 01_schema.sql + 02_functions_realtime_storage.sql MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The setup had grown to nine files of wildly different sizes (9 to 832 lines) and the run order was easy to get wrong when forking. Project house rules now: 1. the .md is written first — detail lives there, never in the SQL 2. a file grows until it is 600-1000 lines, then the next number starts 3. every SQL file opens with a short "COVERS:" header Both files were assembled from the previous content and verified against a real PostgreSQL (fresh install, re-run on seeded data, upgrade from the old install shape, repair of missing columns/indexes/policies/triggers) plus behaviour checks on the history cap, the preview trigger, read-marker RLS isolation and get_unread_counts(). - 01_schema.sql (710 lines): core tables, later columns, column upgrades, constraints, RLS + every policy, indexes, posts/likes/comments, support_tickets. - 02_functions_realtime_storage.sql (843 lines): auth trigger + RPCs, story RPCs, read marker + its RLS UPDATE policy, the single chat-list preview trigger, history cap pruners + sweep, get_unread_counts(), prune_old_messages() + optional hardening, replica identity, realtime publication, storage buckets, self-check. Fixed on the way: - 05's insert-only trg_update_conversation_on_message and 09's preview trigger both fired on every message INSERT and both wrote `conversations` (double work, double realtime traffic). Only one trigger is created now, the old one is dropped, and it keeps conversations.updated_at current. - The last_message picks are tie-broken by id, so equal timestamps resolve to a deterministic preview. - 02's §1 re-creates the auth trigger, so the DROP TRIGGER statements moved into the merged file (the first merge attempt lost them and failed on re-run). Removed: the generated one-file bundle and scripts/build-sql-bundle.mjs (with two files it was a sync surface for no benefit), plus the `sql:bundle` npm script. src/__tests__/sqlMigrations.test.ts now enforces all three house rules: no DROP TABLE/TRUNCATE, idempotent CREATEs, policy dropped before re-created, every file 600-1000 lines (the newest may still be filling up), a COVERS: header, and no duplicate preview trigger. 112/112 tests green. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- AGENTS.md | 4 +- README.md | 13 +- dev/mock/seed.ts | 2 +- docs/CONTEXT.md | 6 +- docs/DATA_MODEL.md | 31 +- docs/DEAD_CODE.md | 36 +- docs/DEV_SETUP.md | 11 +- docs/EGRESS_AUDIT.md | 14 +- docs/KNOWN_ISSUES.md | 16 +- docs/TESTING.md | 2 +- package.json | 3 +- scripts/build-sql-bundle.mjs | 91 - sql/00_master_instructions.md | 182 +- sql/{01_core_schema.sql => 01_schema.sql} | 242 ++- sql/02_functions_realtime_storage.sql | 843 +++++++++ sql/02_posts_and_interactions_schema.sql | 120 -- sql/03_support_tickets_schema.sql | 51 - sql/04_triggers_functions_and_rpc.sql | 98 - ...05_advanced_optimizations_and_realtime.sql | 233 --- sql/06_storage_configurations.sql | 93 - sql/07_chat_time_scheduling_migration.sql | 9 - sql/08_stories_expiration_and_views.sql | 42 - sql/09_egress_optimizations.sql | 382 ---- sql/grixchat_full_setup.sql | 1626 ----------------- sql/legacy/README.md | 14 +- src/__tests__/sqlMigrations.test.ts | 88 +- src/features/chat/hooks/useChatMessages.ts | 2 +- src/features/chat/hooks/useConversations.ts | 4 +- .../notifications/NotificationsScreen.tsx | 2 +- src/services/db/notificationService.ts | 2 +- 30 files changed, 1322 insertions(+), 2940 deletions(-) delete mode 100644 scripts/build-sql-bundle.mjs rename sql/{01_core_schema.sql => 01_schema.sql} (65%) create mode 100644 sql/02_functions_realtime_storage.sql delete mode 100644 sql/02_posts_and_interactions_schema.sql delete mode 100644 sql/03_support_tickets_schema.sql delete mode 100644 sql/04_triggers_functions_and_rpc.sql delete mode 100644 sql/05_advanced_optimizations_and_realtime.sql delete mode 100644 sql/06_storage_configurations.sql delete mode 100644 sql/07_chat_time_scheduling_migration.sql delete mode 100644 sql/08_stories_expiration_and_views.sql delete mode 100644 sql/09_egress_optimizations.sql delete mode 100644 sql/grixchat_full_setup.sql diff --git a/AGENTS.md b/AGENTS.md index 1b673dd..328f7db 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -149,7 +149,7 @@ Response bytes are egress, whether or not you render them. the edge: `npx wrangler pages functions build`. The CI workflow does this on every push. - Notifications: write through `services/db/notificationService.ts` only, and - read the `content` column (`sql/01_core_schema.sql` has no `text`). + read the `content` column (`sql/01_schema.sql` has no `text`). ### File size @@ -217,7 +217,7 @@ Rules: | `npm test` | ✅ 104/104 | | `npm run lint` | ✅ 0 errors | | Dead code | ✅ **0 files** — 189/189 reachable. See [`docs/DEAD_CODE.md`](./docs/DEAD_CODE.md) | -| SQL migrations | ✅ re-runnable (fresh install + re-run on live data verified); `npm run sql:bundle` in sync, guarded by `src/__tests__/sqlMigrations.test.ts` | +| SQL migrations | ✅ `01_schema.sql` + `02_functions_realtime_storage.sql`, both re-runnable (fresh install + re-run on live data verified), 600–1000 lines each, guarded by `src/__tests__/sqlMigrations.test.ts` | | Tables queried but missing from `sql/` | ✅ 0 | | RPCs called but missing from `sql/` | ✅ 0 | | Cloudflare Pages deploy | ✅ `dist/` + `functions/` → | diff --git a/README.md b/README.md index af7c1c4..4444d9a 100644 --- a/README.md +++ b/README.md @@ -41,12 +41,13 @@ To support more than 50,000 active users comfortably on Supabase's free tier, da - `/src/providers`: Application context singletons (Supabase `AuthProvider`, global WebRTC `CallProvider`). - `/src/features`: Modular screens broken into focus zones (`chat`, `call`, `profile`, `search`, `stories`, `github`, `grixai`). - `/src/components`: UI layouts, bottom/top navigation components, and global drop-downs. -- `/sql`: The **only** place for schema — numbered migrations `01_` … `09_`, plus - `00_master_instructions.md` (the runbook) and `grixchat_full_setup.sql` (all of - them in one paste, generated by `npm run sql:bundle`). Contains tables, - PostgreSQL functions, triggers, row-level security and indices. **Every file is - safe to re-run**: nothing is dropped, missing objects are created, policies are - re-created. Superseded files live in `/sql/legacy` — never run those. +- `/sql`: The **only** place for schema — `01_schema.sql` (tables, policies, + indexes) and `02_functions_realtime_storage.sql` (functions, triggers, realtime, + storage, the egress work), plus `00_master_instructions.md` (the runbook). + **Both files are safe to re-run**: nothing is dropped, missing objects are + created, policies and functions are re-created. New SQL is appended to the + current file until it reaches 600–1000 lines, *then* the next number starts; + superseded files live in `/sql/legacy` — never run those. - `/server/api.ts`: **The API.** Runtime-neutral (Web `Request`/`Response`), so the same file serves Cloudflare Pages Functions and the Express dev server. - `/functions`: Cloudflare Pages Functions — thin adapters that forward `/api/*` and `/auth/*` to `server/api.ts`. - `/docs`: Developer documentation — orientation, setup, testing, data model, known issues. diff --git a/dev/mock/seed.ts b/dev/mock/seed.ts index 3ec9f78..87ef799 100644 --- a/dev/mock/seed.ts +++ b/dev/mock/seed.ts @@ -360,7 +360,7 @@ export function buildSeed() { id: `p${String(pIdx++).padStart(35, '0')}`, conversation_id, user_id, - // Read marker (sql/09_egress_optimizations.sql). Unread is derived from + // Read marker (sql/02_functions_realtime_storage.sql). Unread is derived from // `last_read_at` instead of scanning every unread message row. last_read_at: daysAgo(1), created_at: daysAgo(28), diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index fb5cae3..2f36182 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -169,8 +169,10 @@ The long version is in **[../AGENTS.md](../AGENTS.md)**. Short version: ticks, call signalling, presence → `channel().send()`, 0 bytes of egress. 3. **Don't import across sibling features.** `features/chat/` must not reach into `features/call/`. Go through `services/` or a provider. -4. **SQL changes go in `/sql/`, numbered** (`10_…`, appended to - `scripts/build-sql-bundle.mjs`, then `npm run sql:bundle`). Migrations must be +4. **SQL changes go in `/sql/`.** Write the `.md` first (here or in + `EGRESS_AUDIT.md`), then the SQL. Append to the current file until it reaches + **600–1000 lines**, then start the next number — no tiny files, no 2000-line + files, and every file needs a short `COVERS:` header. Migrations must be re-runnable: no `DROP TABLE`, `CREATE … IF NOT EXISTS`, `CREATE OR REPLACE`, `DROP POLICY IF EXISTS` before every policy. Superseded files go to `sql/legacy/` — never recreate root-level duplicates. Runbook: diff --git a/docs/DATA_MODEL.md b/docs/DATA_MODEL.md index a244c65..017cd5d 100644 --- a/docs/DATA_MODEL.md +++ b/docs/DATA_MODEL.md @@ -1,15 +1,18 @@ # Data Model -> `sql/` is the **only** authoritative schema: numbered migrations `01_` … `09_`, -> run in that order. Old copies are parked in [`sql/legacy/`](../sql/legacy/README.md) -> (never run them — they define the same tables differently). +> `sql/` is the **only** authoritative schema: [`01_schema.sql`](../sql/01_schema.sql) +> (tables, policies, indexes) then +> [`02_functions_realtime_storage.sql`](../sql/02_functions_realtime_storage.sql) +> (functions, triggers, realtime, storage). Old copies are parked in +> [`sql/legacy/`](../sql/legacy/README.md) (never run them — they define the same +> tables differently). > -> **Every file is re-runnable.** A new project can paste -> [`sql/grixchat_full_setup.sql`](../sql/grixchat_full_setup.sql); an existing -> project can run the same set again to pick up missing columns, indexes, -> constraints, buckets and updated policies. Nothing is ever dropped. Runbook + -> verification queries: [`sql/00_master_instructions.md`](../sql/00_master_instructions.md). -> The rule is enforced by `src/__tests__/sqlMigrations.test.ts`. +> **Every file is re-runnable.** A new project runs both; an existing project runs +> the same two again to pick up missing columns, indexes, constraints, buckets and +> updated policies. Nothing is ever dropped. Runbook + verification queries: +> [`sql/00_master_instructions.md`](../sql/00_master_instructions.md). The rules +> (re-runnable, 600–1000 lines, `COVERS:` header) are enforced by +> `src/__tests__/sqlMigrations.test.ts`. --- @@ -34,7 +37,7 @@ Vibe features. ## Tables -### `users` — `sql/01_core_schema.sql:30` +### `users` — `sql/01_schema.sql` Profile row, 1:1 with `auth.users`. | Column | Type | Notes | @@ -84,7 +87,7 @@ Profile row, 1:1 with `auth.users`. `created_at`. > The `view_story` RPC writes a `views` array — check the migration in -> `sql/08_stories_expiration_and_views.sql` for the actual column. +> `sql/01_schema.sql (§2) + sql/02_functions_realtime_storage.sql (§2)` for the actual column. ### `calls` — `:122` `id`, `caller_id`, `receiver_id`, `type` (`audio`/`video`), @@ -110,16 +113,16 @@ Per-user chat customisation. `id`, `user_id`, `receiver_id`, `nickname`, > and the offline follow worker. Readers use `content` — the column the schema > defines — and the writer only writes `content`. > -> Writes need no new policy: `sql/01_core_schema.sql` already grants +> Writes need no new policy: `sql/01_schema.sql` already grants > `INSERT` on `notifications` to `authenticated`, and `UPDATE` to the row owner > (used to mark notifications read). -### `posts` — `sql/02_posts_and_interactions_schema.sql` +### `posts` — `sql/01_schema.sql (§8)` `id`, `user_id`, `image_url`, `caption`, `created_at`. ### `post_likes` — composite PK `(post_id, user_id)`, plus `created_at`. ### `post_comments` — `id`, `post_id`, `user_id`, `text`, `created_at`. -### `support_tickets` — `sql/03_support_tickets_schema.sql`. +### `support_tickets` — `sql/01_schema.sql (§9)`. --- diff --git a/docs/DEAD_CODE.md b/docs/DEAD_CODE.md index c0da34f..fb84992 100644 --- a/docs/DEAD_CODE.md +++ b/docs/DEAD_CODE.md @@ -211,10 +211,10 @@ procedure is: | Moved | From | Why | |---|---|---| -| `grixchat_latest_db_updates.sql` | `sql/` | Older patch file with duplicate, differently-named policies — running it next to `01_core_schema.sql` created conflicting RLS | -| `supabase_schema.sql` | `sql/` | Superseded by `01_core_schema.sql` | -| `supabase_posts_schema.sql` | `sql/` | Superseded by `02_posts_and_interactions_schema.sql` | -| `supabase_support_tickets_schema.sql` | `sql/` | Superseded by `03_support_tickets_schema.sql` | +| `grixchat_latest_db_updates.sql` | `sql/` | Older patch file with duplicate, differently-named policies — running it next to `01_schema.sql` created conflicting RLS | +| `supabase_schema.sql` | `sql/` | Superseded by `01_schema.sql` | +| `supabase_posts_schema.sql` | `sql/` | Superseded by `01_schema.sql` | +| `supabase_support_tickets_schema.sql` | `sql/` | Superseded by `01_schema.sql` | | `db/1_complete_schema.sql` | `db/` | Early divergent design: `users.email UNIQUE NOT NULL`, `users.status`, `group_call_participants` — **would break a current project if run** | | `db/2_realtime_and_security.sql` | `db/` | The matching RLS pass for that design | | `db/3_webrtc_signaling_architecture.md` | `db/` → `docs/legacy/` | Design note for signalling that was never adopted (calling uses Broadcast) | @@ -222,8 +222,34 @@ procedure is: All seven now live in [`sql/legacy/`](../sql/legacy/README.md) — parked, not deleted, with a README explaining that they must not be run. -Also fixed in the same pass: `01_core_schema.sql`, `02_…` and `03_…` began with +Also fixed in the same pass: `01_schema.sql`, `02_…` and `03_…` began with `DROP TABLE … CASCADE`. Re-running the documented setup on a live project therefore **deleted every user, message and post while reporting zero errors**. The drops are gone; the files are idempotent now, and `src/__tests__/sqlMigrations.test.ts` fails if anyone adds one back. + +## 2026-10-11 (later) — SQL files consolidated from 9 files into 2 + +The setup had grown to nine files of very different sizes (9 to 832 lines), which +made the run order fragile for anyone forking the repo. They were merged into two +files that each sit in the 600–1000 line band the project now uses: + +| Was | Now | +|---|---| +| `01_core_schema.sql`, `02_posts_and_interactions_schema.sql`, `03_support_tickets_schema.sql`, `07_chat_time_scheduling_migration.sql`, `08_stories_expiration_and_views.sql` (tables/policies/indexes parts) | **`01_schema.sql`** — every table, column, constraint, policy and index | +| `04_triggers_functions_and_rpc.sql`, `05_advanced_optimizations_and_realtime.sql`, `06_storage_configurations.sql`, `08_…` (RPCs), `09_egress_optimizations.sql` | **`02_functions_realtime_storage.sql`** — functions, triggers, realtime, storage, read marker | +| `grixchat_full_setup.sql` (generated bundle) + `scripts/build-sql-bundle.mjs` | deleted — with only two files the bundle added a sync surface for no benefit | + +Two things got better on the way, not just smaller: + +* `05`'s insert-only `trg_update_conversation_on_message` and `09`'s + `trg_sync_conversation_last_message` both fired on every message INSERT and both + wrote `conversations` — double work and double realtime traffic per message. Only + the surviving trigger is created now, `02` explicitly drops the old one, and it + also keeps `conversations.updated_at` current (which the old one did). +* The `last_message` picks are now tie-broken by `id`, so a conversation with two + messages sharing a timestamp always resolves to the same preview. + +`src/__tests__/sqlMigrations.test.ts` now also enforces the new house rules: every +file between 600 and 1000 lines (the newest one may still be filling up), and a +short `COVERS:` header at the top of each file instead of long prose. diff --git a/docs/DEV_SETUP.md b/docs/DEV_SETUP.md index 7454636..c189a39 100644 --- a/docs/DEV_SETUP.md +++ b/docs/DEV_SETUP.md @@ -99,11 +99,12 @@ keeps the messages you sent. `__grixMock.reset()` clears it. Required for: RLS verification, multi-device realtime, actual FCM push, actual file storage. -**1. Prepare the database first.** Supabase → SQL Editor → paste -[`sql/grixchat_full_setup.sql`](../sql/grixchat_full_setup.sql) → RUN. One paste -creates every table, policy, bucket, trigger and function, and it is safe to run -again later (nothing is dropped — see -[`sql/00_master_instructions.md`](../sql/00_master_instructions.md)). Without it +**1. Prepare the database first.** Supabase → SQL Editor → run +[`sql/01_schema.sql`](../sql/01_schema.sql), then +[`sql/02_functions_realtime_storage.sql`](../sql/02_functions_realtime_storage.sql). +Two pastes create every table, policy, bucket, trigger and function, and both are +safe to run again later (nothing is dropped — see +[`sql/00_master_instructions.md`](../sql/00_master_instructions.md)). Without them the app signs in and then shows nothing. **2. Then run the app:** diff --git a/docs/EGRESS_AUDIT.md b/docs/EGRESS_AUDIT.md index 398193c..0798fdc 100644 --- a/docs/EGRESS_AUDIT.md +++ b/docs/EGRESS_AUDIT.md @@ -2,7 +2,7 @@ **Status:** the dominant cause is **found, measured and fixed in code**; the database half needs one SQL file run by hand -([`sql/09_egress_optimizations.sql`](../sql/09_egress_optimizations.sql)). +([`sql/02_functions_realtime_storage.sql`](../sql/02_functions_realtime_storage.sql)). **Symptom:** 5 GB of Supabase egress in under a month. 2–3 active users, 2–3 hours of chatting a day, almost no files shared. 70–80 % of the bill with @@ -36,7 +36,7 @@ Ranked by impact. Line references are to the code *before* this audit's fix. | 2 | **Read receipts were one UPDATE per unread message.** `markAsRead` ran `UPDATE messages SET is_read = true WHERE … is_read = false`; Postgres emits one WAL row-change per row, and Realtime broadcasts each one. | `src/features/chat/hooks/useChatMessages.ts` | **30 unread → 30 events → 30 × 127 KB** in the other client | | 3 | **The newest-messages query.** Every refetch pulled `.limit(max(50, conversations × 5))` full message rows ordered across *all* chats — to draw a one-line preview that the `conversations.last_message` column already had. | same as #1 | 30 rows = 6.5 KB → 135 rows = **36.7 KB** | | 4 | **`select('*')` with a nested `users(*)`.** Every participant came back as the *entire* user row — `settings` jsonb, `lock` (the passcode hash), `fcm_tokens`, six arrays. The list renders six columns. | same as #1 | **0.83 KB per participant row** vs ~0.15 KB needed | -| 5 | **`REPLICA IDENTITY FULL`** on `users`, `messages`, `conversations`, `calls`. Every UPDATE broadcasts the complete OLD row *and* the complete NEW row to every subscriber. | `sql/05_advanced_optimizations_and_realtime.sql:120-124` (5 tables, incl. `call_candidates`) | 2× payload on every update, and ships the passcode hash | +| 5 | **`REPLICA IDENTITY FULL`** on `users`, `messages`, `conversations`, `calls`. Every UPDATE broadcasts the complete OLD row *and* the complete NEW row to every subscriber. | `sql/02_functions_realtime_storage.sql` §8 (5 tables, incl. `call_candidates`) | 2× payload on every update, and ships the passcode hash | | 6 | **Unread counted by downloading messages.** `.select('conversation_id').eq('is_read', false)` — one row per unread message, uncapped, on **every** refetch, in **two** components (`useConversations` *and* `TabBottom`). | `useConversations.ts`, `src/components/layout/TabBottom.tsx` | 84 rows = 4.8 KB, unbounded with backlog | | 7 | **Follows re-fetched every time.** The full follow graph in both directions, on every refetch, though it changes only when someone follows. | `useConversations.ts` | 60 rows = **6.4 KB per refetch** | | 8 | **A channel per conversation.** 20 chats = 20 Realtime channels × 2 table bindings, re-created whenever the list identity changed (which the refetch itself caused). | `useConversations.ts` | connection churn, 40+ bindings | @@ -128,14 +128,14 @@ feature-detected once per session and falls back to the old behaviour. ## 5. What only you can run (2 minutes) Supabase dashboard → **SQL Editor** → paste -[`sql/09_egress_optimizations.sql`](../sql/09_egress_optimizations.sql) → Run. +[`sql/02_functions_realtime_storage.sql`](../sql/02_functions_realtime_storage.sql) → Run. It is idempotent, and it ends with a self-check query. What it does: 1. **`conversation_participants.last_read_at`** (+ index **+ a missing RLS UPDATE policy**) — the read marker. The policy matters: RLS is enabled on - that table and `01_core_schema.sql` defines SELECT/INSERT/DELETE only, so an + that table and `01_schema.sql` defines SELECT/INSERT/DELETE only, so an UPDATE matches no policy, changes **0 rows and reports no error** — the marker would silently never move. 2. **A trigger that maintains `conversations.last_message*`** (including @@ -180,7 +180,7 @@ You asked whether the schema itself is wrong. Partly yes: means "who read this" is answered by writing N rows, and every row is a Realtime event. The normal model is one `last_read_at` per participant — which also makes unread a comparison, not a scan. **This is the single - biggest design fix** and it is in `09_egress_optimizations.sql`. + biggest design fix** and it is in `02_functions_realtime_storage.sql`. 2. **`REPLICA IDENTITY FULL` on hot, wide, private tables.** It was added so DELETE/UPDATE filters would work, but it doubles every UPDATE payload and leaks private columns. The right split is: `FULL` only where a *filtered @@ -208,13 +208,13 @@ You asked whether the schema itself is wrong. Partly yes: and no UPDATE policy, writes succeed "silently" by affecting zero rows — the most expensive kind of bug to find. Any table the client writes to needs a policy per verb; this one only ever had SELECT/INSERT/DELETE. Fixed in - `09_egress_optimizations.sql`. + `02_functions_realtime_storage.sql`. 8. **`FOR SELECT USING (true)` on `users` and `conversation_participants`.** Every authenticated account can read every other account's `email`, `phone`, `lock` (passcode hash), `fcm_tokens`, *and* the whole who-talks-to-whom graph. The code fix here (never select secrets, name the columns) stops the *egress*, not the *exposure* — hardening SQL is included as a commented block - at the end of `09_egress_optimizations.sql` because it needs a + at the end of `02_functions_realtime_storage.sql` because it needs a `SECURITY DEFINER` helper before it can be switched on. Nothing here requires a rewrite. Items 1–3 are the ones worth doing now, while diff --git a/docs/KNOWN_ISSUES.md b/docs/KNOWN_ISSUES.md index c18ae24..c436622 100644 --- a/docs/KNOWN_ISSUES.md +++ b/docs/KNOWN_ISSUES.md @@ -25,7 +25,7 @@ dashboard, Supabase, or a decision. | C | Confirm the Pages build settings: build command `npm run build`, output `dist`, root `/`; production branch = your main branch; custom domain `grixchat.gothwadtech.com` attached | Cloudflare → the project's Settings / Custom domains | `wrangler.toml` pins the output dir and compatibility date, but the dashboard values win. | | D | Decide the fate of `call_candidates` (issue 7) | Supabase SQL editor | It is defined but unused. Drop it with:
`DROP TABLE IF EXISTS public.call_candidates CASCADE;`
or keep it and adopt the table-based signalling in [`docs/legacy/3_webrtc_signaling_architecture.md`](./legacy/3_webrtc_signaling_architecture.md). | | E | Add a **Cloudflare Rate Limiting Rule** on `/api/*` (optional, but recommended before scaling) | Cloudflare → Security → WAF | The limiter in `server/api.ts` counts in memory, i.e. per isolate — a speed bump, not a hard global quota. | -| F | Run **`sql/grixchat_full_setup.sql`** (2 minutes, idempotent, ends with a self-check) — or just `09_egress_optimizations.sql` if you only want the egress fixes | Supabase → SQL Editor | Creates anything missing and updates every policy/function. For the egress work specifically: read receipts become one row instead of one per unread message, the chat-list preview is maintained by a trigger, `REPLICA IDENTITY` stops shipping whole rows + the passcode hash, and the missing RLS UPDATE policy on `conversation_participants` gets created. Runbook: [`../sql/00_master_instructions.md`](../sql/00_master_instructions.md). Full analysis: [EGRESS_AUDIT.md](./EGRESS_AUDIT.md). | +| F | Run **`sql/01_schema.sql`** then **`sql/02_functions_realtime_storage.sql`** (2 minutes, idempotent, `02` ends with a self-check) | Supabase → SQL Editor | Creates anything missing and updates every policy/function. For the egress work specifically: read receipts become one row instead of one per unread message, the chat-list preview is maintained by a trigger, `REPLICA IDENTITY` stops shipping whole rows + the passcode hash, and the missing RLS UPDATE policy on `conversation_participants` gets created. Runbook: [`../sql/00_master_instructions.md`](../sql/00_master_instructions.md). Full analysis: [EGRESS_AUDIT.md](./EGRESS_AUDIT.md). | | G | Decide whether to enable the **RLS hardening** block at the end of that same file (commented out) | Supabase → SQL Editor | Today `users` and `conversation_participants` are readable by every authenticated account: `email`, `phone`, `lock` (passcode hash), `fcm_tokens`, and the whole follow/participant graph. | Optional: set `ALLOWED_ORIGINS=https://your-domain.tld,https://your-other.tld` @@ -106,7 +106,7 @@ follow itself. Covered by `src/__tests__/notificationService.test.ts` (6 tests). ### 5. `notifications` column mismatch — ✅ FIXED -`sql/01_core_schema.sql` is right: the column is `content`. Both readers now +`sql/01_schema.sql` is right: the column is `content`. Both readers now map `content` (with a `text` fallback kept only for rows written by older builds), and the new writer only ever writes `content`. The mock seeds both and the mock now applies the `is_read DEFAULT FALSE` the SQL declares. @@ -232,9 +232,8 @@ a call, so `drop` rightly leaves it alone. ### 20. `01`–`03` began with `DROP TABLE … CASCADE`, so "just run it again" wiped the database -`01_core_schema.sql` opened with `DROP TABLE IF EXISTS public.users CASCADE;` and -the same line for every other core table (`02` and `03` did it for posts and -tickets). The documented setup flow is "run these files in order", so re-running +The setup opened with `DROP TABLE IF EXISTS public.users CASCADE;` and the same +line for every other core table (posts and tickets too). The documented setup flow is "run these files in order", so re-running it on a project with users — the normal way to apply a schema update — silently deleted every user, message, conversation, post and ticket, **while reporting zero errors**, which is exactly why nobody noticed. @@ -244,8 +243,9 @@ zero errors**, which is exactly why nobody noticed. (`ADD COLUMN IF NOT EXISTS`), indexes, constraints, buckets, plus `DROP POLICY IF EXISTS` + `CREATE POLICY` so an updated policy definition actually replaces the old one. Existing rows are never touched. -- **One file to run:** `sql/grixchat_full_setup.sql` (generated by - `npm run sql:bundle`) — fresh project or existing one, same paste. +- **Same two files for everyone:** `sql/01_schema.sql` then + `sql/02_functions_realtime_storage.sql` — fresh project or existing one, no + separate "upgrade" path. - **Docs:** [`../sql/00_master_instructions.md`](../sql/00_master_instructions.md) (runbook + verification queries + troubleshooting). - **Superseded files moved out of the way** to `sql/legacy/` — including @@ -277,7 +277,7 @@ what the dashboard showed. columns, cached follows, read-receipt writes collapsed into one row, and photos are downscaled + cached for a year. Regression tests: `src/__tests__/egressBudget.test.ts`, `src/__tests__/egressRealtime.test.tsx`. -- **Needs you:** run `sql/09_egress_optimizations.sql` (row F above). +- **Needs you:** run `sql/02_functions_realtime_storage.sql` (row F above). - **Analysis, measurements, database-foundation mistakes, caching plan:** [EGRESS_AUDIT.md](./EGRESS_AUDIT.md). diff --git a/docs/TESTING.md b/docs/TESTING.md index 1053447..86b6f5c 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -60,7 +60,7 @@ explicitly: everything looks identical to a working filter in a happy-path test > **Testing the notification writer:** assert on the `content` column, not -> `text` — `sql/01_core_schema.sql` has no `text` column. The mock now mirrors +> `text` — `sql/01_schema.sql` has no `text` column. The mock now mirrors > the SQL default (`is_read boolean default false`) so an insert that forgets > the flag fails a test instead of passing locally. diff --git a/package.json b/package.json index ab03dee..bacba7c 100644 --- a/package.json +++ b/package.json @@ -21,8 +21,7 @@ "test:watch": "vitest", "test:ui": "vitest --ui", "lint": "tsc --noEmit", - "clean": "rm -rf dist", - "sql:bundle": "node scripts/build-sql-bundle.mjs" + "clean": "rm -rf dist" }, "dependencies": { "@livekit/components-react": "^2.9.21", diff --git a/scripts/build-sql-bundle.mjs b/scripts/build-sql-bundle.mjs deleted file mode 100644 index fff1950..0000000 --- a/scripts/build-sql-bundle.mjs +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env node -/** - * Builds `sql/grixchat_full_setup.sql` by concatenating the numbered migrations - * in order, so a new fork can paste ONE file into the Supabase SQL editor. - * - * The numbered files stay the source of truth. Run: - * npm run sql:bundle # regenerate - * npm run sql:bundle -- --check # fail if the bundle is stale (CI + tests) - */ -import {readFileSync, writeFileSync, existsSync} from 'node:fs'; -import {fileURLToPath} from 'node:url'; -import {dirname, join} from 'node:path'; - -const here = dirname(fileURLToPath(import.meta.url)); -const sqlDir = join(here, '..', 'sql'); -const OUT = join(sqlDir, 'grixchat_full_setup.sql'); - -const FILES = [ - '01_core_schema.sql', - '02_posts_and_interactions_schema.sql', - '03_support_tickets_schema.sql', - '04_triggers_functions_and_rpc.sql', - '05_advanced_optimizations_and_realtime.sql', - '06_storage_configurations.sql', - '07_chat_time_scheduling_migration.sql', - '08_stories_expiration_and_views.sql', - '09_egress_optimizations.sql', -]; - -const rule = '-- ' + '═'.repeat(74); - -function banner(name, index, total) { - return `${rule} --- PART ${index}/${total} — sql/${name} --- (generated from the file of that name; edit THAT file, then re-run --- "npm run sql:bundle" — do not edit this bundle by hand) -${rule} -`; -} - -export function buildBundle() { - const parts = [ - `${rule} --- GRIXCHAT — COMPLETE SUPABASE SETUP (generated, do not edit by hand) -${rule} --- One paste for a brand-new Supabase project: --- Supabase Dashboard -> SQL Editor -> New query -> paste ALL of this -> RUN. --- --- Safe to run again later, on the same project, at any time: --- * nothing is dropped or truncated --- * tables/columns/indexes/constraints are created only when missing --- * policies and functions are re-created, so updated definitions apply --- * existing rows are never modified --- --- Generated by: npm run sql:bundle (source: sql/01_*.sql … sql/09_*.sql) --- Read first: sql/00_master_instructions.md -${rule} -`, - ]; - - FILES.forEach((name, i) => { - const path = join(sqlDir, name); - if (!existsSync(path)) throw new Error(`missing migration: ${name}`); - parts.push('\n' + banner(name, i + 1, FILES.length) + '\n' + readFileSync(path, 'utf8').trimEnd() + '\n'); - }); - - parts.push(`\n${rule} --- DONE. Verify with the checklist in sql/00_master_instructions.md -${rule} -`); - return parts.join('\n'); -} - -export function readBundle() { - return existsSync(OUT) ? readFileSync(OUT, 'utf8') : null; -} - -const isCheck = process.argv.includes('--check'); -const expected = buildBundle(); -const current = readBundle(); - -if (isCheck) { - if (current !== expected) { - console.error('sql/grixchat_full_setup.sql is STALE — run: npm run sql:bundle'); - process.exit(1); - } - console.log('sql bundle is up to date'); -} else { - writeFileSync(OUT, expected); - console.log(`wrote sql/grixchat_full_setup.sql (${expected.split('\n').length} lines)`); -} diff --git a/sql/00_master_instructions.md b/sql/00_master_instructions.md index 0d77b0c..e9bc351 100644 --- a/sql/00_master_instructions.md +++ b/sql/00_master_instructions.md @@ -1,77 +1,95 @@ # GrixChat — Supabase setup (read this first) -Everything the app needs in the database lives in this folder. There are two -supported ways to run it, and **both are safe to run on a project that already -has data** — nothing here drops a table, truncates a row, or overwrites a -column. Re-running the whole set is the supported way to pick up a schema -update. - -| You are… | Run | Time | -|---|---|---| -| **starting fresh** (new fork, new Supabase project) | [`grixchat_full_setup.sql`](./grixchat_full_setup.sql) — everything in one paste | ~30 s | -| **updating an existing project** | the same file, again. Or `01` … `09` one by one if you prefer to see each step | ~30 s | -| **verifying after a deploy** | the checklist at the bottom of this file | ~2 min | - -> Prefer the individual files? Run them **in numerical order**: -> `01_core_schema.sql` → `02_posts_and_interactions_schema.sql` → … → -> `09_egress_optimizations.sql`. The bundle is generated from exactly those -> files in that order, so the result is identical. -> -> `npm run sql:bundle` regenerates the bundle after you edit a numbered file. -> `src/__tests__/sqlMigrations.test.ts` fails if the bundle is stale — or if -> anyone reintroduces a `DROP TABLE` or a non-idempotent `CREATE`. +Everything the app needs in the database is in this folder, in **two files**. +Run them in order and, from then on, **run them again whenever the app is +updated** — that is the supported way to pick up a schema change. + +| # | File | What it holds | Runs | +|---|---|---|---| +| 1 | [`01_schema.sql`](./01_schema.sql) | every table, column, constraint, RLS policy and index | ~10 s | +| 2 | [`02_functions_realtime_storage.sql`](./02_functions_realtime_storage.sql) | functions, triggers, realtime publication, storage buckets, the read marker / egress work | ~15 s | + +Both are **safe to run at any time, on a brand-new project or on one that is +already live**: nothing is dropped or truncated, missing tables/columns/indexes/ +buckets/constraints are created, and policies and functions are re-created so an +updated definition replaces the old one. Existing rows are never modified. +`02` ends with a self-check query — every row must read `OK`. + +> **Adding to this folder later?** Two rules, both enforced by +> `src/__tests__/sqlMigrations.test.ts`: +> 1. **Documentation first.** Describe the change in this file (or in +> [`../docs/EGRESS_AUDIT.md`](../docs/EGRESS_AUDIT.md) for egress work) +> *before* writing SQL. Detail belongs in the `.md`, never in the `.sql`. +> 2. **Keep files between 600 and 1000 lines.** Append to the current file until +> it is full, *then* start the next number (`03_…`). Do not create a new file +> for a small change, and do not let a file grow past 1000 lines. +> Every file starts with a short `COVERS:` comment — one line per area, no detail. --- ## 1. New project (fork → deploy) 1. Create the Supabase project, then **SQL Editor → New query**. -2. Paste **all** of [`grixchat_full_setup.sql`](./grixchat_full_setup.sql) and - press **RUN**. It is one transaction-free script: every statement is - idempotent, so a partial run just means "run it again". -3. Copy **Project URL** + **anon key** (Settings → API) into the frontend env: +2. Paste **all** of [`01_schema.sql`](./01_schema.sql) → **RUN**. +3. New query → paste **all** of + [`02_functions_realtime_storage.sql`](./02_functions_realtime_storage.sql) → + **RUN**. Read the output: the last result set is the self-check. +4. Copy **Project URL** + **anon key** (Settings → API) into the frontend env: `VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY`. On Cloudflare Pages these are build-time variables — see [`../docs/DEV_SETUP.md`](../docs/DEV_SETUP.md). -4. Turn on **Authentication → Providers** (email, Google/GitHub if you use - them) and add your site URL to **Authentication → URL configuration**. -5. Run the verification checklist below. +5. Turn on **Authentication → Providers** (email, Google/GitHub if you use them) + and add your site URL to **Authentication → URL configuration**. +6. Run the verification checklist in §4. ## 2. Existing project (schema update) -Paste the same file again. What it does on a live database: +Run the same two files again, in the same order. On a live database they: -* **creates** anything missing — tables, columns (`last_read_at`, +* **create** anything missing — tables, columns (`last_read_at`, `last_message_sender_id`, `chat_time_restrictions`, `stories.views`, `profile_type`, …), indexes, constraints, storage buckets; -* **re-creates** policies and functions, so an updated definition replaces the - old one (that is how the SQL "update" reaches a project that was set up - earlier); -* **never touches** existing rows, and never drops a table or a column. - -Two deliberate exceptions, both about *message history*, and both parts of the -app's existing design — read them before you run: -`05_advanced_optimizations_and_realtime.sql` caps every chat at the newest -**40 messages** (sections 1 and 6). If you want history kept instead, skip -those two sections and use the time-based `prune_old_messages(days)` from `09`. - -## 3. What each file does - -| File | Creates | Notes | -|---|---|---| -| `01_core_schema.sql` | `users`, `follows`, `conversations`, `conversation_participants`, `messages`, `stories`, `calls`, `call_candidates`, `chat_settings`, `notifications` + RLS + indexes | column upgrades for older installs, constraints added only when missing | -| `02_posts_and_interactions_schema.sql` | `posts`, `post_likes`, `post_comments` + RLS + indexes | | -| `03_support_tickets_schema.sql` | `support_tickets` + RLS | | -| `04_triggers_functions_and_rpc.sql` | `get_direct_conversation_id()`, `handle_new_auth_user()` + the `auth.users` → `public.users` trigger | this is what creates a profile on signup/OAuth | -| `05_advanced_optimizations_and_realtime.sql` | realtime publication membership, preview triggers, replica identity, **40-message cap** | see the warning above | -| `06_storage_configurations.sql` | `chat-media` + `profiles` buckets and their storage policies | buckets are public-read on purpose | -| `07_chat_time_scheduling_migration.sql` | `conversations.chat_time_restrictions` | | -| `08_stories_expiration_and_views.sql` | `stories.views`, `view_story()`, `cleanup_expired_stories()` | | -| `09_egress_optimizations.sql` | `conversation_participants.last_read_at` **+ its RLS UPDATE policy**, the `last_message*` trigger, replica-identity fixes, indexes, `get_unread_counts()`, `prune_old_messages()` | ends with a self-check query — see below. Full reasoning: [`../docs/EGRESS_AUDIT.md`](../docs/EGRESS_AUDIT.md) | +* **re-create** policies and functions, so an updated definition replaces the + old one — that is how a SQL "update" reaches a project that was set up earlier; +* **never** touch existing rows and never drop a table or a column. + +Two deliberate exceptions, both about *message history*, both part of the app's +existing design — read them before you run `02`: +the history cap in `02` keeps only the newest **40 messages per chat**. If you +want history kept instead, skip that section (it is marked) and use the +time-based `prune_old_messages(days)` instead. + +## 3. What is inside + +### `01_schema.sql` + +| Section | Creates | +|---|---| +| Core tables | `users`, `follows`, `conversations`, `conversation_participants`, `messages`, `stories`, `calls`, `call_candidates`, `chat_settings`, `notifications` | +| Later columns | `conversations.chat_time_restrictions`, `stories.views` | +| Column upgrades | every column of every table, via `ADD COLUMN IF NOT EXISTS` (for projects created by an older version of this file) | +| Constraints | unique pairs, username length, `post_likes` primary key — added only when absent | +| RLS | row-level security enabled + every policy for the tables above (`DROP POLICY IF EXISTS` first, so edits apply) | +| Posts & tickets | `posts`, `post_likes`, `post_comments`, `support_tickets` with their policies and indexes | +| Indexes | all search and join indexes | + +### `02_functions_realtime_storage.sql` + +| Section | Creates | +|---|---| +| Auth → profile | `handle_new_auth_user()` + the `auth.users` trigger (creates the profile on signup/OAuth), `get_direct_conversation_id()` | +| Stories | `view_story()`, `cleanup_expired_stories()` | +| Read marker | `conversation_participants.last_read_at` **+ its RLS UPDATE policy** + index — unread becomes a comparison instead of a per-message scan | +| Chat-list preview | one `last_message*` trigger (insert, edit, delete, soft delete) — supersedes the older duplicate trigger, which is dropped | +| History cap | `prune_past_messages`, `prune_past_calls` + a one-time sweep (⚠️ deletes history, see §2) | +| Counts & retention | `get_unread_counts()`, `prune_old_messages(days)`, optional RLS hardening block | +| Realtime | replica identity per table, `supabase_realtime` publication membership | +| Storage | `chat-media` + `profiles` buckets and their storage policies | +| Self-check | one query at the end; every row must read `OK` | ## 4. Verification checklist -Run this in the SQL editor. Every line must read `OK` (it is also the self-check -at the end of `09`): +After running both files, this must return a row of `OK`s (it is the same check +`02` prints at the end, plus a few): ```sql SELECT 'tables' AS what, @@ -114,19 +132,24 @@ SELECT 'replica identity (messages must be FULL)', UNION ALL SELECT 'signup trigger', CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END - FROM pg_trigger WHERE tgname = 'on_auth_user_created'; + FROM pg_trigger WHERE tgname = 'on_auth_user_created' +UNION ALL +SELECT 'no duplicate last_message trigger', + CASE WHEN COUNT(*) <= 1 THEN 'OK' ELSE 'DUPLICATE ' || COUNT(*) END + FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'public.messages'::regclass + AND tgname LIKE 'trg_%last_message%'; ``` Then, in the dashboard: * **Table Editor** — the 14 tables above exist. * **Storage** — buckets `chat-media` (50 MB limit) and `profiles` (5 MB). -* **Database → Replication** — `supabase_realtime` is enabled for - `messages`, `conversations`, `users`, `calls`, `conversation_participants`. +* **Database → Replication** — `supabase_realtime` is enabled for `messages`, + `conversations`, `users`, `calls`, `conversation_participants`. (The SQL registers the tables; the dashboard toggle is what actually streams.) * **Authentication → Policies** — no duplicate policy names from an older file. If you ever ran one of the files in [`legacy/`](./legacy/), read - [`legacy/README.md`](./legacy/README.md) and drop the leftovers it lists. + [`legacy/README.md`](./legacy/README.md). ### Prove it is re-runnable @@ -136,35 +159,40 @@ SELECT (SELECT COUNT(*) FROM public.users) AS users, (SELECT COUNT(*) FROM pg_policies WHERE schemaname='public') AS policies; ``` -Run the setup again, then run this again: `users` and `messages` must be -**identical**, `policies` must not grow (policies are replaced, never stacked). -That is exactly what `npm test` checks in `src/__tests__/sqlMigrations.test.ts`. +Run both setup files again, then run this again: `users` and `messages` must be +**identical** and `policies` must not grow (policies are replaced, never +stacked). `src/__tests__/sqlMigrations.test.ts` enforces the same rules. ## 5. Troubleshooting | Symptom | Cause / fix | |---|---| | `relation "public.users" does not exist` | files ran out of order — always `01` first | -| Foreign-key error while running `02`/`03` | same: `01` must be applied first | -| `permission denied for table storage.objects` | run `06` as the project owner (the SQL editor is fine); a non-owner role cannot create storage policies | -| Realtime updates never arrive | dashboard → Database → Replication → `supabase_realtime`; also check that the table is listed in `pg_publication_tables` (the checklist above) | -| Uploads fail with 403 | buckets exist but storage policies were not applied — re-run `06` | -| Chat history looks short | that is `05`'s 40-message cap, by design. Skip its sections 1 and 6 to keep history (see §2) | +| Foreign-key error while running `02` | same: `01_schema.sql` must be applied first | +| `permission denied for table storage.objects` | run `02` as the project owner (the SQL editor is fine); a non-owner role cannot create storage policies | +| Realtime updates never arrive | dashboard → Database → Replication → `supabase_realtime`; also check the table is listed in `pg_publication_tables` (checklist above) | +| Uploads fail with 403 | buckets exist but storage policies were not applied — re-run `02` | +| Chat history looks short | the history cap in `02` (40 messages/chat), by design — see §2 | | A policy name appears twice in the dashboard | an old file from [`legacy/`](./legacy/) was run; drop the duplicates as described there | -| `function public.get_unread_counts() does not exist` | `09` has not been applied yet | -| Everything works but egress is still high | check `last_read_at` exists (the client falls back to the old per-message read path without it) and re-read [`../docs/EGRESS_AUDIT.md`](../docs/EGRESS_AUDIT.md) | +| `function public.get_unread_counts() does not exist` | `02` has not been run yet | +| Two `last_message` triggers on `messages` | an older install; re-running `02` drops the superseded one (checklist row above) | +| Everything works but egress is high | check `last_read_at` exists (the client falls back to the old per-message read path without it) and re-read [`../docs/EGRESS_AUDIT.md`](../docs/EGRESS_AUDIT.md) | -## 6. Rules for changing this folder +## 6. Rules for changing these files 1. **Never add a `DROP TABLE`.** Use `CREATE TABLE IF NOT EXISTS` plus `ALTER TABLE … ADD COLUMN IF NOT EXISTS` for anything new. -2. **Never add a `CREATE` that is not idempotent** — `CREATE OR REPLACE` for - functions, `DROP POLICY IF EXISTS` + `CREATE POLICY` for policies, +2. **Every `CREATE` must be idempotent** — `CREATE OR REPLACE` for functions, + `DROP POLICY IF EXISTS` + `CREATE POLICY` for policies, `CREATE INDEX IF NOT EXISTS` for indexes, `DROP TRIGGER IF EXISTS` + `CREATE TRIGGER` for triggers. -3. **New migrations get the next number** (`10_…`) and are appended to the file - list in `scripts/build-sql-bundle.mjs`; then run `npm run sql:bundle`. -4. **Test before committing.** The suite enforces rules 1–3; a real Postgres run - (fresh + re-run on populated data) is how the 2026-10-11 review was done. -5. Superseded files go to [`legacy/`](./legacy/) — never leave two files that +3. **Write the `.md` first.** What the change does and why goes here or in + [`../docs/EGRESS_AUDIT.md`](../docs/EGRESS_AUDIT.md); the SQL keeps a short + `COVERS:` header only. +4. **600–1000 lines per file.** Append to `02_…` until it is full, then start + `03_…`. Small standalone files and 2000-line files are both wrong. +5. **Test before committing:** the suite enforces rules 1–4. Also run the two + files against a real Postgres twice — fresh, then again on data — the way the + 2026-10-11 review did. +6. Superseded files go to [`legacy/`](./legacy/) — never leave two files that create the same table next to each other. diff --git a/sql/01_core_schema.sql b/sql/01_schema.sql similarity index 65% rename from sql/01_core_schema.sql rename to sql/01_schema.sql index 09dcc10..c76c29f 100644 --- a/sql/01_core_schema.sql +++ b/sql/01_schema.sql @@ -1,18 +1,27 @@ --- ========================================================================= --- STEP 1/9: GRIXCHAT CORE SCHEMA (users, chats, messages, calls, ...) --- ========================================================================= --- Supabase Dashboard -> SQL Editor -> New query -> paste -> RUN. --- Then continue with 02, 03, ... 09 in order (see 00_master_instructions.md). +-- ═══════════════════════════════════════════════════════════════════════════ +-- 01_schema.sql — tables, columns, constraints, RLS, indexes -- --- SAFE TO RE-RUN, ON A FRESH PROJECT AND ON A LIVE ONE: --- * nothing is dropped or truncated — no `DROP TABLE`, ever --- * tables are created only if missing, missing columns/indexes/constraints --- are added, policies are re-created so an updated definition replaces the --- old one --- * existing rows are never modified by this file --- ========================================================================= +-- COVERS (detail: 00_master_instructions.md) +-- §1 core tables: users, follows, conversations, conversation_participants, +-- messages, stories, calls, call_candidates, chat_settings, notifications +-- §2 later columns: conversations.chat_time_restrictions, stories.views +-- §3 column upgrades for older installs +-- §4 constraints (unique pairs, username length) +-- §5 row level security enabled +-- §6 every RLS policy (re-created, so edits apply) +-- §7 core indexes +-- §8 posts, post_likes, post_comments (+ RLS, indexes) +-- §9 support_tickets (+ RLS, index) +-- §10 schema cache reload +-- +-- Safe to re-run: nothing is dropped, missing objects are created, existing +-- rows are never modified. +-- ═══════════════════════════════════════════════════════════════════════════ + --- 2. TABLES (created only if missing) +-- ─────────────────────────────────────────────────────────────────────────── +-- §1 CORE TABLES (created only if missing) +-- ─────────────────────────────────────────────────────────────────────────── -- User Profiles (Integrated with auth.users) CREATE TABLE IF NOT EXISTS public.users ( @@ -154,7 +163,22 @@ CREATE TABLE IF NOT EXISTS public.notifications ( created_at TIMESTAMPTZ DEFAULT NOW() ); --- 3. COLUMN UPGRADES + +-- ─────────────────────────────────────────────────────────────────────────── +-- §2 LATER COLUMNS (kept here so older installs converge on the same shape) +-- ─────────────────────────────────────────────────────────────────────────── + +-- 07: per-chat scheduling (custom allowed days/times for direct chats) +ALTER TABLE public.conversations ADD COLUMN IF NOT EXISTS chat_time_restrictions JSONB DEFAULT NULL; + +-- 08: who viewed a story (the RPC that writes it lives in 02) +ALTER TABLE public.stories ADD COLUMN IF NOT EXISTS views JSONB DEFAULT '[]'::JSONB NOT NULL; + + +-- ─────────────────────────────────────────────────────────────────────────── +-- §3 CORE COLUMN UPGRADES (older installs get the same columns) +-- ─────────────────────────────────────────────────────────────────────────── + -- --------------------------------------------------------------------------- -- A project created from an older version of this file can be missing columns -- that were added later. `ADD COLUMN IF NOT EXISTS` makes every install converge @@ -307,7 +331,11 @@ BEGIN END IF; END $$; --- 4. CONSTRAINTS + +-- ─────────────────────────────────────────────────────────────────────────── +-- §4 CONSTRAINTS (added only when missing) +-- ─────────────────────────────────────────────────────────────────────────── + -- Added only when absent; a duplicate row in an old table produces a NOTICE -- (never an abort) so the rest of the script still runs. DO $$ @@ -336,7 +364,10 @@ EXCEPTION WHEN OTHERS THEN RAISE NOTICE 'Constraint skipped (%): existing rows violate it', SQLERRM; END $$; --- 5. ENABLE ROW LEVEL SECURITY (CORE PRIVACY) + +-- ─────────────────────────────────────────────────────────────────────────── +-- §5 ROW LEVEL SECURITY +-- ─────────────────────────────────────────────────────────────────────────── ALTER TABLE public.users ENABLE ROW LEVEL SECURITY; ALTER TABLE public.follows ENABLE ROW LEVEL SECURITY; @@ -349,7 +380,10 @@ ALTER TABLE public.call_candidates ENABLE ROW LEVEL SECURITY; ALTER TABLE public.chat_settings ENABLE ROW LEVEL SECURITY; ALTER TABLE public.notifications ENABLE ROW LEVEL SECURITY; --- 6. RLS POLICIES (re-created on every run, so edits apply) + +-- ─────────────────────────────────────────────────────────────────────────── +-- §6 RLS POLICIES (re-created on every run, so edits apply) +-- ─────────────────────────────────────────────────────────────────────────── -- profiles DROP POLICY IF EXISTS "Allow public read access on profiles" ON public.users; @@ -489,7 +523,11 @@ CREATE POLICY "Allow users to update own notifications" ON public.notifications DROP POLICY IF EXISTS "Allow users to delete own notifications" ON public.notifications; CREATE POLICY "Allow users to delete own notifications" ON public.notifications FOR DELETE USING (auth.uid() = user_id); --- 7. PERFORMANCE AND SEARCH INDEXES + +-- ─────────────────────────────────────────────────────────────────────────── +-- §7 CORE INDEXES +-- ─────────────────────────────────────────────────────────────────────────── + CREATE INDEX IF NOT EXISTS idx_messages_conversation ON public.messages(conversation_id); CREATE INDEX IF NOT EXISTS idx_messages_created_at ON public.messages(created_at DESC); CREATE INDEX IF NOT EXISTS idx_participants_user ON public.conversation_participants(user_id); @@ -502,5 +540,171 @@ CREATE INDEX IF NOT EXISTS idx_calls_participants ON public.calls(caller_id, rec CREATE INDEX IF NOT EXISTS idx_chat_settings_user ON public.chat_settings(user_id); CREATE INDEX IF NOT EXISTS idx_notifications_user ON public.notifications(user_id); --- Notification sound configuration + +-- ─────────────────────────────────────────────────────────────────────────── +-- §8 POSTS, LIKES AND COMMENTS (with their RLS and indexes) +-- ─────────────────────────────────────────────────────────────────────────── + +-- Posts table +CREATE TABLE IF NOT EXISTS public.posts ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + image_url TEXT NOT NULL, + caption TEXT, + created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL +); + +-- RLS for posts +ALTER TABLE public.posts ENABLE ROW LEVEL SECURITY; + +-- Policies +DROP POLICY IF EXISTS "Allow public read access for posts" ON public.posts; +CREATE POLICY "Allow public read access for posts" ON public.posts FOR SELECT +USING (true); + +DROP POLICY IF EXISTS "Allow authenticated insert for posts" ON public.posts; +CREATE POLICY "Allow authenticated insert for posts" ON public.posts FOR INSERT +WITH CHECK (auth.uid() = user_id); + +DROP POLICY IF EXISTS "Allow users to delete their own posts" ON public.posts; +CREATE POLICY "Allow users to delete their own posts" ON public.posts FOR DELETE +USING (auth.uid() = user_id); + + +-- Post likes table (one row per user/post) +CREATE TABLE IF NOT EXISTS public.post_likes ( + post_id UUID REFERENCES public.posts(id) ON DELETE CASCADE, + user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL, + PRIMARY KEY (post_id, user_id) +); + +-- RLS for post_likes +ALTER TABLE public.post_likes ENABLE ROW LEVEL SECURITY; + +-- Policies +DROP POLICY IF EXISTS "Allow public read access for post likes" ON public.post_likes; +CREATE POLICY "Allow public read access for post likes" ON public.post_likes FOR SELECT +USING (true); + +DROP POLICY IF EXISTS "Allow authenticated insert for post likes" ON public.post_likes; +CREATE POLICY "Allow authenticated insert for post likes" ON public.post_likes FOR INSERT +WITH CHECK (auth.uid() = user_id); + +DROP POLICY IF EXISTS "Allow users to remove their likes" ON public.post_likes; +CREATE POLICY "Allow users to remove their likes" ON public.post_likes FOR DELETE +USING (auth.uid() = user_id); + + +-- Post comments table +CREATE TABLE IF NOT EXISTS public.post_comments ( + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, + post_id UUID REFERENCES public.posts(id) ON DELETE CASCADE, + user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + text TEXT NOT NULL, + created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL +); + +-- RLS for post_comments +ALTER TABLE public.post_comments ENABLE ROW LEVEL SECURITY; + +-- Policies +DROP POLICY IF EXISTS "Allow public read access for post comments" ON public.post_comments; +CREATE POLICY "Allow public read access for post comments" ON public.post_comments FOR SELECT +USING (true); + +DROP POLICY IF EXISTS "Allow authenticated insert for post comments" ON public.post_comments; +CREATE POLICY "Allow authenticated insert for post comments" ON public.post_comments FOR INSERT +WITH CHECK (auth.uid() = user_id); + +DROP POLICY IF EXISTS "Allow users to delete their own comments" ON public.post_comments; +CREATE POLICY "Allow users to delete their own comments" ON public.post_comments FOR DELETE +USING (auth.uid() = user_id); + +-- Indexes +CREATE INDEX IF NOT EXISTS idx_posts_user_id ON public.posts(user_id); +CREATE INDEX IF NOT EXISTS idx_post_likes_post_id ON public.post_likes(post_id); +CREATE INDEX IF NOT EXISTS idx_post_comments_post_id ON public.post_comments(post_id); + +-- Column upgrades: a project created from an older version of this file may be +-- missing columns added later. No existing row is touched. +ALTER TABLE public.posts + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS image_url TEXT, + ADD COLUMN IF NOT EXISTS caption TEXT, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()); + +ALTER TABLE public.post_likes + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()); + +ALTER TABLE public.post_comments + ADD COLUMN IF NOT EXISTS post_id UUID REFERENCES public.posts(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, + ADD COLUMN IF NOT EXISTS text TEXT, + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()); + +-- Primary key of post_likes is (post_id, user_id); add it only if it is absent. +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint + WHERE conname = 'post_likes_pkey' + AND conrelid = 'public.post_likes'::regclass) THEN + ALTER TABLE public.post_likes ADD CONSTRAINT post_likes_pkey PRIMARY KEY (post_id, user_id); + END IF; +EXCEPTION WHEN OTHERS THEN + RAISE NOTICE 'post_likes primary key skipped: %', SQLERRM; +END $$; + + +-- ─────────────────────────────────────────────────────────────────────────── +-- §9 SUPPORT TICKETS (with their RLS and index) +-- ─────────────────────────────────────────────────────────────────────────── + +-- Create support tickets Table +CREATE TABLE IF NOT EXISTS public.support_tickets ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID REFERENCES public.users(id) ON DELETE SET NULL, + email TEXT NOT NULL, + category TEXT NOT NULL, + subject TEXT NOT NULL, + message TEXT NOT NULL, + status TEXT DEFAULT 'open' CHECK (status IN ('open', 'in_progress', 'resolved')), + created_at TIMESTAMPTZ DEFAULT NOW(), + updated_at TIMESTAMPTZ DEFAULT NOW() +); + +-- Column upgrades for older installs (no existing row is touched). +ALTER TABLE public.support_tickets + ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE SET NULL, + ADD COLUMN IF NOT EXISTS email TEXT, + ADD COLUMN IF NOT EXISTS category TEXT, + ADD COLUMN IF NOT EXISTS subject TEXT, + ADD COLUMN IF NOT EXISTS message TEXT, + ADD COLUMN IF NOT EXISTS status TEXT DEFAULT 'open', + ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(), + ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT NOW(); + +-- RLS +ALTER TABLE public.support_tickets ENABLE ROW LEVEL SECURITY; + +-- Anyone (anon or signed in) may open a ticket +DROP POLICY IF EXISTS "Allow anonymous and authenticated ticket insertion" ON public.support_tickets; +CREATE POLICY "Allow anonymous and authenticated ticket insertion" ON public.support_tickets + FOR INSERT + WITH CHECK (true); + +-- A user reads only their own tickets +DROP POLICY IF EXISTS "Allow users to view own tickets" ON public.support_tickets; +CREATE POLICY "Allow users to view own tickets" ON public.support_tickets + FOR SELECT + USING (auth.uid() = user_id); + +-- Index +CREATE INDEX IF NOT EXISTS idx_support_tickets_user_id ON public.support_tickets(user_id); + + +-- ─────────────────────────────────────────────────────────────────────────── +-- §10 POSTGREST SCHEMA CACHE +-- ─────────────────────────────────────────────────────────────────────────── + NOTIFY pgrst, 'reload schema'; diff --git a/sql/02_functions_realtime_storage.sql b/sql/02_functions_realtime_storage.sql new file mode 100644 index 0000000..06b1e7c --- /dev/null +++ b/sql/02_functions_realtime_storage.sql @@ -0,0 +1,843 @@ +-- ═══════════════════════════════════════════════════════════════════════════ +-- 02_functions_realtime_storage.sql — server-side logic +-- +-- COVERS (detail: 00_master_instructions.md) +-- §1 auth.users -> public.users trigger, get_direct_conversation_id() +-- §2 story RPCs: view_story(), cleanup_expired_stories() +-- §3 read marker: conversation_participants.last_read_at + RLS UPDATE policy +-- §4 chat-list preview trigger (last_message* / updated_at) +-- §5 history cap pruners + one-time sweep ⚠️ deletes old messages +-- §6 get_unread_counts() RPC +-- §7 prune_old_messages() retention + optional RLS hardening (commented) +-- §8 replica identity per table +-- §9 supabase_realtime publication membership +-- §10 storage buckets (chat-media, profiles) + storage policies +-- §10b PostgREST schema cache reload +-- §11 self-check query — every row must read OK +-- +-- Safe to re-run: functions are CREATE OR REPLACE, triggers/policies are dropped +-- first, and nothing here deletes data except the documented history cap (§5). +-- ═══════════════════════════════════════════════════════════════════════════ + + +-- ─────────────────────────────────────────────────────────────────────────── +-- §1 AUTH -> PROFILE TRIGGER AND DIRECT-CHAT RPC +-- ─────────────────────────────────────────────────────────────────────────── + +-- Re-created below: drop the old trigger first, otherwise CREATE TRIGGER fails +-- on a second run (the functions themselves are CREATE OR REPLACE). +DROP TRIGGER IF EXISTS on_auth_user_created ON auth.users; +DROP FUNCTION IF EXISTS public.handle_new_auth_user(); +DROP FUNCTION IF EXISTS public.get_direct_conversation_id(UUID, UUID); + +-- Room lookup for a direct chat (one indexed query instead of a join in the client) +CREATE OR REPLACE FUNCTION public.get_direct_conversation_id(u1 UUID, u2 UUID) +RETURNS UUID AS $$ +DECLARE + conv_id UUID; +BEGIN + SELECT cp1.conversation_id INTO conv_id + FROM public.conversation_participants cp1 + JOIN public.conversation_participants cp2 + ON cp1.conversation_id = cp2.conversation_id + JOIN public.conversations c + ON cp1.conversation_id = c.id + WHERE cp1.user_id = u1 + AND cp2.user_id = u2 + AND c.type = 'direct' + LIMIT 1; + + RETURN conv_id; +END; +$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public; + + +-- auth.users -> public.users: the profile is created by the database, for +-- email signup and every OAuth provider alike +CREATE OR REPLACE FUNCTION public.handle_new_auth_user() +RETURNS TRIGGER AS $$ +DECLARE + username_val TEXT; + full_name_val TEXT; +BEGIN + -- Extract values safely from raw_user_meta_data or default to email split-part + username_val := COALESCE( + new.raw_user_meta_data->>'username', + split_part(new.email, '@', 1) + ); + full_name_val := COALESCE( + new.raw_user_meta_data->>'full_name', + split_part(new.email, '@', 1) + ); + + -- Clean the username values to be under 15 characters + username_val := SUBSTRING(username_val, 1, 15); + + -- Ensure uniqueness of username, append unique IDs if a duplicate is found + IF EXISTS (SELECT 1 FROM public.users WHERE username = username_val) THEN + username_val := SUBSTRING(username_val, 1, 9) || '_' || substring(new.id::text, 1, 5); + END IF; + + -- Insert profile safely + INSERT INTO public.users ( + id, + email, + phone, + full_name, + username, + photo_url, + bio + ) + VALUES ( + new.id, + new.email, + COALESCE(new.raw_user_meta_data->>'phone', ''), + full_name_val, + LOWER(username_val), + COALESCE(new.raw_user_meta_data->>'avatar_url', 'https://cdn-icons-png.flaticon.com/512/149/149071.png'), + 'Available' + ) + ON CONFLICT (id) DO UPDATE SET + email = EXCLUDED.email, + phone = COALESCE(public.users.phone, EXCLUDED.phone), + full_name = COALESCE(public.users.full_name, EXCLUDED.full_name), + username = COALESCE(public.users.username, EXCLUDED.username); + + RETURN NEW; +END; +$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public; + +-- Bind trigger on auth.users (Runs completely on auth signup) +CREATE TRIGGER on_auth_user_created + AFTER INSERT ON auth.users + FOR EACH ROW EXECUTE FUNCTION public.handle_new_auth_user(); + + +-- ─────────────────────────────────────────────────────────────────────────── +-- §2 STORY RPCS +-- ─────────────────────────────────────────────────────────────────────────── + +-- Record a story view without granting UPDATE on stories to clients. +-- The viewer JSON is built inline to keep the function trivially parseable. +CREATE OR REPLACE FUNCTION public.view_story( + story_id_param UUID, + viewer_id_param UUID, + viewer_username_param TEXT, + viewer_fullname_param TEXT, + viewer_photo_url_param TEXT +) +RETURNS VOID AS $$ +BEGIN + UPDATE public.stories + SET views = COALESCE(views, '[]'::JSONB) || jsonb_build_array( + jsonb_build_object( + 'id', viewer_id_param, + 'username', viewer_username_param, + 'full_name', viewer_fullname_param, + 'photo_url', viewer_photo_url_param, + 'viewed_at', NOW() + ) + ) + WHERE id = story_id_param + AND NOT (COALESCE(views, '[]'::JSONB) @> jsonb_build_array(jsonb_build_object('id', viewer_id_param::text))); +END; +$$ LANGUAGE plpgsql SECURITY DEFINER; + +-- Delete stories older than 24 h (called by the client / a cron job) +CREATE OR REPLACE FUNCTION public.cleanup_expired_stories() +RETURNS VOID AS $$ +BEGIN + DELETE FROM public.stories WHERE created_at < NOW() - INTERVAL '24 hours'; +END; +$$ LANGUAGE plpgsql SECURITY DEFINER; + + +-- ─────────────────────────────────────────────────────────────────────────── +-- §3 READ MARKER (unread by comparison, not by scanning messages) +-- ─────────────────────────────────────────────────────────────────────────── + +-- The chat list decides unread by comparing timestamps, so "I read this chat" +-- is one row update instead of one UPDATE per unread message (each of which was +-- broadcast to every subscribed client). +-- Unread is a comparison: conversations.last_message_at > my last_read_at. +-- One UPDATE per "I opened/read this chat" instead of one row per message. + +-- Existing rows are stamped with the moment this runs, so history starts +-- "read" and nobody gets a fake 400-message unread badge. +ALTER TABLE public.conversation_participants + ADD COLUMN IF NOT EXISTS last_read_at TIMESTAMPTZ DEFAULT NOW(); + +-- The client updates ITS OWN row to say "I have read up to here". Without this +-- policy the UPDATE matches no policy, affects 0 rows, and returns no error — +-- the read marker would silently never move. (RLS is on for this table, and +-- 01_schema.sql only defined SELECT/INSERT/DELETE.) +DROP POLICY IF EXISTS "Participants can update their own membership" ON public.conversation_participants; +CREATE POLICY "Participants can update their own membership" + ON public.conversation_participants + FOR UPDATE + USING (user_id = auth.uid()) + WITH CHECK (user_id = auth.uid()); + +CREATE INDEX IF NOT EXISTS idx_participants_user_last_read + ON public.conversation_participants(user_id, last_read_at DESC); + +-- Realtime: the client subscribes with `user_id=eq.` and must also receive +-- DELETEs (a participant removed from a group). DEFAULT identity only carries +-- the primary key in the `old` record, so the server cannot evaluate the filter +-- for deletes. These rows are tiny and rarely written, so FULL is cheap here. +ALTER TABLE public.conversation_participants REPLICA IDENTITY FULL; + + +-- ─────────────────────────────────────────────────────────────────────────── +-- §4 CHAT-LIST PREVIEW TRIGGER (insert, edit, soft delete, delete) +-- ─────────────────────────────────────────────────────────────────────────── + +-- The list draws a one-line preview from conversations.last_message*; the +-- database keeps those columns current so the client never re-reads messages. +-- The chat list shows `last_message` / `last_message_at` / (for ticks) the +-- sender. Writers already set the first two; the trigger also covers edits, +-- deletes and direct SQL inserts, so the client never needs to re-read the +-- newest messages for every conversation. + +ALTER TABLE public.conversations + ADD COLUMN IF NOT EXISTS last_message_sender_id UUID; + +CREATE OR REPLACE FUNCTION public.sync_conversation_last_message() +RETURNS TRIGGER +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = public +AS $$ +DECLARE + target_conversation UUID; + newest RECORD; +BEGIN + target_conversation := COALESCE(NEW.conversation_id, OLD.conversation_id); + IF target_conversation IS NULL THEN + RETURN NULL; + END IF; + + -- Fast path: a new (or edited) message that is not older than what the + -- conversation already shows IS the newest one, so write it across without + -- looking at the table. Appends are the hot path: no extra index scan. + IF TG_OP <> 'DELETE' AND NEW.is_deleted = false THEN + UPDATE public.conversations + SET last_message = COALESCE(NEW.text, + 'Sent a ' || COALESCE(NEW.media_type, 'file')), + last_message_at = NEW.created_at, + last_message_sender_id = NEW.sender_id, + updated_at = NEW.created_at + WHERE id = target_conversation + AND (last_message_at IS NULL OR NEW.created_at >= last_message_at); + IF FOUND THEN + RETURN NULL; + END IF; + END IF; + + -- Fast skip for DELETEs: if the conversation already shows something newer, + -- removing an older row cannot change the preview. This is the common case + -- for the 40-message history cap in 05, which deletes a batch per insert. + IF TG_OP = 'DELETE' AND EXISTS ( + SELECT 1 FROM public.conversations + WHERE id = target_conversation + AND last_message_at IS NOT NULL + AND last_message_at > OLD.created_at + ) THEN + RETURN NULL; + END IF; + + -- Slow path: a delete of the newest row, a soft delete, or an edit of an + -- older message. The preview has to be re-derived from what is left. + SELECT m.text, m.media_type, m.created_at, m.sender_id, m.is_deleted + INTO newest + FROM public.messages m + WHERE m.conversation_id = target_conversation + AND m.is_deleted = false + ORDER BY m.created_at DESC, m.id DESC + LIMIT 1; + + IF NOT FOUND THEN + UPDATE public.conversations + SET last_message = NULL, + last_message_at = NULL, + last_message_sender_id = NULL + WHERE id = target_conversation; + ELSE + UPDATE public.conversations + SET last_message = COALESCE(newest.text, + 'Sent a ' || COALESCE(newest.media_type, 'file')), + last_message_at = newest.created_at, + last_message_sender_id = newest.sender_id + WHERE id = target_conversation; + END IF; + + RETURN NULL; +END; +$$; + +-- Superseded duplicate: older installs also have trg_update_conversation_on_message +-- (insert-only, no sender, no delete handling). Two triggers doing the same write +-- doubled the work on every message — it is dropped here and replaced by the +-- trigger below. +DROP TRIGGER IF EXISTS trg_update_conversation_on_message ON public.messages; +DROP FUNCTION IF EXISTS public.update_conversation_timestamp_and_last_message(); + +DROP TRIGGER IF EXISTS trg_sync_conversation_last_message ON public.messages; +CREATE TRIGGER trg_sync_conversation_last_message + AFTER INSERT OR UPDATE OF text, media_type, is_deleted OR DELETE + ON public.messages + FOR EACH ROW + EXECUTE FUNCTION public.sync_conversation_last_message(); + +-- The fast path above needs no lookup at all; only edits/deletes of older +-- messages touch the index below, and they resolve it in one index scan. + +CREATE INDEX IF NOT EXISTS idx_messages_conv_created + ON public.messages(conversation_id, created_at DESC); + +CREATE INDEX IF NOT EXISTS idx_conversations_last_message_at + ON public.conversations(last_message_at DESC NULLS LAST); + +-- Legacy path only (used until the client detects `last_read_at`). +CREATE INDEX IF NOT EXISTS idx_messages_unread + ON public.messages(conversation_id) + WHERE is_read = false; + + +-- ─────────────────────────────────────────────────────────────────────────── +-- §5 HISTORY CAP (⚠️ keeps only the newest 40 messages per chat) +-- ─────────────────────────────────────────────────────────────────────────── + +-- ⚠️ This section deletes message history on purpose: every chat is capped at 60 +-- rows and pruned back to the newest 40 on insert, and §5c sweeps existing data +-- once. It keeps a free-tier project small. To keep history instead, do not run +-- this section — use prune_old_messages() from §7, which is time-based. +-- +-- §5a messages + +-- Cap per room: at 60 rows, keep the newest 40. +CREATE OR REPLACE FUNCTION prune_past_messages() +RETURNS TRIGGER AS $$ +DECLARE + msg_count INT; +BEGIN + SELECT COUNT(*) INTO msg_count + FROM public.messages + WHERE conversation_id = NEW.conversation_id; + + IF msg_count >= 60 THEN + DELETE FROM public.messages + WHERE conversation_id = NEW.conversation_id + AND id NOT IN ( + SELECT subquery.id FROM ( + SELECT id FROM public.messages + WHERE conversation_id = NEW.conversation_id + ORDER BY created_at DESC, id DESC + LIMIT 40 + ) subquery + ); + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql SECURITY DEFINER; + +DROP TRIGGER IF EXISTS trg_prune_past_messages ON public.messages; +CREATE TRIGGER trg_prune_past_messages +AFTER INSERT ON public.messages +FOR EACH ROW +EXECUTE FUNCTION prune_past_messages(); + + +-- §5b calls + +-- Same cap for call history: at 60 rows per user, keep the newest 40. +CREATE OR REPLACE FUNCTION prune_past_calls() +RETURNS TRIGGER AS $$ +DECLARE + caller_call_count INT; + receiver_call_count INT; +BEGIN + SELECT COUNT(*) INTO caller_call_count + FROM public.calls + WHERE caller_id = NEW.caller_id OR receiver_id = NEW.caller_id; + + IF caller_call_count >= 60 THEN + DELETE FROM public.calls + WHERE (caller_id = NEW.caller_id OR receiver_id = NEW.caller_id) + AND id NOT IN ( + SELECT subquery.id FROM ( + SELECT id FROM public.calls + WHERE caller_id = NEW.caller_id OR receiver_id = NEW.caller_id + ORDER BY created_at DESC, id DESC + LIMIT 40 + ) subquery + ); + END IF; + + IF NEW.receiver_id IS NOT NULL AND NEW.receiver_id <> NEW.caller_id THEN + SELECT COUNT(*) INTO receiver_call_count + FROM public.calls + WHERE caller_id = NEW.receiver_id OR receiver_id = NEW.receiver_id; + + IF receiver_call_count >= 60 THEN + DELETE FROM public.calls + WHERE (caller_id = NEW.receiver_id OR receiver_id = NEW.receiver_id) + AND id NOT IN ( + SELECT subquery.id FROM ( + SELECT id FROM public.calls + WHERE caller_id = NEW.receiver_id OR receiver_id = NEW.receiver_id + ORDER BY created_at DESC, id DESC + LIMIT 40 + ) subquery + ); + END IF; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql SECURITY DEFINER; + +DROP TRIGGER IF EXISTS trg_prune_past_calls ON public.calls; +CREATE TRIGGER trg_prune_past_calls +AFTER INSERT ON public.calls +FOR EACH ROW +EXECUTE FUNCTION prune_past_calls(); + + +-- §5c one-time sweep of existing rows + +-- Apply the cap to data that already exists (no-op once a chat is under 60 rows). +-- Same policy as section 1: it keeps the newest 40 messages per chat and the +-- newest 40 calls per user. Skip this section if you skipped section 1. +DO $$ +DECLARE + u_rec RECORD; + conv_rec RECORD; +BEGIN + -- Prune existing calls back to newest 40 for every user + FOR u_rec IN (SELECT DISTINCT id FROM public.users) LOOP + DELETE FROM public.calls + WHERE (caller_id = u_rec.id OR receiver_id = u_rec.id) + AND id NOT IN ( + SELECT subquery.id FROM ( + SELECT id FROM public.calls + WHERE caller_id = u_rec.id OR receiver_id = u_rec.id + ORDER BY created_at DESC, id DESC + LIMIT 40 + ) subquery + ); + END LOOP; + + -- Prune existing messages back to newest 40 for every conversation room + FOR conv_rec IN (SELECT DISTINCT id FROM public.conversations) LOOP + DELETE FROM public.messages + WHERE conversation_id = conv_rec.id + AND id NOT IN ( + SELECT subquery.id FROM ( + SELECT id FROM public.messages + WHERE conversation_id = conv_rec.id + ORDER BY created_at DESC, id DESC + LIMIT 40 + ) subquery + ); + END LOOP; +END; +$$; + + +-- ─────────────────────────────────────────────────────────────────────────── +-- §6 UNREAD COUNTS RPC (exact badges without scanning messages) +-- ─────────────────────────────────────────────────────────────────────────── + +-- Optional: exact badges from the server in one row per conversation. +-- Call: supabase.rpc('get_unread_counts') +-- Returns one row per conversation with a badge, instead of one row per unread +-- message. `last_read_at` already removes the need; this is exact and cheap. + +CREATE OR REPLACE FUNCTION public.get_unread_counts() +RETURNS TABLE (conversation_id UUID, unread_count BIGINT) +LANGUAGE sql +STABLE +SECURITY DEFINER +SET search_path = public +AS $$ + SELECT m.conversation_id, COUNT(*) AS unread_count + FROM public.messages m + JOIN public.conversation_participants cp + ON cp.conversation_id = m.conversation_id + AND cp.user_id = auth.uid() + WHERE m.sender_id <> auth.uid() + AND m.is_deleted = false + AND (cp.last_read_at IS NULL OR m.created_at > cp.last_read_at) + GROUP BY m.conversation_id; +$$; + +GRANT EXECUTE ON FUNCTION public.get_unread_counts() TO authenticated; + + +-- ─────────────────────────────────────────────────────────────────────────── +-- §7 RETENTION PRUNER + OPTIONAL RLS HARDENING +-- ─────────────────────────────────────────────────────────────────────────── + +-- Optional, time-based retention: nothing calls this automatically. +-- Egress is paid on read, not on storage, but a smaller table keeps the +-- unread/latest queries from degrading. Deletes soft-deleted rows and anything +-- older than `keep_days` for conversations that are inactive. + +CREATE OR REPLACE FUNCTION public.prune_old_messages(keep_days INTEGER DEFAULT 90) +RETURNS INTEGER +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = public +AS $$ +DECLARE + removed INTEGER := 0; + affected UUID[]; +BEGIN + SELECT array_agg(DISTINCT conversation_id) INTO affected + FROM ( + SELECT m.conversation_id + FROM public.messages m + JOIN public.conversations c ON c.id = m.conversation_id + WHERE m.created_at < NOW() - make_interval(days => keep_days) + AND c.updated_at < NOW() - make_interval(days => keep_days) + ORDER BY m.created_at + LIMIT 5000 + ) t; + + IF affected IS NULL THEN + RETURN 0; + END IF; + + -- The per-row last_message trigger would fire once per deleted row (5000 + -- index scans); the last_message of these inactive conversations is + -- recomputed in one pass below instead. DDL is transactional, so this rolls + -- back with the function if anything fails. + BEGIN + ALTER TABLE public.messages DISABLE TRIGGER trg_sync_conversation_last_message; + EXCEPTION WHEN OTHERS THEN + NULL; -- not the table owner; the trigger just stays on + END; + + DELETE FROM public.messages m + USING ( + SELECT m2.id + FROM public.messages m2 + JOIN public.conversations c ON c.id = m2.conversation_id + WHERE m2.created_at < NOW() - make_interval(days => keep_days) + AND c.updated_at < NOW() - make_interval(days => keep_days) + ORDER BY m2.created_at + LIMIT 5000 + ) stale + WHERE m.id = stale.id; + + GET DIAGNOSTICS removed = ROW_COUNT; + + BEGIN + ALTER TABLE public.messages ENABLE TRIGGER trg_sync_conversation_last_message; + EXCEPTION WHEN OTHERS THEN + NULL; + END; + + UPDATE public.conversations c + SET last_message = x.text, + last_message_at = x.created_at, + last_message_sender_id = x.sender_id + FROM ( + SELECT DISTINCT ON (m.conversation_id) + m.conversation_id, m.text, m.created_at, m.sender_id + FROM public.messages m + WHERE m.conversation_id = ANY(affected) + AND m.is_deleted = false + ORDER BY m.conversation_id, m.created_at DESC, m.id DESC + ) x + WHERE c.id = x.conversation_id; + + RETURN removed; +END; +$$; + +-- Example: keep the last 90 days. +-- SELECT public.prune_old_messages(90); +-- Scheduled (needs the pg_cron extension enabled in Dashboard → Database → +-- Extensions): +-- SELECT cron.schedule('prune-messages', '0 4 * * *', $$SELECT public.prune_old_messages(90)$$); + + +-- Optional hardening (commented out — read before enabling). +-- `conversation_participants` is readable by EVERY authenticated user +-- (`FOR SELECT USING (true)`), which leaks who-talks-to-whom, and `users` is +-- readable the same way, which leaks `email`, `phone`, `lock` (passcode hash!) +-- and `fcm_tokens` of every account. Neither is an egress bug, but both are +-- foundation mistakes worth closing. The membership check below needs a +-- SECURITY DEFINER helper: a policy on the table cannot query the same table +-- (Postgres raises "infinite recursion detected in policy"). +-- +-- CREATE OR REPLACE FUNCTION public.is_conversation_member(conv UUID, uid UUID) +-- RETURNS BOOLEAN LANGUAGE sql STABLE SECURITY DEFINER SET search_path = public +-- AS $$ SELECT EXISTS (SELECT 1 FROM public.conversation_participants +-- WHERE conversation_id = conv AND user_id = uid); $$; +-- +-- DROP POLICY IF EXISTS "Allow auth users to inspect participants" +-- ON public.conversation_participants; +-- CREATE POLICY "Members can inspect their conversations' participants" +-- ON public.conversation_participants FOR SELECT +-- USING (public.is_conversation_member(conversation_id, auth.uid())); +-- +-- DROP POLICY IF EXISTS "Allow public read access on profiles" ON public.users; +-- CREATE POLICY "Profiles are readable, secrets are not" ON public.users +-- FOR SELECT USING (true); -- plus a view/column grants, see +-- -- docs/EGRESS_AUDIT.md §6 + + +-- ─────────────────────────────────────────────────────────────────────────── +-- §8 REPLICA IDENTITY +-- ─────────────────────────────────────────────────────────────────────────── + +-- FULL is only needed where the client filters DELETEs by a non-key column +-- (`conversation_id=eq.…` on messages, participant removal on +-- conversation_participants). Everywhere else DEFAULT keeps UPDATE payloads to +-- "new row + primary key" — which also stops `users.lock` (the app-lock passcode +-- hash) and `fcm_tokens` from travelling over Realtime. +-- `REPLICA IDENTITY FULL` makes every UPDATE emit the complete OLD row and the +-- complete NEW row to every subscribed client. On `users` that payload includes +-- `settings`, `lock` (passcode hash!) and `fcm_tokens`. DEFAULT sends the new +-- row plus the primary key only — smaller, and no private columns on the wire. +-- +-- `messages` is deliberately NOT in this list. `useChatMessages` listens for +-- DELETE events with a `conversation_id=eq.…` filter, and the filter column is +-- only present in the `old` record when the identity is FULL — with DEFAULT the +-- event cannot be matched and "delete for everyone" would stop propagating. +-- The read-marker change (section 1) is what removes messages UPDATE traffic; +-- deletes are rare, so FULL stays there. +-- +-- `conversations`, `users` and `calls` are only ever read via `payload.new` on +-- the client (and a conversation DELETE also removes its participant rows, which +-- ARE FULL), so DEFAULT is safe for them. Calls are status-UPDATEd, never +-- deleted (`CallProvider` zombie sweep). The pair of `FULL` entries re-asserts +-- the two tables whose filtered DELETEs the client depends on, so this file +-- leaves the database correct no matter which earlier scripts were applied. + +DO $$ +DECLARE + target RECORD; +BEGIN + FOR target IN + SELECT * FROM (VALUES + ('users', 'DEFAULT'), + ('conversations', 'DEFAULT'), + ('calls', 'DEFAULT'), + ('call_candidates', 'DEFAULT'), + ('messages', 'FULL'), + ('conversation_participants','FULL') + ) AS t(tbl, identity) + LOOP + IF EXISTS (SELECT 1 FROM pg_class c + JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname = target.tbl) THEN + EXECUTE format('ALTER TABLE public.%I REPLICA IDENTITY %s', + target.tbl, target.identity); + END IF; + END LOOP; +END; +$$; + + +-- Advanced (optional, experimental): if messages UPDATE payloads ever matter +-- again, `ALTER TABLE public.messages REPLICA IDENTITY USING INDEX +-- messages_id_conversation_id_key;` (with a UNIQUE index on (id, +-- conversation_id)) makes the `old` record carry just those two columns. Verify +-- in the Realtime inspector that DELETE events still arrive before relying on +-- it. + + +-- ─────────────────────────────────────────────────────────────────────────── +-- §9 REALTIME PUBLICATION MEMBERSHIP +-- ─────────────────────────────────────────────────────────────────────────── + +-- Only the tables the client actually subscribes to. Membership is idempotent: +-- a table is added only when it exists and is not already published. +-- --------------------------------------------------------------------------- +-- Only the tables the client actually subscribes to. Membership is idempotent: +-- a table is added only when it exists and is not already published, so a run +-- over an existing project changes nothing and a fork that dropped a table +-- (e.g. call_candidates) does not abort the script. +-- --------------------------------------------------------------------------- +DO $$ +DECLARE + tbl TEXT; +BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_publication WHERE pubname = 'supabase_realtime') THEN + CREATE PUBLICATION supabase_realtime; + END IF; + + FOREACH tbl IN ARRAY ARRAY[ + 'messages', 'conversations', 'users', 'calls', + 'call_candidates', 'conversation_participants' + ] LOOP + IF to_regclass('public.' || tbl) IS NOT NULL + AND NOT EXISTS (SELECT 1 FROM pg_publication_tables + WHERE pubname = 'supabase_realtime' + AND schemaname = 'public' + AND tablename = tbl) THEN + EXECUTE format('ALTER PUBLICATION supabase_realtime ADD TABLE public.%I', tbl); + END IF; + END LOOP; +END; +$$; + +-- Also enable Realtime in the dashboard for these tables: +-- Database -> Replication -> supabase_realtime +-- The SQL above registers the tables; the dashboard toggle is what actually +-- streams them. + + +-- ─────────────────────────────────────────────────────────────────────────── +-- §10 STORAGE BUCKETS AND POLICIES +-- ─────────────────────────────────────────────────────────────────────────── + +-- Buckets (inserted only if missing; sizes are limits, not defaults). +INSERT INTO storage.buckets (id, name, public, file_size_limit, allowed_mime_types) +VALUES + ('chat-media', 'chat-media', true, 52428800, NULL), -- 50 MB limit + ('profiles', 'profiles', true, 5242880, ARRAY['image/jpeg', 'image/png', 'image/gif', 'image/webp']) -- 5 MB limit +ON CONFLICT (id) DO NOTHING; + + +-- Policies are dropped and re-created, so an edited definition always wins. +-- Clean up any conflicting pre-existing policies for these buckets +DROP POLICY IF EXISTS "Public Access to chat-media" ON storage.objects; +DROP POLICY IF EXISTS "Authenticated Users can upload to chat-media" ON storage.objects; +DROP POLICY IF EXISTS "Owners can update their own chat-media objects" ON storage.objects; +DROP POLICY IF EXISTS "Owners can delete their own chat-media objects" ON storage.objects; + +DROP POLICY IF EXISTS "Public Access to profiles" ON storage.objects; +DROP POLICY IF EXISTS "Authenticated Users can upload to profiles" ON storage.objects; +DROP POLICY IF EXISTS "Owners can update their own profiles" ON storage.objects; +DROP POLICY IF EXISTS "Owners can delete their own profiles" ON storage.objects; + + +-- chat-media + +-- Read Policy: Anyone can read media (Publicly accessible) +CREATE POLICY "Public Access to chat-media" +ON storage.objects FOR SELECT +TO public +USING (bucket_id = 'chat-media'); + +-- Write Policy: Authenticated users can insert files +CREATE POLICY "Authenticated Users can upload to chat-media" +ON storage.objects FOR INSERT +TO authenticated +WITH CHECK (bucket_id = 'chat-media' AND (auth.uid()::text = (storage.foldername(name))[1] OR true)); + +-- Update Policy: Authenticated owners can update files +CREATE POLICY "Owners can update their own chat-media objects" +ON storage.objects FOR UPDATE +TO authenticated +USING (bucket_id = 'chat-media') +WITH CHECK (bucket_id = 'chat-media'); + +-- Delete Policy: Authenticated users can delete files they own +CREATE POLICY "Owners can delete their own chat-media objects" +ON storage.objects FOR DELETE +TO authenticated +USING (bucket_id = 'chat-media'); + + +-- profiles + +-- Read Policy: Anyone can read profiles photos (Publicly accessible) +CREATE POLICY "Public Access to profiles" +ON storage.objects FOR SELECT +TO public +USING (bucket_id = 'profiles'); + +-- Write Policy: Authenticated users can upload profile icons +CREATE POLICY "Authenticated Users can upload to profiles" +ON storage.objects FOR INSERT +TO authenticated +WITH CHECK (bucket_id = 'profiles'); + +-- Update Policy: Authenticated users can replace profile icons +CREATE POLICY "Owners can update their own profiles" +ON storage.objects FOR UPDATE +TO authenticated +USING (bucket_id = 'profiles') +WITH CHECK (bucket_id = 'profiles'); + +-- Delete Policy: Authenticated users can delete profile icons +CREATE POLICY "Owners can delete their own profiles" +ON storage.objects FOR DELETE +TO authenticated +USING (bucket_id = 'profiles'); + + +-- ─────────────────────────────────────────────────────────────────────────── +-- §10b POSTGREST SCHEMA CACHE +-- ─────────────────────────────────────────────────────────────────────────── + +NOTIFY pgrst, 'reload schema'; + + +-- ─────────────────────────────────────────────────────────────────────────── +-- §11 SELF-CHECK +-- ─────────────────────────────────────────────────────────────────────────── + +-- ── final self-check ────────────────────────────────────────────────────── +-- Run this afterwards; every row should read like the expected value. +SELECT 'conversation_participants.last_read_at' AS what, + CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END AS state + FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'conversation_participants' + AND column_name = 'last_read_at' +UNION ALL +SELECT 'conversations.last_message_sender_id', + CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END + FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'conversations' + AND column_name = 'last_message_sender_id' +UNION ALL +SELECT 'replica identity: users', + COALESCE((SELECT CASE WHEN c.relreplident = 'f' THEN 'STILL FULL' ELSE 'OK (default)' END + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname = 'users'), 'MISSING') +UNION ALL +SELECT 'replica identity: conversations (expect default)', + COALESCE((SELECT CASE WHEN c.relreplident = 'f' THEN 'STILL FULL' ELSE 'OK (default)' END + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname = 'conversations'), 'MISSING') +UNION ALL +SELECT 'replica identity: messages (expect FULL)', + COALESCE((SELECT CASE WHEN c.relreplident = 'f' THEN 'OK (full)' ELSE 'CHANGED - deletes will stop reaching clients' END + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname = 'messages'), 'MISSING') +UNION ALL +SELECT 'sync trigger on messages', + CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END + FROM pg_trigger + WHERE tgname = 'trg_sync_conversation_last_message' +UNION ALL +SELECT 'posts / post_likes / post_comments / support_tickets', + CASE WHEN COUNT(*) = 4 THEN 'OK' ELSE 'MISSING' END + FROM information_schema.tables + WHERE table_schema = 'public' + AND table_name IN ('posts','post_likes','post_comments','support_tickets') +UNION ALL +SELECT 'no duplicate last_message trigger', + CASE WHEN COUNT(*) <= 1 THEN 'OK' ELSE 'DUPLICATE ' || COUNT(*) END + FROM pg_trigger + WHERE NOT tgisinternal AND tgrelid = 'public.messages'::regclass + AND tgname LIKE 'trg_%last_message%' +UNION ALL +SELECT 'stories.views + chat_time_restrictions columns', + CASE WHEN COUNT(*) = 2 THEN 'OK' ELSE 'MISSING' END + FROM information_schema.columns + WHERE table_schema = 'public' + AND (table_name, column_name) IN (('stories','views'), ('conversations','chat_time_restrictions')) +UNION ALL +SELECT 'UPDATE policy on conversation_participants', + CASE WHEN COUNT(*) FILTER (WHERE cmd = 'UPDATE') > 0 THEN 'OK' ELSE 'MISSING' END + FROM pg_policies + WHERE schemaname = 'public' AND tablename = 'conversation_participants'; diff --git a/sql/02_posts_and_interactions_schema.sql b/sql/02_posts_and_interactions_schema.sql deleted file mode 100644 index 5e3aaf0..0000000 --- a/sql/02_posts_and_interactions_schema.sql +++ /dev/null @@ -1,120 +0,0 @@ --- ========================================================================= --- STEP 2/9: POSTS, LIKES AND COMMENTS --- ========================================================================= --- Run in the Supabase SQL Editor after 01_core_schema.sql. --- Safe to re-run: nothing is dropped, missing tables/columns/policies are --- created, existing rows are untouched. --- ========================================================================= - --- 1. Create Posts Table -CREATE TABLE IF NOT EXISTS public.posts ( - id UUID DEFAULT gen_random_uuid() PRIMARY KEY, - user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - image_url TEXT NOT NULL, - caption TEXT, - created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL -); - --- Enable RLS for public.posts -ALTER TABLE public.posts ENABLE ROW LEVEL SECURITY; - --- Post Policies -DROP POLICY IF EXISTS "Allow public read access for posts" ON public.posts; -CREATE POLICY "Allow public read access for posts" ON public.posts FOR SELECT -USING (true); - -DROP POLICY IF EXISTS "Allow authenticated insert for posts" ON public.posts; -CREATE POLICY "Allow authenticated insert for posts" ON public.posts FOR INSERT -WITH CHECK (auth.uid() = user_id); - -DROP POLICY IF EXISTS "Allow users to delete their own posts" ON public.posts; -CREATE POLICY "Allow users to delete their own posts" ON public.posts FOR DELETE -USING (auth.uid() = user_id); - - --- 2. Create Post Likes Table (Tracking active likes) -CREATE TABLE IF NOT EXISTS public.post_likes ( - post_id UUID REFERENCES public.posts(id) ON DELETE CASCADE, - user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL, - PRIMARY KEY (post_id, user_id) -); - --- Enable RLS for public.post_likes -ALTER TABLE public.post_likes ENABLE ROW LEVEL SECURITY; - --- Post Likes Policies -DROP POLICY IF EXISTS "Allow public read access for post likes" ON public.post_likes; -CREATE POLICY "Allow public read access for post likes" ON public.post_likes FOR SELECT -USING (true); - -DROP POLICY IF EXISTS "Allow authenticated insert for post likes" ON public.post_likes; -CREATE POLICY "Allow authenticated insert for post likes" ON public.post_likes FOR INSERT -WITH CHECK (auth.uid() = user_id); - -DROP POLICY IF EXISTS "Allow users to remove their likes" ON public.post_likes; -CREATE POLICY "Allow users to remove their likes" ON public.post_likes FOR DELETE -USING (auth.uid() = user_id); - - --- 3. Create Post Comments Table -CREATE TABLE IF NOT EXISTS public.post_comments ( - id UUID DEFAULT gen_random_uuid() PRIMARY KEY, - post_id UUID REFERENCES public.posts(id) ON DELETE CASCADE, - user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - text TEXT NOT NULL, - created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL -); - --- Enable RLS for public.post_comments -ALTER TABLE public.post_comments ENABLE ROW LEVEL SECURITY; - --- Post Comments Policies -DROP POLICY IF EXISTS "Allow public read access for post comments" ON public.post_comments; -CREATE POLICY "Allow public read access for post comments" ON public.post_comments FOR SELECT -USING (true); - -DROP POLICY IF EXISTS "Allow authenticated insert for post comments" ON public.post_comments; -CREATE POLICY "Allow authenticated insert for post comments" ON public.post_comments FOR INSERT -WITH CHECK (auth.uid() = user_id); - -DROP POLICY IF EXISTS "Allow users to delete their own comments" ON public.post_comments; -CREATE POLICY "Allow users to delete their own comments" ON public.post_comments FOR DELETE -USING (auth.uid() = user_id); - --- Performance Indexes -CREATE INDEX IF NOT EXISTS idx_posts_user_id ON public.posts(user_id); -CREATE INDEX IF NOT EXISTS idx_post_likes_post_id ON public.post_likes(post_id); -CREATE INDEX IF NOT EXISTS idx_post_comments_post_id ON public.post_comments(post_id); - --- Column upgrades: a project created from an older version of this file may be --- missing columns added later. No existing row is touched. -ALTER TABLE public.posts - ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS image_url TEXT, - ADD COLUMN IF NOT EXISTS caption TEXT, - ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()); - -ALTER TABLE public.post_likes - ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()); - -ALTER TABLE public.post_comments - ADD COLUMN IF NOT EXISTS post_id UUID REFERENCES public.posts(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS text TEXT, - ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()); - --- Primary key of post_likes is (post_id, user_id); add it only if it is absent. -DO $$ -BEGIN - IF NOT EXISTS (SELECT 1 FROM pg_constraint - WHERE conname = 'post_likes_pkey' - AND conrelid = 'public.post_likes'::regclass) THEN - ALTER TABLE public.post_likes ADD CONSTRAINT post_likes_pkey PRIMARY KEY (post_id, user_id); - END IF; -EXCEPTION WHEN OTHERS THEN - RAISE NOTICE 'post_likes primary key skipped: %', SQLERRM; -END $$; - --- Reload Schema -NOTIFY pgrst, 'reload schema'; diff --git a/sql/03_support_tickets_schema.sql b/sql/03_support_tickets_schema.sql deleted file mode 100644 index 596ce2c..0000000 --- a/sql/03_support_tickets_schema.sql +++ /dev/null @@ -1,51 +0,0 @@ --- ========================================================================= --- STEP 3/9: SUPPORT TICKETS --- ========================================================================= --- Run in the Supabase SQL Editor after 02_posts_and_interactions_schema.sql. --- Safe to re-run: nothing is dropped, existing tickets are kept. --- ========================================================================= - --- Create support tickets Table -CREATE TABLE IF NOT EXISTS public.support_tickets ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - user_id UUID REFERENCES public.users(id) ON DELETE SET NULL, - email TEXT NOT NULL, - category TEXT NOT NULL, - subject TEXT NOT NULL, - message TEXT NOT NULL, - status TEXT DEFAULT 'open' CHECK (status IN ('open', 'in_progress', 'resolved')), - created_at TIMESTAMPTZ DEFAULT NOW(), - updated_at TIMESTAMPTZ DEFAULT NOW() -); - --- Column upgrades for older installs (no existing row is touched). -ALTER TABLE public.support_tickets - ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE SET NULL, - ADD COLUMN IF NOT EXISTS email TEXT, - ADD COLUMN IF NOT EXISTS category TEXT, - ADD COLUMN IF NOT EXISTS subject TEXT, - ADD COLUMN IF NOT EXISTS message TEXT, - ADD COLUMN IF NOT EXISTS status TEXT DEFAULT 'open', - ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(), - ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT NOW(); - --- Enable Row Level Security (RLS) -ALTER TABLE public.support_tickets ENABLE ROW LEVEL SECURITY; - --- 1. Anonymous and Authenticated submittals -DROP POLICY IF EXISTS "Allow anonymous and authenticated ticket insertion" ON public.support_tickets; -CREATE POLICY "Allow anonymous and authenticated ticket insertion" ON public.support_tickets - FOR INSERT - WITH CHECK (true); - --- 2. Fetch logged tickets -DROP POLICY IF EXISTS "Allow users to view own tickets" ON public.support_tickets; -CREATE POLICY "Allow users to view own tickets" ON public.support_tickets - FOR SELECT - USING (auth.uid() = user_id); - --- Performance Indexing -CREATE INDEX IF NOT EXISTS idx_support_tickets_user_id ON public.support_tickets(user_id); - --- Reload Schema Cache -NOTIFY pgrst, 'reload schema'; diff --git a/sql/04_triggers_functions_and_rpc.sql b/sql/04_triggers_functions_and_rpc.sql deleted file mode 100644 index 7fdcf20..0000000 --- a/sql/04_triggers_functions_and_rpc.sql +++ /dev/null @@ -1,98 +0,0 @@ --- ========================================================================= --- STEP 4/9: RPC FUNCTIONS, TRIGGERS & AUTH -> PROFILE AUTO-SYNC --- ========================================================================= --- Run in the Supabase SQL Editor after 03_support_tickets_schema.sql. --- Safe to re-run: the trigger and the functions are dropped and re-created, so --- an updated definition always replaces the old one. No row is ever deleted. --- (`DROP FUNCTION` cannot lose the trigger's target: the trigger is dropped --- first, in the same run.) --- ========================================================================= - --- Clear existing Triggers & Functions -DROP TRIGGER IF EXISTS on_auth_user_created ON auth.users; -DROP FUNCTION IF EXISTS public.handle_new_auth_user(); -DROP FUNCTION IF EXISTS public.get_direct_conversation_id(UUID, UUID); - --- 1. Direct Conversation Match RPC (Guarantees Instant Room Lookups) -CREATE OR REPLACE FUNCTION public.get_direct_conversation_id(u1 UUID, u2 UUID) -RETURNS UUID AS $$ -DECLARE - conv_id UUID; -BEGIN - SELECT cp1.conversation_id INTO conv_id - FROM public.conversation_participants cp1 - JOIN public.conversation_participants cp2 - ON cp1.conversation_id = cp2.conversation_id - JOIN public.conversations c - ON cp1.conversation_id = c.id - WHERE cp1.user_id = u1 - AND cp2.user_id = u2 - AND c.type = 'direct' - LIMIT 1; - - RETURN conv_id; -END; -$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public; - - --- 2. Auth to Public user profiles sync (Essential for Signup and OAuth sign-in) -CREATE OR REPLACE FUNCTION public.handle_new_auth_user() -RETURNS TRIGGER AS $$ -DECLARE - username_val TEXT; - full_name_val TEXT; -BEGIN - -- Extract values safely from raw_user_meta_data or default to email split-part - username_val := COALESCE( - new.raw_user_meta_data->>'username', - split_part(new.email, '@', 1) - ); - full_name_val := COALESCE( - new.raw_user_meta_data->>'full_name', - split_part(new.email, '@', 1) - ); - - -- Clean the username values to be under 15 characters - username_val := SUBSTRING(username_val, 1, 15); - - -- Ensure uniqueness of username, append unique IDs if a duplicate is found - IF EXISTS (SELECT 1 FROM public.users WHERE username = username_val) THEN - username_val := SUBSTRING(username_val, 1, 9) || '_' || substring(new.id::text, 1, 5); - END IF; - - -- Insert profile safely - INSERT INTO public.users ( - id, - email, - phone, - full_name, - username, - photo_url, - bio - ) - VALUES ( - new.id, - new.email, - COALESCE(new.raw_user_meta_data->>'phone', ''), - full_name_val, - LOWER(username_val), - COALESCE(new.raw_user_meta_data->>'avatar_url', 'https://cdn-icons-png.flaticon.com/512/149/149071.png'), - 'Available' - ) - ON CONFLICT (id) DO UPDATE SET - email = EXCLUDED.email, - phone = COALESCE(public.users.phone, EXCLUDED.phone), - full_name = COALESCE(public.users.full_name, EXCLUDED.full_name), - username = COALESCE(public.users.username, EXCLUDED.username); - - RETURN NEW; -END; -$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public; - --- Bind trigger on auth.users (Runs completely on auth signup) -CREATE TRIGGER on_auth_user_created - AFTER INSERT ON auth.users - FOR EACH ROW EXECUTE FUNCTION public.handle_new_auth_user(); - --- Clear Schema cache -NOTIFY pgrst, 'reload schema'; diff --git a/sql/05_advanced_optimizations_and_realtime.sql b/sql/05_advanced_optimizations_and_realtime.sql deleted file mode 100644 index eea628e..0000000 --- a/sql/05_advanced_optimizations_and_realtime.sql +++ /dev/null @@ -1,233 +0,0 @@ --- ========================================================================= --- STEP 5/9: REALTIME PUBLICATION, PREVIEW TRIGGERS, HISTORY CAP --- ========================================================================= --- Run in the Supabase SQL Editor after 04_triggers_functions_and_rpc.sql. --- Safe to re-run: functions are CREATE OR REPLACE, triggers are dropped first, --- replica identity and publication membership are re-asserted. --- --- ⚠️ READ THIS BEFORE RUNNING — sections 1 and 6 DELETE MESSAGE HISTORY: --- every chat is capped at 60 rows, pruned back to the newest 40, on every --- insert. It keeps a free-tier project small, but it also means chat history --- is not kept. To keep history instead: do NOT run sections 1 and 6, and use --- the time-based pruner in 09_egress_optimizations.sql (`prune_old_messages`). --- ========================================================================= - --- 1. MESSAGE CAP PRUNER (LIMITS ROOMS TO LAST 60 MESSAGES - PRUNES TO 40) -CREATE OR REPLACE FUNCTION prune_past_messages() -RETURNS TRIGGER AS $$ -DECLARE - msg_count INT; -BEGIN - SELECT COUNT(*) INTO msg_count - FROM public.messages - WHERE conversation_id = NEW.conversation_id; - - IF msg_count >= 60 THEN - DELETE FROM public.messages - WHERE conversation_id = NEW.conversation_id - AND id NOT IN ( - SELECT subquery.id FROM ( - SELECT id FROM public.messages - WHERE conversation_id = NEW.conversation_id - ORDER BY created_at DESC, id DESC - LIMIT 40 - ) subquery - ); - END IF; - - RETURN NEW; -END; -$$ LANGUAGE plpgsql SECURITY DEFINER; - -DROP TRIGGER IF EXISTS trg_prune_past_messages ON public.messages; -CREATE TRIGGER trg_prune_past_messages -AFTER INSERT ON public.messages -FOR EACH ROW -EXECUTE FUNCTION prune_past_messages(); - - --- 2. AUTOMATICALLY SYNC NEW MESSAGES WITH CONVERSATIONS PREVIEWS -CREATE OR REPLACE FUNCTION update_conversation_timestamp_and_last_message() -RETURNS TRIGGER AS $$ -BEGIN - UPDATE public.conversations - SET - updated_at = NEW.created_at, - last_message = COALESCE(NEW.text, CASE WHEN NEW.media_type IS NOT NULL THEN 'Sent a ' || NEW.media_type ELSE 'Sent an attachment' END), - last_message_at = NEW.created_at - WHERE id = NEW.conversation_id; - RETURN NEW; -END; -$$ LANGUAGE plpgsql SECURITY DEFINER; - -DROP TRIGGER IF EXISTS trg_update_conversation_on_message ON public.messages; -CREATE TRIGGER trg_update_conversation_on_message -AFTER INSERT ON public.messages -FOR EACH ROW -EXECUTE FUNCTION update_conversation_timestamp_and_last_message(); - - --- 3. INTERACTIVE CALLS RECUPERATOR PRUNER (LIMITS CHRONO CALLS TO LAST 60) -CREATE OR REPLACE FUNCTION prune_past_calls() -RETURNS TRIGGER AS $$ -DECLARE - caller_call_count INT; - receiver_call_count INT; -BEGIN - SELECT COUNT(*) INTO caller_call_count - FROM public.calls - WHERE caller_id = NEW.caller_id OR receiver_id = NEW.caller_id; - - IF caller_call_count >= 60 THEN - DELETE FROM public.calls - WHERE (caller_id = NEW.caller_id OR receiver_id = NEW.caller_id) - AND id NOT IN ( - SELECT subquery.id FROM ( - SELECT id FROM public.calls - WHERE caller_id = NEW.caller_id OR receiver_id = NEW.caller_id - ORDER BY created_at DESC, id DESC - LIMIT 40 - ) subquery - ); - END IF; - - IF NEW.receiver_id IS NOT NULL AND NEW.receiver_id <> NEW.caller_id THEN - SELECT COUNT(*) INTO receiver_call_count - FROM public.calls - WHERE caller_id = NEW.receiver_id OR receiver_id = NEW.receiver_id; - - IF receiver_call_count >= 60 THEN - DELETE FROM public.calls - WHERE (caller_id = NEW.receiver_id OR receiver_id = NEW.receiver_id) - AND id NOT IN ( - SELECT subquery.id FROM ( - SELECT id FROM public.calls - WHERE caller_id = NEW.receiver_id OR receiver_id = NEW.receiver_id - ORDER BY created_at DESC, id DESC - LIMIT 40 - ) subquery - ); - END IF; - END IF; - - RETURN NEW; -END; -$$ LANGUAGE plpgsql SECURITY DEFINER; - -DROP TRIGGER IF EXISTS trg_prune_past_calls ON public.calls; -CREATE TRIGGER trg_prune_past_calls -AFTER INSERT ON public.calls -FOR EACH ROW -EXECUTE FUNCTION prune_past_calls(); - - --- 4. REPLICA IDENTITY --- --------------------------------------------------------------------------- --- FULL is only needed where the client filters DELETEs by a non-key column --- (`conversation_id=eq.…` on messages and conversation_participants). Everywhere --- else DEFAULT keeps UPDATE payloads to "new row + primary key", which stops --- whole rows — including `users.lock`, the app-lock passcode hash, and --- `fcm_tokens` — from being broadcast to every subscribed client. --- 09_egress_optimizations.sql re-asserts the same values, so either file leaves --- the database in this state. --- --------------------------------------------------------------------------- -DO $$ -DECLARE - target RECORD; -BEGIN - FOR target IN - SELECT * FROM (VALUES - ('users', 'DEFAULT'), - ('conversations', 'DEFAULT'), - ('calls', 'DEFAULT'), - ('call_candidates', 'DEFAULT'), - ('messages', 'FULL'), - ('conversation_participants','FULL') - ) AS t(tbl, identity) - LOOP - IF EXISTS (SELECT 1 FROM pg_class c - JOIN pg_namespace n ON n.oid = c.relnamespace - WHERE n.nspname = 'public' AND c.relname = target.tbl) THEN - EXECUTE format('ALTER TABLE public.%I REPLICA IDENTITY %s', target.tbl, target.identity); - END IF; - END LOOP; -END; -$$; - - --- 5. SUPABASE REALTIME PUBLICATION MEMBERSHIP --- --------------------------------------------------------------------------- --- Only the tables the client actually subscribes to. Membership is idempotent: --- a table is added only when it exists and is not already published, so a run --- over an existing project changes nothing and a fork that dropped a table --- (e.g. call_candidates) does not abort the script. --- --------------------------------------------------------------------------- -DO $$ -DECLARE - tbl TEXT; -BEGIN - IF NOT EXISTS (SELECT 1 FROM pg_publication WHERE pubname = 'supabase_realtime') THEN - CREATE PUBLICATION supabase_realtime; - END IF; - - FOREACH tbl IN ARRAY ARRAY[ - 'messages', 'conversations', 'users', 'calls', - 'call_candidates', 'conversation_participants' - ] LOOP - IF to_regclass('public.' || tbl) IS NOT NULL - AND NOT EXISTS (SELECT 1 FROM pg_publication_tables - WHERE pubname = 'supabase_realtime' - AND schemaname = 'public' - AND tablename = tbl) THEN - EXECUTE format('ALTER PUBLICATION supabase_realtime ADD TABLE public.%I', tbl); - END IF; - END LOOP; -END; -$$; - --- Also enable Realtime in the dashboard for these tables: --- Database -> Replication -> supabase_realtime --- The SQL above registers the tables; the dashboard toggle is what actually --- streams them. - - --- 6. RETROACTIVE SWEEP (trims pre-existing high-volume tables down to 40 rows) --- Same policy as section 1: it keeps the newest 40 messages per chat and the --- newest 40 calls per user. Skip this section if you skipped section 1. -DO $$ -DECLARE - u_rec RECORD; - conv_rec RECORD; -BEGIN - -- Prune existing calls back to newest 40 for every user - FOR u_rec IN (SELECT DISTINCT id FROM public.users) LOOP - DELETE FROM public.calls - WHERE (caller_id = u_rec.id OR receiver_id = u_rec.id) - AND id NOT IN ( - SELECT subquery.id FROM ( - SELECT id FROM public.calls - WHERE caller_id = u_rec.id OR receiver_id = u_rec.id - ORDER BY created_at DESC, id DESC - LIMIT 40 - ) subquery - ); - END LOOP; - - -- Prune existing messages back to newest 40 for every conversation room - FOR conv_rec IN (SELECT DISTINCT id FROM public.conversations) LOOP - DELETE FROM public.messages - WHERE conversation_id = conv_rec.id - AND id NOT IN ( - SELECT subquery.id FROM ( - SELECT id FROM public.messages - WHERE conversation_id = conv_rec.id - ORDER BY created_at DESC, id DESC - LIMIT 40 - ) subquery - ); - END LOOP; -END; -$$; - --- Reload Schema and notify PostgREST -NOTIFY pgrst, 'reload schema'; diff --git a/sql/06_storage_configurations.sql b/sql/06_storage_configurations.sql deleted file mode 100644 index 4849265..0000000 --- a/sql/06_storage_configurations.sql +++ /dev/null @@ -1,93 +0,0 @@ --- ========================================================================= --- STEP 6/9: STORAGE BUCKETS (chat-media, profiles) AND THEIR POLICIES --- ========================================================================= --- Run in the Supabase SQL Editor after 05_advanced_optimizations_and_realtime.sql. --- Safe to re-run: buckets are inserted with ON CONFLICT DO NOTHING and every --- policy is dropped and re-created, so an updated definition always wins. --- --- ⚠️ These policies are deliberately permissive (public read, any authenticated --- user may upload/update/delete in these buckets) because the app uploads to --- `chat-media/images/_.` — paths carry no user id, so --- ownership cannot be checked from the path. Hardening notes: --- docs/EGRESS_AUDIT.md §6 and the commented block in 09_egress_optimizations.sql. --- ========================================================================= - --- 1. PROVISION BUCKETS (If they do not already exist) -INSERT INTO storage.buckets (id, name, public, file_size_limit, allowed_mime_types) -VALUES - ('chat-media', 'chat-media', true, 52428800, NULL), -- 50 MB limit - ('profiles', 'profiles', true, 5242880, ARRAY['image/jpeg', 'image/png', 'image/gif', 'image/webp']) -- 5 MB limit -ON CONFLICT (id) DO NOTHING; - - --- 2. RE-ENABLE AND RESET STRATEGIC POLICIES FOR STORAGE OBJECTS --- Clean up any conflicting pre-existing policies for these buckets -DROP POLICY IF EXISTS "Public Access to chat-media" ON storage.objects; -DROP POLICY IF EXISTS "Authenticated Users can upload to chat-media" ON storage.objects; -DROP POLICY IF EXISTS "Owners can update their own chat-media objects" ON storage.objects; -DROP POLICY IF EXISTS "Owners can delete their own chat-media objects" ON storage.objects; - -DROP POLICY IF EXISTS "Public Access to profiles" ON storage.objects; -DROP POLICY IF EXISTS "Authenticated Users can upload to profiles" ON storage.objects; -DROP POLICY IF EXISTS "Owners can update their own profiles" ON storage.objects; -DROP POLICY IF EXISTS "Owners can delete their own profiles" ON storage.objects; - - --- 3. APPLY SECURITY POLICIES FOR 'chat-media' BUCKET - --- Read Policy: Anyone can read media (Publicly accessible) -CREATE POLICY "Public Access to chat-media" -ON storage.objects FOR SELECT -TO public -USING (bucket_id = 'chat-media'); - --- Write Policy: Authenticated users can insert files -CREATE POLICY "Authenticated Users can upload to chat-media" -ON storage.objects FOR INSERT -TO authenticated -WITH CHECK (bucket_id = 'chat-media' AND (auth.uid()::text = (storage.foldername(name))[1] OR true)); - --- Update Policy: Authenticated owners can update files -CREATE POLICY "Owners can update their own chat-media objects" -ON storage.objects FOR UPDATE -TO authenticated -USING (bucket_id = 'chat-media') -WITH CHECK (bucket_id = 'chat-media'); - --- Delete Policy: Authenticated users can delete files they own -CREATE POLICY "Owners can delete their own chat-media objects" -ON storage.objects FOR DELETE -TO authenticated -USING (bucket_id = 'chat-media'); - - --- 4. APPLY SECURITY POLICIES FOR 'profiles' BUCKET - --- Read Policy: Anyone can read profiles photos (Publicly accessible) -CREATE POLICY "Public Access to profiles" -ON storage.objects FOR SELECT -TO public -USING (bucket_id = 'profiles'); - --- Write Policy: Authenticated users can upload profile icons -CREATE POLICY "Authenticated Users can upload to profiles" -ON storage.objects FOR INSERT -TO authenticated -WITH CHECK (bucket_id = 'profiles'); - --- Update Policy: Authenticated users can replace profile icons -CREATE POLICY "Owners can update their own profiles" -ON storage.objects FOR UPDATE -TO authenticated -USING (bucket_id = 'profiles') -WITH CHECK (bucket_id = 'profiles'); - --- Delete Policy: Authenticated users can delete profile icons -CREATE POLICY "Owners can delete their own profiles" -ON storage.objects FOR DELETE -TO authenticated -USING (bucket_id = 'profiles'); - - --- 5. RELOAD POSTGRES SCHEMA CACHE -NOTIFY pgrst, 'reload schema'; diff --git a/sql/07_chat_time_scheduling_migration.sql b/sql/07_chat_time_scheduling_migration.sql deleted file mode 100644 index 4e83c57..0000000 --- a/sql/07_chat_time_scheduling_migration.sql +++ /dev/null @@ -1,9 +0,0 @@ --- Incremental Migration for Chat Time Scheduling --- Purpose: Add support for custom chat times, allowing users of direct chats to set allowed days/times. --- Integrates directly inside public.conversations table under watch_state JSONB field, with defensive fallback. - -ALTER TABLE public.conversations ADD COLUMN IF NOT EXISTS chat_time_restrictions JSONB DEFAULT NULL; - --- Keep Row Level Security enabled for access constraints --- Triggers a reload of PostgREST schema cache to make column visible -NOTIFY pgrst, 'reload schema'; diff --git a/sql/08_stories_expiration_and_views.sql b/sql/08_stories_expiration_and_views.sql deleted file mode 100644 index f087834..0000000 --- a/sql/08_stories_expiration_and_views.sql +++ /dev/null @@ -1,42 +0,0 @@ --- Incremental Migration for Stories Expiration (24h) and Views tracking --- Purpose: Adds views column to stories table, adds view_story RPC, and adds cleanup_expired_stories RPC. - --- 1. Add views JSONb column to stories table -ALTER TABLE public.stories ADD COLUMN IF NOT EXISTS views JSONB DEFAULT '[]'::JSONB NOT NULL; - --- 2. Create RPC to register a view securely without exposing direct update permissions --- This is written in the simplest possible form to avoid any PL/pgSQL parsing issues. -CREATE OR REPLACE FUNCTION public.view_story( - story_id_param UUID, - viewer_id_param UUID, - viewer_username_param TEXT, - viewer_fullname_param TEXT, - viewer_photo_url_param TEXT -) -RETURNS VOID AS $$ -BEGIN - UPDATE public.stories - SET views = COALESCE(views, '[]'::JSONB) || jsonb_build_array( - jsonb_build_object( - 'id', viewer_id_param, - 'username', viewer_username_param, - 'full_name', viewer_fullname_param, - 'photo_url', viewer_photo_url_param, - 'viewed_at', NOW() - ) - ) - WHERE id = story_id_param - AND NOT (COALESCE(views, '[]'::JSONB) @> jsonb_build_array(jsonb_build_object('id', viewer_id_param::text))); -END; -$$ LANGUAGE plpgsql SECURITY DEFINER; - --- 3. Create RPC to clean up stories older than 24 hours -CREATE OR REPLACE FUNCTION public.cleanup_expired_stories() -RETURNS VOID AS $$ -BEGIN - DELETE FROM public.stories WHERE created_at < NOW() - INTERVAL '24 hours'; -END; -$$ LANGUAGE plpgsql SECURITY DEFINER; - --- Trigger schema reload -NOTIFY pgrst, 'reload schema'; diff --git a/sql/09_egress_optimizations.sql b/sql/09_egress_optimizations.sql deleted file mode 100644 index f027502..0000000 --- a/sql/09_egress_optimizations.sql +++ /dev/null @@ -1,382 +0,0 @@ --- ═══════════════════════════════════════════════════════════════════════════ --- 09 — Egress optimizations --- --- Apply this in the Supabase SQL editor: Database → SQL Editor → New query. --- It is idempotent, so running it twice is safe. --- --- Why: the app consumed 5 GB of egress in under a month with 2–3 active users. --- The client-side cause (a full conversation-list refetch per realtime event) --- is fixed in code — see docs/EGRESS_AUDIT.md. This file fixes the database --- half, which cannot be changed from the repository: --- --- 1. `last_read_at` — read receipts become ONE row update instead of one per --- unread message (each of which was broadcast to every client). --- 2. Denormalized `last_message*` maintained by trigger, so the chat list --- never has to fetch message rows just to draw a one-line preview. --- 3. REPLICA IDENTITY: stop broadcasting whole rows (including the passcode --- hash and FCM tokens in `users`) on every UPDATE. --- 4. Indexes for the hot paths. --- 5. Optional retention pruner for old messages. --- ═══════════════════════════════════════════════════════════════════════════ - - --- ── 1. Read marker ───────────────────────────────────────────────────────── --- Unread is a comparison: conversations.last_message_at > my last_read_at. --- One UPDATE per "I opened/read this chat" instead of one row per message. - --- Existing rows are stamped with the moment this runs, so history starts --- "read" and nobody gets a fake 400-message unread badge. -ALTER TABLE public.conversation_participants - ADD COLUMN IF NOT EXISTS last_read_at TIMESTAMPTZ DEFAULT NOW(); - --- The client updates ITS OWN row to say "I have read up to here". Without this --- policy the UPDATE matches no policy, affects 0 rows, and returns no error — --- the read marker would silently never move. (RLS is on for this table, and --- 01_core_schema.sql only defined SELECT/INSERT/DELETE.) -DROP POLICY IF EXISTS "Participants can update their own membership" ON public.conversation_participants; -CREATE POLICY "Participants can update their own membership" - ON public.conversation_participants - FOR UPDATE - USING (user_id = auth.uid()) - WITH CHECK (user_id = auth.uid()); - -CREATE INDEX IF NOT EXISTS idx_participants_user_last_read - ON public.conversation_participants(user_id, last_read_at DESC); - --- Realtime: the client subscribes with `user_id=eq.` and must also receive --- DELETEs (a participant removed from a group). DEFAULT identity only carries --- the primary key in the `old` record, so the server cannot evaluate the filter --- for deletes. These rows are tiny and rarely written, so FULL is cheap here. -ALTER TABLE public.conversation_participants REPLICA IDENTITY FULL; - - --- ── 2. `last_message*` is maintained by the database ─────────────────────── --- The chat list shows `last_message` / `last_message_at` / (for ticks) the --- sender. Writers already set the first two; the trigger also covers edits, --- deletes and direct SQL inserts, so the client never needs to re-read the --- newest messages for every conversation. - -ALTER TABLE public.conversations - ADD COLUMN IF NOT EXISTS last_message_sender_id UUID; - -CREATE OR REPLACE FUNCTION public.sync_conversation_last_message() -RETURNS TRIGGER -LANGUAGE plpgsql -SECURITY DEFINER -SET search_path = public -AS $$ -DECLARE - target_conversation UUID; - newest RECORD; -BEGIN - target_conversation := COALESCE(NEW.conversation_id, OLD.conversation_id); - IF target_conversation IS NULL THEN - RETURN NULL; - END IF; - - -- Fast path: a new (or edited) message that is not older than what the - -- conversation already shows IS the newest one, so write it across without - -- looking at the table. Appends are the hot path: no extra index scan. - IF TG_OP <> 'DELETE' AND NEW.is_deleted = false THEN - UPDATE public.conversations - SET last_message = COALESCE(NEW.text, - 'Sent a ' || COALESCE(NEW.media_type, 'file')), - last_message_at = NEW.created_at, - last_message_sender_id = NEW.sender_id - WHERE id = target_conversation - AND (last_message_at IS NULL OR NEW.created_at >= last_message_at); - IF FOUND THEN - RETURN NULL; - END IF; - END IF; - - -- Fast skip for DELETEs: if the conversation already shows something newer, - -- removing an older row cannot change the preview. This is the common case - -- for the 40-message history cap in 05, which deletes a batch per insert. - IF TG_OP = 'DELETE' AND EXISTS ( - SELECT 1 FROM public.conversations - WHERE id = target_conversation - AND last_message_at IS NOT NULL - AND last_message_at > OLD.created_at - ) THEN - RETURN NULL; - END IF; - - -- Slow path: a delete of the newest row, a soft delete, or an edit of an - -- older message. The preview has to be re-derived from what is left. - SELECT m.text, m.media_type, m.created_at, m.sender_id, m.is_deleted - INTO newest - FROM public.messages m - WHERE m.conversation_id = target_conversation - AND m.is_deleted = false - ORDER BY m.created_at DESC - LIMIT 1; - - IF NOT FOUND THEN - UPDATE public.conversations - SET last_message = NULL, - last_message_at = NULL, - last_message_sender_id = NULL - WHERE id = target_conversation; - ELSE - UPDATE public.conversations - SET last_message = COALESCE(newest.text, - 'Sent a ' || COALESCE(newest.media_type, 'file')), - last_message_at = newest.created_at, - last_message_sender_id = newest.sender_id - WHERE id = target_conversation; - END IF; - - RETURN NULL; -END; -$$; - -DROP TRIGGER IF EXISTS trg_sync_conversation_last_message ON public.messages; -CREATE TRIGGER trg_sync_conversation_last_message - AFTER INSERT OR UPDATE OF text, media_type, is_deleted OR DELETE - ON public.messages - FOR EACH ROW - EXECUTE FUNCTION public.sync_conversation_last_message(); - --- The fast path above needs no lookup at all; only edits/deletes of older --- messages touch the index below, and they resolve it in one index scan. - -CREATE INDEX IF NOT EXISTS idx_messages_conv_created - ON public.messages(conversation_id, created_at DESC); - -CREATE INDEX IF NOT EXISTS idx_conversations_last_message_at - ON public.conversations(last_message_at DESC NULLS LAST); - --- Legacy path only (used until the client detects `last_read_at`). -CREATE INDEX IF NOT EXISTS idx_messages_unread - ON public.messages(conversation_id) - WHERE is_read = false; - - --- ── 3. Stop broadcasting whole rows on UPDATE ────────────────────────────── --- `REPLICA IDENTITY FULL` makes every UPDATE emit the complete OLD row and the --- complete NEW row to every subscribed client. On `users` that payload includes --- `settings`, `lock` (passcode hash!) and `fcm_tokens`. DEFAULT sends the new --- row plus the primary key only — smaller, and no private columns on the wire. --- --- `messages` is deliberately NOT in this list. `useChatMessages` listens for --- DELETE events with a `conversation_id=eq.…` filter, and the filter column is --- only present in the `old` record when the identity is FULL — with DEFAULT the --- event cannot be matched and "delete for everyone" would stop propagating. --- The read-marker change (section 1) is what removes messages UPDATE traffic; --- deletes are rare, so FULL stays there. --- --- `conversations`, `users` and `calls` are only ever read via `payload.new` on --- the client (and a conversation DELETE also removes its participant rows, which --- ARE FULL), so DEFAULT is safe for them. Calls are status-UPDATEd, never --- deleted (`CallProvider` zombie sweep). The pair of `FULL` entries re-asserts --- the two tables whose filtered DELETEs the client depends on, so this file --- leaves the database correct no matter which earlier scripts were applied. - -DO $$ -DECLARE - target RECORD; -BEGIN - FOR target IN - SELECT * FROM (VALUES - ('users', 'DEFAULT'), - ('conversations', 'DEFAULT'), - ('calls', 'DEFAULT'), - ('call_candidates', 'DEFAULT'), - ('messages', 'FULL'), - ('conversation_participants','FULL') - ) AS t(tbl, identity) - LOOP - IF EXISTS (SELECT 1 FROM pg_class c - JOIN pg_namespace n ON n.oid = c.relnamespace - WHERE n.nspname = 'public' AND c.relname = target.tbl) THEN - EXECUTE format('ALTER TABLE public.%I REPLICA IDENTITY %s', - target.tbl, target.identity); - END IF; - END LOOP; -END; -$$; - - --- Advanced (optional, experimental): if messages UPDATE payloads ever matter --- again, `ALTER TABLE public.messages REPLICA IDENTITY USING INDEX --- messages_id_conversation_id_key;` (with a UNIQUE index on (id, --- conversation_id)) makes the `old` record carry just those two columns. Verify --- in the Realtime inspector that DELETE events still arrive before relying on --- it. - --- ── 4. Unread counts without a per-message scan (optional, recommended) ──── --- Call: supabase.rpc('get_unread_counts') --- Returns one row per conversation with a badge, instead of one row per unread --- message. `last_read_at` already removes the need; this is exact and cheap. - -CREATE OR REPLACE FUNCTION public.get_unread_counts() -RETURNS TABLE (conversation_id UUID, unread_count BIGINT) -LANGUAGE sql -STABLE -SECURITY DEFINER -SET search_path = public -AS $$ - SELECT m.conversation_id, COUNT(*) AS unread_count - FROM public.messages m - JOIN public.conversation_participants cp - ON cp.conversation_id = m.conversation_id - AND cp.user_id = auth.uid() - WHERE m.sender_id <> auth.uid() - AND m.is_deleted = false - AND (cp.last_read_at IS NULL OR m.created_at > cp.last_read_at) - GROUP BY m.conversation_id; -$$; - -GRANT EXECUTE ON FUNCTION public.get_unread_counts() TO authenticated; - - --- ── 5. Retention (run when you want it — nothing calls it automatically) ─── --- Egress is paid on read, not on storage, but a smaller table keeps the --- unread/latest queries from degrading. Deletes soft-deleted rows and anything --- older than `keep_days` for conversations that are inactive. - -CREATE OR REPLACE FUNCTION public.prune_old_messages(keep_days INTEGER DEFAULT 90) -RETURNS INTEGER -LANGUAGE plpgsql -SECURITY DEFINER -SET search_path = public -AS $$ -DECLARE - removed INTEGER := 0; - affected UUID[]; -BEGIN - SELECT array_agg(DISTINCT conversation_id) INTO affected - FROM ( - SELECT m.conversation_id - FROM public.messages m - JOIN public.conversations c ON c.id = m.conversation_id - WHERE m.created_at < NOW() - make_interval(days => keep_days) - AND c.updated_at < NOW() - make_interval(days => keep_days) - ORDER BY m.created_at - LIMIT 5000 - ) t; - - IF affected IS NULL THEN - RETURN 0; - END IF; - - -- The per-row last_message trigger would fire once per deleted row (5000 - -- index scans); the last_message of these inactive conversations is - -- recomputed in one pass below instead. DDL is transactional, so this rolls - -- back with the function if anything fails. - BEGIN - ALTER TABLE public.messages DISABLE TRIGGER trg_sync_conversation_last_message; - EXCEPTION WHEN OTHERS THEN - NULL; -- not the table owner; the trigger just stays on - END; - - DELETE FROM public.messages m - USING ( - SELECT m2.id - FROM public.messages m2 - JOIN public.conversations c ON c.id = m2.conversation_id - WHERE m2.created_at < NOW() - make_interval(days => keep_days) - AND c.updated_at < NOW() - make_interval(days => keep_days) - ORDER BY m2.created_at - LIMIT 5000 - ) stale - WHERE m.id = stale.id; - - GET DIAGNOSTICS removed = ROW_COUNT; - - BEGIN - ALTER TABLE public.messages ENABLE TRIGGER trg_sync_conversation_last_message; - EXCEPTION WHEN OTHERS THEN - NULL; - END; - - UPDATE public.conversations c - SET last_message = x.text, - last_message_at = x.created_at, - last_message_sender_id = x.sender_id - FROM ( - SELECT DISTINCT ON (m.conversation_id) - m.conversation_id, m.text, m.created_at, m.sender_id - FROM public.messages m - WHERE m.conversation_id = ANY(affected) - AND m.is_deleted = false - ORDER BY m.conversation_id, m.created_at DESC - ) x - WHERE c.id = x.conversation_id; - - RETURN removed; -END; -$$; - --- Example: keep the last 90 days. --- SELECT public.prune_old_messages(90); --- Scheduled (needs the pg_cron extension enabled in Dashboard → Database → --- Extensions): --- SELECT cron.schedule('prune-messages', '0 4 * * *', $$SELECT public.prune_old_messages(90)$$); - - --- ── 5b. Optional hardening (commented out — read before enabling) ────────── --- `conversation_participants` is readable by EVERY authenticated user --- (`FOR SELECT USING (true)`), which leaks who-talks-to-whom, and `users` is --- readable the same way, which leaks `email`, `phone`, `lock` (passcode hash!) --- and `fcm_tokens` of every account. Neither is an egress bug, but both are --- foundation mistakes worth closing. The membership check below needs a --- SECURITY DEFINER helper: a policy on the table cannot query the same table --- (Postgres raises "infinite recursion detected in policy"). --- --- CREATE OR REPLACE FUNCTION public.is_conversation_member(conv UUID, uid UUID) --- RETURNS BOOLEAN LANGUAGE sql STABLE SECURITY DEFINER SET search_path = public --- AS $$ SELECT EXISTS (SELECT 1 FROM public.conversation_participants --- WHERE conversation_id = conv AND user_id = uid); $$; --- --- DROP POLICY IF EXISTS "Allow auth users to inspect participants" --- ON public.conversation_participants; --- CREATE POLICY "Members can inspect their conversations' participants" --- ON public.conversation_participants FOR SELECT --- USING (public.is_conversation_member(conversation_id, auth.uid())); --- --- DROP POLICY IF EXISTS "Allow public read access on profiles" ON public.users; --- CREATE POLICY "Profiles are readable, secrets are not" ON public.users --- FOR SELECT USING (true); -- plus a view/column grants, see --- -- docs/EGRESS_AUDIT.md §6.4 - - --- ── 6. Sanity check ──────────────────────────────────────────────────────── --- Run this afterwards; every row should read like the expected value. -SELECT 'conversation_participants.last_read_at' AS what, - CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END AS state - FROM information_schema.columns - WHERE table_schema = 'public' AND table_name = 'conversation_participants' - AND column_name = 'last_read_at' -UNION ALL -SELECT 'conversations.last_message_sender_id', - CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END - FROM information_schema.columns - WHERE table_schema = 'public' AND table_name = 'conversations' - AND column_name = 'last_message_sender_id' -UNION ALL -SELECT 'replica identity: users', - COALESCE((SELECT CASE WHEN c.relreplident = 'f' THEN 'STILL FULL' ELSE 'OK (default)' END - FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace - WHERE n.nspname = 'public' AND c.relname = 'users'), 'MISSING') -UNION ALL -SELECT 'replica identity: conversations (expect default)', - COALESCE((SELECT CASE WHEN c.relreplident = 'f' THEN 'STILL FULL' ELSE 'OK (default)' END - FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace - WHERE n.nspname = 'public' AND c.relname = 'conversations'), 'MISSING') -UNION ALL -SELECT 'replica identity: messages (expect FULL)', - COALESCE((SELECT CASE WHEN c.relreplident = 'f' THEN 'OK (full)' ELSE 'CHANGED - deletes will stop reaching clients' END - FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace - WHERE n.nspname = 'public' AND c.relname = 'messages'), 'MISSING') -UNION ALL -SELECT 'sync trigger on messages', - CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END - FROM pg_trigger - WHERE tgname = 'trg_sync_conversation_last_message' -UNION ALL -SELECT 'UPDATE policy on conversation_participants', - CASE WHEN COUNT(*) FILTER (WHERE cmd = 'UPDATE') > 0 THEN 'OK' ELSE 'MISSING' END - FROM pg_policies - WHERE schemaname = 'public' AND tablename = 'conversation_participants'; diff --git a/sql/grixchat_full_setup.sql b/sql/grixchat_full_setup.sql deleted file mode 100644 index 172fac1..0000000 --- a/sql/grixchat_full_setup.sql +++ /dev/null @@ -1,1626 +0,0 @@ --- ══════════════════════════════════════════════════════════════════════════ --- GRIXCHAT — COMPLETE SUPABASE SETUP (generated, do not edit by hand) --- ══════════════════════════════════════════════════════════════════════════ --- One paste for a brand-new Supabase project: --- Supabase Dashboard -> SQL Editor -> New query -> paste ALL of this -> RUN. --- --- Safe to run again later, on the same project, at any time: --- * nothing is dropped or truncated --- * tables/columns/indexes/constraints are created only when missing --- * policies and functions are re-created, so updated definitions apply --- * existing rows are never modified --- --- Generated by: npm run sql:bundle (source: sql/01_*.sql … sql/09_*.sql) --- Read first: sql/00_master_instructions.md --- ══════════════════════════════════════════════════════════════════════════ - - --- ══════════════════════════════════════════════════════════════════════════ --- PART 1/9 — sql/01_core_schema.sql --- (generated from the file of that name; edit THAT file, then re-run --- "npm run sql:bundle" — do not edit this bundle by hand) --- ══════════════════════════════════════════════════════════════════════════ - --- ========================================================================= --- STEP 1/9: GRIXCHAT CORE SCHEMA (users, chats, messages, calls, ...) --- ========================================================================= --- Supabase Dashboard -> SQL Editor -> New query -> paste -> RUN. --- Then continue with 02, 03, ... 09 in order (see 00_master_instructions.md). --- --- SAFE TO RE-RUN, ON A FRESH PROJECT AND ON A LIVE ONE: --- * nothing is dropped or truncated — no `DROP TABLE`, ever --- * tables are created only if missing, missing columns/indexes/constraints --- are added, policies are re-created so an updated definition replaces the --- old one --- * existing rows are never modified by this file --- ========================================================================= - --- 2. TABLES (created only if missing) - --- User Profiles (Integrated with auth.users) -CREATE TABLE IF NOT EXISTS public.users ( - id UUID PRIMARY KEY REFERENCES auth.users ON DELETE CASCADE, - email TEXT, - phone TEXT, - full_name TEXT, - username TEXT UNIQUE NOT NULL, - photo_url TEXT DEFAULT 'https://cdn-icons-png.flaticon.com/512/149/149071.png', - bio TEXT DEFAULT 'Available', - is_verified BOOLEAN DEFAULT FALSE, - profile_type TEXT DEFAULT 'personal', - is_online BOOLEAN DEFAULT FALSE, - last_seen TIMESTAMPTZ DEFAULT NOW(), - updated_at TIMESTAMPTZ DEFAULT NOW(), - settings JSONB DEFAULT '{}'::jsonb, - lock JSONB DEFAULT NULL, -- Passcode lock hash & configuration - blocked_users TEXT[] DEFAULT '{}'::text[], - muted_users TEXT[] DEFAULT '{}'::text[], - favorites TEXT[] DEFAULT '{}'::text[], - hidden_chats TEXT[] DEFAULT '{}'::text[], - archived_chats TEXT[] DEFAULT '{}'::text[], - hidden_chat_settings JSONB DEFAULT '{"secretCode": null, "showMenuEntry": true}'::jsonb, - fcm_tokens TEXT[] DEFAULT '{}'::text[], - CONSTRAINT username_length_check CHECK (char_length(username) <= 15) -); - --- Connections / Followers / Friends -CREATE TABLE IF NOT EXISTS public.follows ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - follower_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, - following_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, - created_at TIMESTAMPTZ DEFAULT NOW(), - CONSTRAINT follows_unique_pair UNIQUE (follower_id, following_id) -); - --- Conversation Rooms (Direct & Group chats) -CREATE TABLE IF NOT EXISTS public.conversations ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - type TEXT NOT NULL CHECK (type IN ('direct', 'group')), - name TEXT, - photo_url TEXT, - admins UUID[] DEFAULT '{}'::uuid[], - watch_video_url TEXT, - watch_state JSONB DEFAULT '{}'::jsonb, - last_message TEXT, - last_message_at TIMESTAMPTZ, - created_at TIMESTAMPTZ DEFAULT NOW(), - updated_at TIMESTAMPTZ DEFAULT NOW() -); - --- Conversation Roster / Members -CREATE TABLE IF NOT EXISTS public.conversation_participants ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - conversation_id UUID REFERENCES public.conversations(id) ON DELETE CASCADE NOT NULL, - user_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, - created_at TIMESTAMPTZ DEFAULT NOW(), - joined_at TIMESTAMPTZ DEFAULT NOW(), - CONSTRAINT conversation_participants_unique_pair UNIQUE (conversation_id, user_id) -); - --- Chat Messages -CREATE TABLE IF NOT EXISTS public.messages ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - conversation_id UUID REFERENCES public.conversations(id) ON DELETE CASCADE NOT NULL, - sender_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, - text TEXT, - media_url TEXT, - media_type TEXT, - reply_to UUID REFERENCES public.messages(id) ON DELETE SET NULL, - reactions JSONB DEFAULT '{}'::jsonb, - is_read BOOLEAN DEFAULT FALSE, - is_edited BOOLEAN DEFAULT FALSE, - is_deleted BOOLEAN DEFAULT FALSE, - deleted_by UUID[] DEFAULT '{}'::UUID[], -- Tracks delete for me IDs - created_at TIMESTAMPTZ DEFAULT NOW() -); - --- Stories & Status Updates -CREATE TABLE IF NOT EXISTS public.stories ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - user_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, - media_url TEXT, - type TEXT DEFAULT 'image', -- 'image', 'text', 'video' - text_content TEXT, - bg_color TEXT, - music_title TEXT, - music_artist TEXT, - music_url TEXT, - filter_applied TEXT, - created_at TIMESTAMPTZ DEFAULT NOW() -); - --- Voice / Video Calls -CREATE TABLE IF NOT EXISTS public.calls ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - caller_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, - receiver_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, - type TEXT CHECK (type IN ('audio', 'video')) NOT NULL, - status TEXT DEFAULT 'ringing' CHECK (status IN ('ringing', 'accepted', 'rejected', 'ended', 'error')), - offer JSONB, - answer JSONB, - is_missed BOOLEAN DEFAULT FALSE, - created_at TIMESTAMPTZ DEFAULT NOW() -); - --- WebRTC ICE Candidates Signaling -CREATE TABLE IF NOT EXISTS public.call_candidates ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - call_id UUID REFERENCES public.calls(id) ON DELETE CASCADE NOT NULL, - user_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, - candidate JSONB NOT NULL, - type TEXT NOT NULL, -- 'offer' or 'answer' candidate - created_at TIMESTAMPTZ DEFAULT NOW() -); - --- Personalized Chat Settings & Customizations -CREATE TABLE IF NOT EXISTS public.chat_settings ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - user_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, - receiver_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, - nickname TEXT, - custom_photo_url TEXT, - is_muted BOOLEAN DEFAULT FALSE, - created_at TIMESTAMPTZ DEFAULT NOW(), - CONSTRAINT chat_settings_unique_pair UNIQUE (user_id, receiver_id) -); - --- System & Interaction Notifications -CREATE TABLE IF NOT EXISTS public.notifications ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - user_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL, - from_user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - type TEXT NOT NULL, - title TEXT, - content TEXT, - is_read BOOLEAN DEFAULT FALSE, - post_id TEXT, - created_at TIMESTAMPTZ DEFAULT NOW() -); - --- 3. COLUMN UPGRADES --- --------------------------------------------------------------------------- --- A project created from an older version of this file can be missing columns --- that were added later. `ADD COLUMN IF NOT EXISTS` makes every install converge --- on the same shape without touching a single existing row. --- --------------------------------------------------------------------------- - -ALTER TABLE public.users - ADD COLUMN IF NOT EXISTS email TEXT, - ADD COLUMN IF NOT EXISTS phone TEXT, - ADD COLUMN IF NOT EXISTS full_name TEXT, - ADD COLUMN IF NOT EXISTS username TEXT, - ADD COLUMN IF NOT EXISTS photo_url TEXT DEFAULT 'https://cdn-icons-png.flaticon.com/512/149/149071.png', - ADD COLUMN IF NOT EXISTS bio TEXT DEFAULT 'Available', - ADD COLUMN IF NOT EXISTS is_verified BOOLEAN DEFAULT FALSE, - ADD COLUMN IF NOT EXISTS profile_type TEXT DEFAULT 'personal', - ADD COLUMN IF NOT EXISTS is_online BOOLEAN DEFAULT FALSE, - ADD COLUMN IF NOT EXISTS last_seen TIMESTAMPTZ DEFAULT NOW(), - ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT NOW(), - ADD COLUMN IF NOT EXISTS settings JSONB DEFAULT '{}'::jsonb, - ADD COLUMN IF NOT EXISTS lock JSONB DEFAULT NULL, - ADD COLUMN IF NOT EXISTS blocked_users TEXT[] DEFAULT '{}'::text[], - ADD COLUMN IF NOT EXISTS muted_users TEXT[] DEFAULT '{}'::text[], - ADD COLUMN IF NOT EXISTS favorites TEXT[] DEFAULT '{}'::text[], - ADD COLUMN IF NOT EXISTS hidden_chats TEXT[] DEFAULT '{}'::text[], - ADD COLUMN IF NOT EXISTS archived_chats TEXT[] DEFAULT '{}'::text[], - ADD COLUMN IF NOT EXISTS hidden_chat_settings JSONB DEFAULT '{"secretCode": null, "showMenuEntry": true}'::jsonb, - ADD COLUMN IF NOT EXISTS fcm_tokens TEXT[] DEFAULT '{}'::text[]; - -ALTER TABLE public.follows - ADD COLUMN IF NOT EXISTS follower_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS following_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); - -ALTER TABLE public.conversations - ADD COLUMN IF NOT EXISTS type TEXT, - ADD COLUMN IF NOT EXISTS name TEXT, - ADD COLUMN IF NOT EXISTS photo_url TEXT, - ADD COLUMN IF NOT EXISTS admins UUID[] DEFAULT '{}'::uuid[], - ADD COLUMN IF NOT EXISTS watch_video_url TEXT, - ADD COLUMN IF NOT EXISTS watch_state JSONB DEFAULT '{}'::jsonb, - ADD COLUMN IF NOT EXISTS last_message TEXT, - ADD COLUMN IF NOT EXISTS last_message_at TIMESTAMPTZ, - ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(), - ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT NOW(); - -ALTER TABLE public.conversation_participants - ADD COLUMN IF NOT EXISTS conversation_id UUID REFERENCES public.conversations(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(), - ADD COLUMN IF NOT EXISTS joined_at TIMESTAMPTZ DEFAULT NOW(); - -ALTER TABLE public.messages - ADD COLUMN IF NOT EXISTS conversation_id UUID REFERENCES public.conversations(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS sender_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS text TEXT, - ADD COLUMN IF NOT EXISTS media_url TEXT, - ADD COLUMN IF NOT EXISTS media_type TEXT, - ADD COLUMN IF NOT EXISTS reply_to UUID REFERENCES public.messages(id) ON DELETE SET NULL, - ADD COLUMN IF NOT EXISTS reactions JSONB DEFAULT '{}'::jsonb, - ADD COLUMN IF NOT EXISTS is_read BOOLEAN DEFAULT FALSE, - ADD COLUMN IF NOT EXISTS is_edited BOOLEAN DEFAULT FALSE, - ADD COLUMN IF NOT EXISTS is_deleted BOOLEAN DEFAULT FALSE, - ADD COLUMN IF NOT EXISTS deleted_by UUID[] DEFAULT '{}'::UUID[], - ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); - -ALTER TABLE public.stories - ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS media_url TEXT, - ADD COLUMN IF NOT EXISTS type TEXT DEFAULT 'image', - ADD COLUMN IF NOT EXISTS text_content TEXT, - ADD COLUMN IF NOT EXISTS bg_color TEXT, - ADD COLUMN IF NOT EXISTS music_title TEXT, - ADD COLUMN IF NOT EXISTS music_artist TEXT, - ADD COLUMN IF NOT EXISTS music_url TEXT, - ADD COLUMN IF NOT EXISTS filter_applied TEXT, - ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); - -ALTER TABLE public.calls - ADD COLUMN IF NOT EXISTS caller_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS receiver_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS type TEXT, - ADD COLUMN IF NOT EXISTS status TEXT DEFAULT 'ringing', - ADD COLUMN IF NOT EXISTS offer JSONB, - ADD COLUMN IF NOT EXISTS answer JSONB, - ADD COLUMN IF NOT EXISTS is_missed BOOLEAN DEFAULT FALSE, - ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); - -ALTER TABLE public.call_candidates - ADD COLUMN IF NOT EXISTS call_id UUID REFERENCES public.calls(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS candidate JSONB, - ADD COLUMN IF NOT EXISTS type TEXT, - ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); - -ALTER TABLE public.chat_settings - ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS receiver_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS nickname TEXT, - ADD COLUMN IF NOT EXISTS custom_photo_url TEXT, - ADD COLUMN IF NOT EXISTS is_muted BOOLEAN DEFAULT FALSE, - ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); - -ALTER TABLE public.notifications - ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS from_user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS type TEXT, - ADD COLUMN IF NOT EXISTS title TEXT, - ADD COLUMN IF NOT EXISTS content TEXT, - ADD COLUMN IF NOT EXISTS is_read BOOLEAN DEFAULT FALSE, - ADD COLUMN IF NOT EXISTS post_id TEXT, - ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(); - --- NOT NULL is enforced only when the data already satisfies it, so an old table --- with stray NULLs never makes this script abort. -DO $$ -BEGIN - IF NOT EXISTS (SELECT 1 FROM public.users WHERE username IS NULL) THEN - ALTER TABLE public.users ALTER COLUMN username SET NOT NULL; - END IF; - IF NOT EXISTS (SELECT 1 FROM public.follows WHERE follower_id IS NULL OR following_id IS NULL) THEN - ALTER TABLE public.follows ALTER COLUMN follower_id SET NOT NULL; - ALTER TABLE public.follows ALTER COLUMN following_id SET NOT NULL; - END IF; - IF NOT EXISTS (SELECT 1 FROM public.conversations WHERE type IS NULL) THEN - ALTER TABLE public.conversations ALTER COLUMN type SET NOT NULL; - END IF; - IF NOT EXISTS (SELECT 1 FROM public.conversation_participants WHERE conversation_id IS NULL OR user_id IS NULL) THEN - ALTER TABLE public.conversation_participants ALTER COLUMN conversation_id SET NOT NULL; - ALTER TABLE public.conversation_participants ALTER COLUMN user_id SET NOT NULL; - END IF; - IF NOT EXISTS (SELECT 1 FROM public.messages WHERE conversation_id IS NULL OR sender_id IS NULL) THEN - ALTER TABLE public.messages ALTER COLUMN conversation_id SET NOT NULL; - ALTER TABLE public.messages ALTER COLUMN sender_id SET NOT NULL; - END IF; - IF NOT EXISTS (SELECT 1 FROM public.stories WHERE user_id IS NULL) THEN - ALTER TABLE public.stories ALTER COLUMN user_id SET NOT NULL; - END IF; - IF NOT EXISTS (SELECT 1 FROM public.calls WHERE caller_id IS NULL OR receiver_id IS NULL OR type IS NULL) THEN - ALTER TABLE public.calls ALTER COLUMN caller_id SET NOT NULL; - ALTER TABLE public.calls ALTER COLUMN receiver_id SET NOT NULL; - ALTER TABLE public.calls ALTER COLUMN type SET NOT NULL; - END IF; - IF NOT EXISTS (SELECT 1 FROM public.chat_settings WHERE user_id IS NULL OR receiver_id IS NULL) THEN - ALTER TABLE public.chat_settings ALTER COLUMN user_id SET NOT NULL; - ALTER TABLE public.chat_settings ALTER COLUMN receiver_id SET NOT NULL; - END IF; - IF NOT EXISTS (SELECT 1 FROM public.notifications WHERE user_id IS NULL OR type IS NULL) THEN - ALTER TABLE public.notifications ALTER COLUMN user_id SET NOT NULL; - ALTER TABLE public.notifications ALTER COLUMN type SET NOT NULL; - END IF; -END $$; - --- 4. CONSTRAINTS --- Added only when absent; a duplicate row in an old table produces a NOTICE --- (never an abort) so the rest of the script still runs. -DO $$ -BEGIN - IF NOT EXISTS (SELECT 1 FROM pg_constraint - WHERE conname = 'username_length_check' - AND conrelid = 'public.users'::regclass) THEN - ALTER TABLE public.users ADD CONSTRAINT username_length_check CHECK (char_length(username) <= 15); - END IF; - IF NOT EXISTS (SELECT 1 FROM pg_constraint - WHERE conname = 'follows_unique_pair' - AND conrelid = 'public.follows'::regclass) THEN - ALTER TABLE public.follows ADD CONSTRAINT follows_unique_pair UNIQUE (follower_id, following_id); - END IF; - IF NOT EXISTS (SELECT 1 FROM pg_constraint - WHERE conname = 'conversation_participants_unique_pair' - AND conrelid = 'public.conversation_participants'::regclass) THEN - ALTER TABLE public.conversation_participants ADD CONSTRAINT conversation_participants_unique_pair UNIQUE (conversation_id, user_id); - END IF; - IF NOT EXISTS (SELECT 1 FROM pg_constraint - WHERE conname = 'chat_settings_unique_pair' - AND conrelid = 'public.chat_settings'::regclass) THEN - ALTER TABLE public.chat_settings ADD CONSTRAINT chat_settings_unique_pair UNIQUE (user_id, receiver_id); - END IF; -EXCEPTION WHEN OTHERS THEN - RAISE NOTICE 'Constraint skipped (%): existing rows violate it', SQLERRM; -END $$; - --- 5. ENABLE ROW LEVEL SECURITY (CORE PRIVACY) - -ALTER TABLE public.users ENABLE ROW LEVEL SECURITY; -ALTER TABLE public.follows ENABLE ROW LEVEL SECURITY; -ALTER TABLE public.conversations ENABLE ROW LEVEL SECURITY; -ALTER TABLE public.conversation_participants ENABLE ROW LEVEL SECURITY; -ALTER TABLE public.messages ENABLE ROW LEVEL SECURITY; -ALTER TABLE public.stories ENABLE ROW LEVEL SECURITY; -ALTER TABLE public.calls ENABLE ROW LEVEL SECURITY; -ALTER TABLE public.call_candidates ENABLE ROW LEVEL SECURITY; -ALTER TABLE public.chat_settings ENABLE ROW LEVEL SECURITY; -ALTER TABLE public.notifications ENABLE ROW LEVEL SECURITY; - --- 6. RLS POLICIES (re-created on every run, so edits apply) - --- profiles -DROP POLICY IF EXISTS "Allow public read access on profiles" ON public.users; -CREATE POLICY "Allow public read access on profiles" ON public.users FOR SELECT USING (true); -DROP POLICY IF EXISTS "Allow users to update own profile" ON public.users; -CREATE POLICY "Allow users to update own profile" ON public.users FOR UPDATE USING (auth.uid() = id) WITH CHECK (auth.uid() = id); -DROP POLICY IF EXISTS "Allow users to insert own profile" ON public.users; -CREATE POLICY "Allow users to insert own profile" ON public.users FOR INSERT WITH CHECK (auth.uid() = id); - --- connections -DROP POLICY IF EXISTS "Allow users to view all follows" ON public.follows; -CREATE POLICY "Allow users to view all follows" ON public.follows FOR SELECT USING (true); -DROP POLICY IF EXISTS "Allow users to follow others" ON public.follows; -CREATE POLICY "Allow users to follow others" ON public.follows FOR INSERT WITH CHECK (auth.uid() = follower_id); -DROP POLICY IF EXISTS "Allow users to unfollow others" ON public.follows; -CREATE POLICY "Allow users to unfollow others" ON public.follows FOR DELETE USING (auth.uid() = follower_id); - --- conversations -DROP POLICY IF EXISTS "Allow auth users to make conversations" ON public.conversations; -CREATE POLICY "Allow auth users to make conversations" ON public.conversations FOR INSERT WITH CHECK (auth.role() = 'authenticated'); -DROP POLICY IF EXISTS "Allow members to see conversations" ON public.conversations; -CREATE POLICY "Allow members to see conversations" ON public.conversations FOR SELECT USING ( - EXISTS ( - SELECT 1 FROM public.conversation_participants - WHERE conversation_participants.conversation_id = conversations.id - AND conversation_participants.user_id = auth.uid() - ) -); -DROP POLICY IF EXISTS "Allow participants to edit conversations" ON public.conversations; -CREATE POLICY "Allow participants to edit conversations" ON public.conversations FOR UPDATE USING ( - EXISTS ( - SELECT 1 FROM public.conversation_participants - WHERE conversation_participants.conversation_id = conversations.id - AND conversation_participants.user_id = auth.uid() - ) -); -DROP POLICY IF EXISTS "Allow participants to delete conversations" ON public.conversations; -CREATE POLICY "Allow participants to delete conversations" ON public.conversations FOR DELETE USING ( - EXISTS ( - SELECT 1 FROM public.conversation_participants - WHERE conversation_participants.conversation_id = conversations.id - AND conversation_participants.user_id = auth.uid() - ) -); - --- members -DROP POLICY IF EXISTS "Allow auth users to inspect participants" ON public.conversation_participants; -CREATE POLICY "Allow auth users to inspect participants" ON public.conversation_participants FOR SELECT USING (true); -DROP POLICY IF EXISTS "Allow members to join rooms" ON public.conversation_participants; -CREATE POLICY "Allow members to join rooms" ON public.conversation_participants FOR INSERT WITH CHECK (auth.role() = 'authenticated'); -DROP POLICY IF EXISTS "Allow participants to leave rooms" ON public.conversation_participants; -CREATE POLICY "Allow participants to leave rooms" ON public.conversation_participants FOR DELETE USING (auth.role() = 'authenticated'); - --- messages -DROP POLICY IF EXISTS "Allow conversation members to view messages" ON public.messages; -CREATE POLICY "Allow conversation members to view messages" ON public.messages FOR SELECT USING ( - EXISTS ( - SELECT 1 FROM public.conversation_participants - WHERE conversation_participants.conversation_id = messages.conversation_id - AND conversation_participants.user_id = auth.uid() - ) -); -DROP POLICY IF EXISTS "Allow active members to insert messages" ON public.messages; -CREATE POLICY "Allow active members to insert messages" ON public.messages FOR INSERT WITH CHECK ( - auth.uid() = sender_id - AND EXISTS ( - SELECT 1 FROM public.conversation_participants - WHERE conversation_participants.conversation_id = messages.conversation_id - AND conversation_participants.user_id = auth.uid() - ) -); -DROP POLICY IF EXISTS "Allow participants to update messages" ON public.messages; -CREATE POLICY "Allow participants to update messages" ON public.messages FOR UPDATE USING ( - EXISTS ( - SELECT 1 FROM public.conversation_participants - WHERE conversation_participants.conversation_id = messages.conversation_id - AND conversation_participants.user_id = auth.uid() - ) -); -DROP POLICY IF EXISTS "Allow participants to delete messages" ON public.messages; -CREATE POLICY "Allow participants to delete messages" ON public.messages FOR DELETE USING ( - EXISTS ( - SELECT 1 FROM public.conversation_participants - WHERE conversation_participants.conversation_id = messages.conversation_id - AND conversation_participants.user_id = auth.uid() - ) -); - --- stories -DROP POLICY IF EXISTS "Allow auth users to view stories" ON public.stories; -CREATE POLICY "Allow auth users to view stories" ON public.stories FOR SELECT USING (auth.role() = 'authenticated'); -DROP POLICY IF EXISTS "Allow owners to publish stories" ON public.stories; -CREATE POLICY "Allow owners to publish stories" ON public.stories FOR INSERT WITH CHECK (auth.uid() = user_id); -DROP POLICY IF EXISTS "Allow owners to delete stories" ON public.stories; -CREATE POLICY "Allow owners to delete stories" ON public.stories FOR DELETE USING (auth.uid() = user_id); - --- calling -DROP POLICY IF EXISTS "Allow view access to call records" ON public.calls; -CREATE POLICY "Allow view access to call records" ON public.calls FOR SELECT USING (auth.uid() = caller_id OR auth.uid() = receiver_id); -DROP POLICY IF EXISTS "Allow calls insertion to caller" ON public.calls; -CREATE POLICY "Allow calls insertion to caller" ON public.calls FOR INSERT WITH CHECK (auth.uid() = caller_id); -DROP POLICY IF EXISTS "Allow call updates on participants" ON public.calls; -CREATE POLICY "Allow call updates on participants" ON public.calls FOR UPDATE USING (auth.uid() = caller_id OR auth.uid() = receiver_id); - --- signaling Candidates -DROP POLICY IF EXISTS "Allow select on candidates to call members" ON public.call_candidates; -CREATE POLICY "Allow select on candidates to call members" ON public.call_candidates FOR SELECT USING ( - EXISTS ( - SELECT 1 FROM public.calls - WHERE calls.id = call_candidates.call_id - AND (calls.caller_id = auth.uid() OR calls.receiver_id = auth.uid()) - ) -); -DROP POLICY IF EXISTS "Allow call participants to insert candidates" ON public.call_candidates; -CREATE POLICY "Allow call participants to insert candidates" ON public.call_candidates FOR INSERT WITH CHECK ( - auth.uid() = user_id - AND EXISTS ( - SELECT 1 FROM public.calls - WHERE calls.id = call_candidates.call_id - AND (calls.caller_id = auth.uid() OR calls.receiver_id = auth.uid()) - ) -); - --- custom chat settings -DROP POLICY IF EXISTS "Allow users to read own chat settings" ON public.chat_settings; -CREATE POLICY "Allow users to read own chat settings" ON public.chat_settings FOR SELECT USING (auth.uid() = user_id); -DROP POLICY IF EXISTS "Allow users to modify own chat settings" ON public.chat_settings; -CREATE POLICY "Allow users to modify own chat settings" ON public.chat_settings FOR ALL USING (auth.uid() = user_id); - --- user notifications -DROP POLICY IF EXISTS "Allow users to read own notifications" ON public.notifications; -CREATE POLICY "Allow users to read own notifications" ON public.notifications FOR SELECT USING (auth.uid() = user_id); -DROP POLICY IF EXISTS "Allow auth users system to insert notifications" ON public.notifications; -CREATE POLICY "Allow auth users system to insert notifications" ON public.notifications FOR INSERT WITH CHECK (auth.role() = 'authenticated'); -DROP POLICY IF EXISTS "Allow users to update own notifications" ON public.notifications; -CREATE POLICY "Allow users to update own notifications" ON public.notifications FOR UPDATE USING (auth.uid() = user_id); -DROP POLICY IF EXISTS "Allow users to delete own notifications" ON public.notifications; -CREATE POLICY "Allow users to delete own notifications" ON public.notifications FOR DELETE USING (auth.uid() = user_id); - --- 7. PERFORMANCE AND SEARCH INDEXES -CREATE INDEX IF NOT EXISTS idx_messages_conversation ON public.messages(conversation_id); -CREATE INDEX IF NOT EXISTS idx_messages_created_at ON public.messages(created_at DESC); -CREATE INDEX IF NOT EXISTS idx_participants_user ON public.conversation_participants(user_id); -CREATE INDEX IF NOT EXISTS idx_participants_conversation ON public.conversation_participants(conversation_id); -CREATE INDEX IF NOT EXISTS idx_users_username_lowered ON public.users(LOWER(username)); -CREATE INDEX IF NOT EXISTS idx_follows_follower ON public.follows(follower_id); -CREATE INDEX IF NOT EXISTS idx_follows_following ON public.follows(following_id); -CREATE INDEX IF NOT EXISTS idx_stories_user ON public.stories(user_id); -CREATE INDEX IF NOT EXISTS idx_calls_participants ON public.calls(caller_id, receiver_id); -CREATE INDEX IF NOT EXISTS idx_chat_settings_user ON public.chat_settings(user_id); -CREATE INDEX IF NOT EXISTS idx_notifications_user ON public.notifications(user_id); - --- Notification sound configuration -NOTIFY pgrst, 'reload schema'; - - --- ══════════════════════════════════════════════════════════════════════════ --- PART 2/9 — sql/02_posts_and_interactions_schema.sql --- (generated from the file of that name; edit THAT file, then re-run --- "npm run sql:bundle" — do not edit this bundle by hand) --- ══════════════════════════════════════════════════════════════════════════ - --- ========================================================================= --- STEP 2/9: POSTS, LIKES AND COMMENTS --- ========================================================================= --- Run in the Supabase SQL Editor after 01_core_schema.sql. --- Safe to re-run: nothing is dropped, missing tables/columns/policies are --- created, existing rows are untouched. --- ========================================================================= - --- 1. Create Posts Table -CREATE TABLE IF NOT EXISTS public.posts ( - id UUID DEFAULT gen_random_uuid() PRIMARY KEY, - user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - image_url TEXT NOT NULL, - caption TEXT, - created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL -); - --- Enable RLS for public.posts -ALTER TABLE public.posts ENABLE ROW LEVEL SECURITY; - --- Post Policies -DROP POLICY IF EXISTS "Allow public read access for posts" ON public.posts; -CREATE POLICY "Allow public read access for posts" ON public.posts FOR SELECT -USING (true); - -DROP POLICY IF EXISTS "Allow authenticated insert for posts" ON public.posts; -CREATE POLICY "Allow authenticated insert for posts" ON public.posts FOR INSERT -WITH CHECK (auth.uid() = user_id); - -DROP POLICY IF EXISTS "Allow users to delete their own posts" ON public.posts; -CREATE POLICY "Allow users to delete their own posts" ON public.posts FOR DELETE -USING (auth.uid() = user_id); - - --- 2. Create Post Likes Table (Tracking active likes) -CREATE TABLE IF NOT EXISTS public.post_likes ( - post_id UUID REFERENCES public.posts(id) ON DELETE CASCADE, - user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL, - PRIMARY KEY (post_id, user_id) -); - --- Enable RLS for public.post_likes -ALTER TABLE public.post_likes ENABLE ROW LEVEL SECURITY; - --- Post Likes Policies -DROP POLICY IF EXISTS "Allow public read access for post likes" ON public.post_likes; -CREATE POLICY "Allow public read access for post likes" ON public.post_likes FOR SELECT -USING (true); - -DROP POLICY IF EXISTS "Allow authenticated insert for post likes" ON public.post_likes; -CREATE POLICY "Allow authenticated insert for post likes" ON public.post_likes FOR INSERT -WITH CHECK (auth.uid() = user_id); - -DROP POLICY IF EXISTS "Allow users to remove their likes" ON public.post_likes; -CREATE POLICY "Allow users to remove their likes" ON public.post_likes FOR DELETE -USING (auth.uid() = user_id); - - --- 3. Create Post Comments Table -CREATE TABLE IF NOT EXISTS public.post_comments ( - id UUID DEFAULT gen_random_uuid() PRIMARY KEY, - post_id UUID REFERENCES public.posts(id) ON DELETE CASCADE, - user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - text TEXT NOT NULL, - created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL -); - --- Enable RLS for public.post_comments -ALTER TABLE public.post_comments ENABLE ROW LEVEL SECURITY; - --- Post Comments Policies -DROP POLICY IF EXISTS "Allow public read access for post comments" ON public.post_comments; -CREATE POLICY "Allow public read access for post comments" ON public.post_comments FOR SELECT -USING (true); - -DROP POLICY IF EXISTS "Allow authenticated insert for post comments" ON public.post_comments; -CREATE POLICY "Allow authenticated insert for post comments" ON public.post_comments FOR INSERT -WITH CHECK (auth.uid() = user_id); - -DROP POLICY IF EXISTS "Allow users to delete their own comments" ON public.post_comments; -CREATE POLICY "Allow users to delete their own comments" ON public.post_comments FOR DELETE -USING (auth.uid() = user_id); - --- Performance Indexes -CREATE INDEX IF NOT EXISTS idx_posts_user_id ON public.posts(user_id); -CREATE INDEX IF NOT EXISTS idx_post_likes_post_id ON public.post_likes(post_id); -CREATE INDEX IF NOT EXISTS idx_post_comments_post_id ON public.post_comments(post_id); - --- Column upgrades: a project created from an older version of this file may be --- missing columns added later. No existing row is touched. -ALTER TABLE public.posts - ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS image_url TEXT, - ADD COLUMN IF NOT EXISTS caption TEXT, - ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()); - -ALTER TABLE public.post_likes - ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()); - -ALTER TABLE public.post_comments - ADD COLUMN IF NOT EXISTS post_id UUID REFERENCES public.posts(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE CASCADE, - ADD COLUMN IF NOT EXISTS text TEXT, - ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()); - --- Primary key of post_likes is (post_id, user_id); add it only if it is absent. -DO $$ -BEGIN - IF NOT EXISTS (SELECT 1 FROM pg_constraint - WHERE conname = 'post_likes_pkey' - AND conrelid = 'public.post_likes'::regclass) THEN - ALTER TABLE public.post_likes ADD CONSTRAINT post_likes_pkey PRIMARY KEY (post_id, user_id); - END IF; -EXCEPTION WHEN OTHERS THEN - RAISE NOTICE 'post_likes primary key skipped: %', SQLERRM; -END $$; - --- Reload Schema -NOTIFY pgrst, 'reload schema'; - - --- ══════════════════════════════════════════════════════════════════════════ --- PART 3/9 — sql/03_support_tickets_schema.sql --- (generated from the file of that name; edit THAT file, then re-run --- "npm run sql:bundle" — do not edit this bundle by hand) --- ══════════════════════════════════════════════════════════════════════════ - --- ========================================================================= --- STEP 3/9: SUPPORT TICKETS --- ========================================================================= --- Run in the Supabase SQL Editor after 02_posts_and_interactions_schema.sql. --- Safe to re-run: nothing is dropped, existing tickets are kept. --- ========================================================================= - --- Create support tickets Table -CREATE TABLE IF NOT EXISTS public.support_tickets ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - user_id UUID REFERENCES public.users(id) ON DELETE SET NULL, - email TEXT NOT NULL, - category TEXT NOT NULL, - subject TEXT NOT NULL, - message TEXT NOT NULL, - status TEXT DEFAULT 'open' CHECK (status IN ('open', 'in_progress', 'resolved')), - created_at TIMESTAMPTZ DEFAULT NOW(), - updated_at TIMESTAMPTZ DEFAULT NOW() -); - --- Column upgrades for older installs (no existing row is touched). -ALTER TABLE public.support_tickets - ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES public.users(id) ON DELETE SET NULL, - ADD COLUMN IF NOT EXISTS email TEXT, - ADD COLUMN IF NOT EXISTS category TEXT, - ADD COLUMN IF NOT EXISTS subject TEXT, - ADD COLUMN IF NOT EXISTS message TEXT, - ADD COLUMN IF NOT EXISTS status TEXT DEFAULT 'open', - ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT NOW(), - ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT NOW(); - --- Enable Row Level Security (RLS) -ALTER TABLE public.support_tickets ENABLE ROW LEVEL SECURITY; - --- 1. Anonymous and Authenticated submittals -DROP POLICY IF EXISTS "Allow anonymous and authenticated ticket insertion" ON public.support_tickets; -CREATE POLICY "Allow anonymous and authenticated ticket insertion" ON public.support_tickets - FOR INSERT - WITH CHECK (true); - --- 2. Fetch logged tickets -DROP POLICY IF EXISTS "Allow users to view own tickets" ON public.support_tickets; -CREATE POLICY "Allow users to view own tickets" ON public.support_tickets - FOR SELECT - USING (auth.uid() = user_id); - --- Performance Indexing -CREATE INDEX IF NOT EXISTS idx_support_tickets_user_id ON public.support_tickets(user_id); - --- Reload Schema Cache -NOTIFY pgrst, 'reload schema'; - - --- ══════════════════════════════════════════════════════════════════════════ --- PART 4/9 — sql/04_triggers_functions_and_rpc.sql --- (generated from the file of that name; edit THAT file, then re-run --- "npm run sql:bundle" — do not edit this bundle by hand) --- ══════════════════════════════════════════════════════════════════════════ - --- ========================================================================= --- STEP 4/9: RPC FUNCTIONS, TRIGGERS & AUTH -> PROFILE AUTO-SYNC --- ========================================================================= --- Run in the Supabase SQL Editor after 03_support_tickets_schema.sql. --- Safe to re-run: the trigger and the functions are dropped and re-created, so --- an updated definition always replaces the old one. No row is ever deleted. --- (`DROP FUNCTION` cannot lose the trigger's target: the trigger is dropped --- first, in the same run.) --- ========================================================================= - --- Clear existing Triggers & Functions -DROP TRIGGER IF EXISTS on_auth_user_created ON auth.users; -DROP FUNCTION IF EXISTS public.handle_new_auth_user(); -DROP FUNCTION IF EXISTS public.get_direct_conversation_id(UUID, UUID); - --- 1. Direct Conversation Match RPC (Guarantees Instant Room Lookups) -CREATE OR REPLACE FUNCTION public.get_direct_conversation_id(u1 UUID, u2 UUID) -RETURNS UUID AS $$ -DECLARE - conv_id UUID; -BEGIN - SELECT cp1.conversation_id INTO conv_id - FROM public.conversation_participants cp1 - JOIN public.conversation_participants cp2 - ON cp1.conversation_id = cp2.conversation_id - JOIN public.conversations c - ON cp1.conversation_id = c.id - WHERE cp1.user_id = u1 - AND cp2.user_id = u2 - AND c.type = 'direct' - LIMIT 1; - - RETURN conv_id; -END; -$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public; - - --- 2. Auth to Public user profiles sync (Essential for Signup and OAuth sign-in) -CREATE OR REPLACE FUNCTION public.handle_new_auth_user() -RETURNS TRIGGER AS $$ -DECLARE - username_val TEXT; - full_name_val TEXT; -BEGIN - -- Extract values safely from raw_user_meta_data or default to email split-part - username_val := COALESCE( - new.raw_user_meta_data->>'username', - split_part(new.email, '@', 1) - ); - full_name_val := COALESCE( - new.raw_user_meta_data->>'full_name', - split_part(new.email, '@', 1) - ); - - -- Clean the username values to be under 15 characters - username_val := SUBSTRING(username_val, 1, 15); - - -- Ensure uniqueness of username, append unique IDs if a duplicate is found - IF EXISTS (SELECT 1 FROM public.users WHERE username = username_val) THEN - username_val := SUBSTRING(username_val, 1, 9) || '_' || substring(new.id::text, 1, 5); - END IF; - - -- Insert profile safely - INSERT INTO public.users ( - id, - email, - phone, - full_name, - username, - photo_url, - bio - ) - VALUES ( - new.id, - new.email, - COALESCE(new.raw_user_meta_data->>'phone', ''), - full_name_val, - LOWER(username_val), - COALESCE(new.raw_user_meta_data->>'avatar_url', 'https://cdn-icons-png.flaticon.com/512/149/149071.png'), - 'Available' - ) - ON CONFLICT (id) DO UPDATE SET - email = EXCLUDED.email, - phone = COALESCE(public.users.phone, EXCLUDED.phone), - full_name = COALESCE(public.users.full_name, EXCLUDED.full_name), - username = COALESCE(public.users.username, EXCLUDED.username); - - RETURN NEW; -END; -$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public; - --- Bind trigger on auth.users (Runs completely on auth signup) -CREATE TRIGGER on_auth_user_created - AFTER INSERT ON auth.users - FOR EACH ROW EXECUTE FUNCTION public.handle_new_auth_user(); - --- Clear Schema cache -NOTIFY pgrst, 'reload schema'; - - --- ══════════════════════════════════════════════════════════════════════════ --- PART 5/9 — sql/05_advanced_optimizations_and_realtime.sql --- (generated from the file of that name; edit THAT file, then re-run --- "npm run sql:bundle" — do not edit this bundle by hand) --- ══════════════════════════════════════════════════════════════════════════ - --- ========================================================================= --- STEP 5/9: REALTIME PUBLICATION, PREVIEW TRIGGERS, HISTORY CAP --- ========================================================================= --- Run in the Supabase SQL Editor after 04_triggers_functions_and_rpc.sql. --- Safe to re-run: functions are CREATE OR REPLACE, triggers are dropped first, --- replica identity and publication membership are re-asserted. --- --- ⚠️ READ THIS BEFORE RUNNING — sections 1 and 6 DELETE MESSAGE HISTORY: --- every chat is capped at 60 rows, pruned back to the newest 40, on every --- insert. It keeps a free-tier project small, but it also means chat history --- is not kept. To keep history instead: do NOT run sections 1 and 6, and use --- the time-based pruner in 09_egress_optimizations.sql (`prune_old_messages`). --- ========================================================================= - --- 1. MESSAGE CAP PRUNER (LIMITS ROOMS TO LAST 60 MESSAGES - PRUNES TO 40) -CREATE OR REPLACE FUNCTION prune_past_messages() -RETURNS TRIGGER AS $$ -DECLARE - msg_count INT; -BEGIN - SELECT COUNT(*) INTO msg_count - FROM public.messages - WHERE conversation_id = NEW.conversation_id; - - IF msg_count >= 60 THEN - DELETE FROM public.messages - WHERE conversation_id = NEW.conversation_id - AND id NOT IN ( - SELECT subquery.id FROM ( - SELECT id FROM public.messages - WHERE conversation_id = NEW.conversation_id - ORDER BY created_at DESC, id DESC - LIMIT 40 - ) subquery - ); - END IF; - - RETURN NEW; -END; -$$ LANGUAGE plpgsql SECURITY DEFINER; - -DROP TRIGGER IF EXISTS trg_prune_past_messages ON public.messages; -CREATE TRIGGER trg_prune_past_messages -AFTER INSERT ON public.messages -FOR EACH ROW -EXECUTE FUNCTION prune_past_messages(); - - --- 2. AUTOMATICALLY SYNC NEW MESSAGES WITH CONVERSATIONS PREVIEWS -CREATE OR REPLACE FUNCTION update_conversation_timestamp_and_last_message() -RETURNS TRIGGER AS $$ -BEGIN - UPDATE public.conversations - SET - updated_at = NEW.created_at, - last_message = COALESCE(NEW.text, CASE WHEN NEW.media_type IS NOT NULL THEN 'Sent a ' || NEW.media_type ELSE 'Sent an attachment' END), - last_message_at = NEW.created_at - WHERE id = NEW.conversation_id; - RETURN NEW; -END; -$$ LANGUAGE plpgsql SECURITY DEFINER; - -DROP TRIGGER IF EXISTS trg_update_conversation_on_message ON public.messages; -CREATE TRIGGER trg_update_conversation_on_message -AFTER INSERT ON public.messages -FOR EACH ROW -EXECUTE FUNCTION update_conversation_timestamp_and_last_message(); - - --- 3. INTERACTIVE CALLS RECUPERATOR PRUNER (LIMITS CHRONO CALLS TO LAST 60) -CREATE OR REPLACE FUNCTION prune_past_calls() -RETURNS TRIGGER AS $$ -DECLARE - caller_call_count INT; - receiver_call_count INT; -BEGIN - SELECT COUNT(*) INTO caller_call_count - FROM public.calls - WHERE caller_id = NEW.caller_id OR receiver_id = NEW.caller_id; - - IF caller_call_count >= 60 THEN - DELETE FROM public.calls - WHERE (caller_id = NEW.caller_id OR receiver_id = NEW.caller_id) - AND id NOT IN ( - SELECT subquery.id FROM ( - SELECT id FROM public.calls - WHERE caller_id = NEW.caller_id OR receiver_id = NEW.caller_id - ORDER BY created_at DESC, id DESC - LIMIT 40 - ) subquery - ); - END IF; - - IF NEW.receiver_id IS NOT NULL AND NEW.receiver_id <> NEW.caller_id THEN - SELECT COUNT(*) INTO receiver_call_count - FROM public.calls - WHERE caller_id = NEW.receiver_id OR receiver_id = NEW.receiver_id; - - IF receiver_call_count >= 60 THEN - DELETE FROM public.calls - WHERE (caller_id = NEW.receiver_id OR receiver_id = NEW.receiver_id) - AND id NOT IN ( - SELECT subquery.id FROM ( - SELECT id FROM public.calls - WHERE caller_id = NEW.receiver_id OR receiver_id = NEW.receiver_id - ORDER BY created_at DESC, id DESC - LIMIT 40 - ) subquery - ); - END IF; - END IF; - - RETURN NEW; -END; -$$ LANGUAGE plpgsql SECURITY DEFINER; - -DROP TRIGGER IF EXISTS trg_prune_past_calls ON public.calls; -CREATE TRIGGER trg_prune_past_calls -AFTER INSERT ON public.calls -FOR EACH ROW -EXECUTE FUNCTION prune_past_calls(); - - --- 4. REPLICA IDENTITY --- --------------------------------------------------------------------------- --- FULL is only needed where the client filters DELETEs by a non-key column --- (`conversation_id=eq.…` on messages and conversation_participants). Everywhere --- else DEFAULT keeps UPDATE payloads to "new row + primary key", which stops --- whole rows — including `users.lock`, the app-lock passcode hash, and --- `fcm_tokens` — from being broadcast to every subscribed client. --- 09_egress_optimizations.sql re-asserts the same values, so either file leaves --- the database in this state. --- --------------------------------------------------------------------------- -DO $$ -DECLARE - target RECORD; -BEGIN - FOR target IN - SELECT * FROM (VALUES - ('users', 'DEFAULT'), - ('conversations', 'DEFAULT'), - ('calls', 'DEFAULT'), - ('call_candidates', 'DEFAULT'), - ('messages', 'FULL'), - ('conversation_participants','FULL') - ) AS t(tbl, identity) - LOOP - IF EXISTS (SELECT 1 FROM pg_class c - JOIN pg_namespace n ON n.oid = c.relnamespace - WHERE n.nspname = 'public' AND c.relname = target.tbl) THEN - EXECUTE format('ALTER TABLE public.%I REPLICA IDENTITY %s', target.tbl, target.identity); - END IF; - END LOOP; -END; -$$; - - --- 5. SUPABASE REALTIME PUBLICATION MEMBERSHIP --- --------------------------------------------------------------------------- --- Only the tables the client actually subscribes to. Membership is idempotent: --- a table is added only when it exists and is not already published, so a run --- over an existing project changes nothing and a fork that dropped a table --- (e.g. call_candidates) does not abort the script. --- --------------------------------------------------------------------------- -DO $$ -DECLARE - tbl TEXT; -BEGIN - IF NOT EXISTS (SELECT 1 FROM pg_publication WHERE pubname = 'supabase_realtime') THEN - CREATE PUBLICATION supabase_realtime; - END IF; - - FOREACH tbl IN ARRAY ARRAY[ - 'messages', 'conversations', 'users', 'calls', - 'call_candidates', 'conversation_participants' - ] LOOP - IF to_regclass('public.' || tbl) IS NOT NULL - AND NOT EXISTS (SELECT 1 FROM pg_publication_tables - WHERE pubname = 'supabase_realtime' - AND schemaname = 'public' - AND tablename = tbl) THEN - EXECUTE format('ALTER PUBLICATION supabase_realtime ADD TABLE public.%I', tbl); - END IF; - END LOOP; -END; -$$; - --- Also enable Realtime in the dashboard for these tables: --- Database -> Replication -> supabase_realtime --- The SQL above registers the tables; the dashboard toggle is what actually --- streams them. - - --- 6. RETROACTIVE SWEEP (trims pre-existing high-volume tables down to 40 rows) --- Same policy as section 1: it keeps the newest 40 messages per chat and the --- newest 40 calls per user. Skip this section if you skipped section 1. -DO $$ -DECLARE - u_rec RECORD; - conv_rec RECORD; -BEGIN - -- Prune existing calls back to newest 40 for every user - FOR u_rec IN (SELECT DISTINCT id FROM public.users) LOOP - DELETE FROM public.calls - WHERE (caller_id = u_rec.id OR receiver_id = u_rec.id) - AND id NOT IN ( - SELECT subquery.id FROM ( - SELECT id FROM public.calls - WHERE caller_id = u_rec.id OR receiver_id = u_rec.id - ORDER BY created_at DESC, id DESC - LIMIT 40 - ) subquery - ); - END LOOP; - - -- Prune existing messages back to newest 40 for every conversation room - FOR conv_rec IN (SELECT DISTINCT id FROM public.conversations) LOOP - DELETE FROM public.messages - WHERE conversation_id = conv_rec.id - AND id NOT IN ( - SELECT subquery.id FROM ( - SELECT id FROM public.messages - WHERE conversation_id = conv_rec.id - ORDER BY created_at DESC, id DESC - LIMIT 40 - ) subquery - ); - END LOOP; -END; -$$; - --- Reload Schema and notify PostgREST -NOTIFY pgrst, 'reload schema'; - - --- ══════════════════════════════════════════════════════════════════════════ --- PART 6/9 — sql/06_storage_configurations.sql --- (generated from the file of that name; edit THAT file, then re-run --- "npm run sql:bundle" — do not edit this bundle by hand) --- ══════════════════════════════════════════════════════════════════════════ - --- ========================================================================= --- STEP 6/9: STORAGE BUCKETS (chat-media, profiles) AND THEIR POLICIES --- ========================================================================= --- Run in the Supabase SQL Editor after 05_advanced_optimizations_and_realtime.sql. --- Safe to re-run: buckets are inserted with ON CONFLICT DO NOTHING and every --- policy is dropped and re-created, so an updated definition always wins. --- --- ⚠️ These policies are deliberately permissive (public read, any authenticated --- user may upload/update/delete in these buckets) because the app uploads to --- `chat-media/images/_.` — paths carry no user id, so --- ownership cannot be checked from the path. Hardening notes: --- docs/EGRESS_AUDIT.md §6 and the commented block in 09_egress_optimizations.sql. --- ========================================================================= - --- 1. PROVISION BUCKETS (If they do not already exist) -INSERT INTO storage.buckets (id, name, public, file_size_limit, allowed_mime_types) -VALUES - ('chat-media', 'chat-media', true, 52428800, NULL), -- 50 MB limit - ('profiles', 'profiles', true, 5242880, ARRAY['image/jpeg', 'image/png', 'image/gif', 'image/webp']) -- 5 MB limit -ON CONFLICT (id) DO NOTHING; - - --- 2. RE-ENABLE AND RESET STRATEGIC POLICIES FOR STORAGE OBJECTS --- Clean up any conflicting pre-existing policies for these buckets -DROP POLICY IF EXISTS "Public Access to chat-media" ON storage.objects; -DROP POLICY IF EXISTS "Authenticated Users can upload to chat-media" ON storage.objects; -DROP POLICY IF EXISTS "Owners can update their own chat-media objects" ON storage.objects; -DROP POLICY IF EXISTS "Owners can delete their own chat-media objects" ON storage.objects; - -DROP POLICY IF EXISTS "Public Access to profiles" ON storage.objects; -DROP POLICY IF EXISTS "Authenticated Users can upload to profiles" ON storage.objects; -DROP POLICY IF EXISTS "Owners can update their own profiles" ON storage.objects; -DROP POLICY IF EXISTS "Owners can delete their own profiles" ON storage.objects; - - --- 3. APPLY SECURITY POLICIES FOR 'chat-media' BUCKET - --- Read Policy: Anyone can read media (Publicly accessible) -CREATE POLICY "Public Access to chat-media" -ON storage.objects FOR SELECT -TO public -USING (bucket_id = 'chat-media'); - --- Write Policy: Authenticated users can insert files -CREATE POLICY "Authenticated Users can upload to chat-media" -ON storage.objects FOR INSERT -TO authenticated -WITH CHECK (bucket_id = 'chat-media' AND (auth.uid()::text = (storage.foldername(name))[1] OR true)); - --- Update Policy: Authenticated owners can update files -CREATE POLICY "Owners can update their own chat-media objects" -ON storage.objects FOR UPDATE -TO authenticated -USING (bucket_id = 'chat-media') -WITH CHECK (bucket_id = 'chat-media'); - --- Delete Policy: Authenticated users can delete files they own -CREATE POLICY "Owners can delete their own chat-media objects" -ON storage.objects FOR DELETE -TO authenticated -USING (bucket_id = 'chat-media'); - - --- 4. APPLY SECURITY POLICIES FOR 'profiles' BUCKET - --- Read Policy: Anyone can read profiles photos (Publicly accessible) -CREATE POLICY "Public Access to profiles" -ON storage.objects FOR SELECT -TO public -USING (bucket_id = 'profiles'); - --- Write Policy: Authenticated users can upload profile icons -CREATE POLICY "Authenticated Users can upload to profiles" -ON storage.objects FOR INSERT -TO authenticated -WITH CHECK (bucket_id = 'profiles'); - --- Update Policy: Authenticated users can replace profile icons -CREATE POLICY "Owners can update their own profiles" -ON storage.objects FOR UPDATE -TO authenticated -USING (bucket_id = 'profiles') -WITH CHECK (bucket_id = 'profiles'); - --- Delete Policy: Authenticated users can delete profile icons -CREATE POLICY "Owners can delete their own profiles" -ON storage.objects FOR DELETE -TO authenticated -USING (bucket_id = 'profiles'); - - --- 5. RELOAD POSTGRES SCHEMA CACHE -NOTIFY pgrst, 'reload schema'; - - --- ══════════════════════════════════════════════════════════════════════════ --- PART 7/9 — sql/07_chat_time_scheduling_migration.sql --- (generated from the file of that name; edit THAT file, then re-run --- "npm run sql:bundle" — do not edit this bundle by hand) --- ══════════════════════════════════════════════════════════════════════════ - --- Incremental Migration for Chat Time Scheduling --- Purpose: Add support for custom chat times, allowing users of direct chats to set allowed days/times. --- Integrates directly inside public.conversations table under watch_state JSONB field, with defensive fallback. - -ALTER TABLE public.conversations ADD COLUMN IF NOT EXISTS chat_time_restrictions JSONB DEFAULT NULL; - --- Keep Row Level Security enabled for access constraints --- Triggers a reload of PostgREST schema cache to make column visible -NOTIFY pgrst, 'reload schema'; - - --- ══════════════════════════════════════════════════════════════════════════ --- PART 8/9 — sql/08_stories_expiration_and_views.sql --- (generated from the file of that name; edit THAT file, then re-run --- "npm run sql:bundle" — do not edit this bundle by hand) --- ══════════════════════════════════════════════════════════════════════════ - --- Incremental Migration for Stories Expiration (24h) and Views tracking --- Purpose: Adds views column to stories table, adds view_story RPC, and adds cleanup_expired_stories RPC. - --- 1. Add views JSONb column to stories table -ALTER TABLE public.stories ADD COLUMN IF NOT EXISTS views JSONB DEFAULT '[]'::JSONB NOT NULL; - --- 2. Create RPC to register a view securely without exposing direct update permissions --- This is written in the simplest possible form to avoid any PL/pgSQL parsing issues. -CREATE OR REPLACE FUNCTION public.view_story( - story_id_param UUID, - viewer_id_param UUID, - viewer_username_param TEXT, - viewer_fullname_param TEXT, - viewer_photo_url_param TEXT -) -RETURNS VOID AS $$ -BEGIN - UPDATE public.stories - SET views = COALESCE(views, '[]'::JSONB) || jsonb_build_array( - jsonb_build_object( - 'id', viewer_id_param, - 'username', viewer_username_param, - 'full_name', viewer_fullname_param, - 'photo_url', viewer_photo_url_param, - 'viewed_at', NOW() - ) - ) - WHERE id = story_id_param - AND NOT (COALESCE(views, '[]'::JSONB) @> jsonb_build_array(jsonb_build_object('id', viewer_id_param::text))); -END; -$$ LANGUAGE plpgsql SECURITY DEFINER; - --- 3. Create RPC to clean up stories older than 24 hours -CREATE OR REPLACE FUNCTION public.cleanup_expired_stories() -RETURNS VOID AS $$ -BEGIN - DELETE FROM public.stories WHERE created_at < NOW() - INTERVAL '24 hours'; -END; -$$ LANGUAGE plpgsql SECURITY DEFINER; - --- Trigger schema reload -NOTIFY pgrst, 'reload schema'; - - --- ══════════════════════════════════════════════════════════════════════════ --- PART 9/9 — sql/09_egress_optimizations.sql --- (generated from the file of that name; edit THAT file, then re-run --- "npm run sql:bundle" — do not edit this bundle by hand) --- ══════════════════════════════════════════════════════════════════════════ - --- ═══════════════════════════════════════════════════════════════════════════ --- 09 — Egress optimizations --- --- Apply this in the Supabase SQL editor: Database → SQL Editor → New query. --- It is idempotent, so running it twice is safe. --- --- Why: the app consumed 5 GB of egress in under a month with 2–3 active users. --- The client-side cause (a full conversation-list refetch per realtime event) --- is fixed in code — see docs/EGRESS_AUDIT.md. This file fixes the database --- half, which cannot be changed from the repository: --- --- 1. `last_read_at` — read receipts become ONE row update instead of one per --- unread message (each of which was broadcast to every client). --- 2. Denormalized `last_message*` maintained by trigger, so the chat list --- never has to fetch message rows just to draw a one-line preview. --- 3. REPLICA IDENTITY: stop broadcasting whole rows (including the passcode --- hash and FCM tokens in `users`) on every UPDATE. --- 4. Indexes for the hot paths. --- 5. Optional retention pruner for old messages. --- ═══════════════════════════════════════════════════════════════════════════ - - --- ── 1. Read marker ───────────────────────────────────────────────────────── --- Unread is a comparison: conversations.last_message_at > my last_read_at. --- One UPDATE per "I opened/read this chat" instead of one row per message. - --- Existing rows are stamped with the moment this runs, so history starts --- "read" and nobody gets a fake 400-message unread badge. -ALTER TABLE public.conversation_participants - ADD COLUMN IF NOT EXISTS last_read_at TIMESTAMPTZ DEFAULT NOW(); - --- The client updates ITS OWN row to say "I have read up to here". Without this --- policy the UPDATE matches no policy, affects 0 rows, and returns no error — --- the read marker would silently never move. (RLS is on for this table, and --- 01_core_schema.sql only defined SELECT/INSERT/DELETE.) -DROP POLICY IF EXISTS "Participants can update their own membership" ON public.conversation_participants; -CREATE POLICY "Participants can update their own membership" - ON public.conversation_participants - FOR UPDATE - USING (user_id = auth.uid()) - WITH CHECK (user_id = auth.uid()); - -CREATE INDEX IF NOT EXISTS idx_participants_user_last_read - ON public.conversation_participants(user_id, last_read_at DESC); - --- Realtime: the client subscribes with `user_id=eq.` and must also receive --- DELETEs (a participant removed from a group). DEFAULT identity only carries --- the primary key in the `old` record, so the server cannot evaluate the filter --- for deletes. These rows are tiny and rarely written, so FULL is cheap here. -ALTER TABLE public.conversation_participants REPLICA IDENTITY FULL; - - --- ── 2. `last_message*` is maintained by the database ─────────────────────── --- The chat list shows `last_message` / `last_message_at` / (for ticks) the --- sender. Writers already set the first two; the trigger also covers edits, --- deletes and direct SQL inserts, so the client never needs to re-read the --- newest messages for every conversation. - -ALTER TABLE public.conversations - ADD COLUMN IF NOT EXISTS last_message_sender_id UUID; - -CREATE OR REPLACE FUNCTION public.sync_conversation_last_message() -RETURNS TRIGGER -LANGUAGE plpgsql -SECURITY DEFINER -SET search_path = public -AS $$ -DECLARE - target_conversation UUID; - newest RECORD; -BEGIN - target_conversation := COALESCE(NEW.conversation_id, OLD.conversation_id); - IF target_conversation IS NULL THEN - RETURN NULL; - END IF; - - -- Fast path: a new (or edited) message that is not older than what the - -- conversation already shows IS the newest one, so write it across without - -- looking at the table. Appends are the hot path: no extra index scan. - IF TG_OP <> 'DELETE' AND NEW.is_deleted = false THEN - UPDATE public.conversations - SET last_message = COALESCE(NEW.text, - 'Sent a ' || COALESCE(NEW.media_type, 'file')), - last_message_at = NEW.created_at, - last_message_sender_id = NEW.sender_id - WHERE id = target_conversation - AND (last_message_at IS NULL OR NEW.created_at >= last_message_at); - IF FOUND THEN - RETURN NULL; - END IF; - END IF; - - -- Fast skip for DELETEs: if the conversation already shows something newer, - -- removing an older row cannot change the preview. This is the common case - -- for the 40-message history cap in 05, which deletes a batch per insert. - IF TG_OP = 'DELETE' AND EXISTS ( - SELECT 1 FROM public.conversations - WHERE id = target_conversation - AND last_message_at IS NOT NULL - AND last_message_at > OLD.created_at - ) THEN - RETURN NULL; - END IF; - - -- Slow path: a delete of the newest row, a soft delete, or an edit of an - -- older message. The preview has to be re-derived from what is left. - SELECT m.text, m.media_type, m.created_at, m.sender_id, m.is_deleted - INTO newest - FROM public.messages m - WHERE m.conversation_id = target_conversation - AND m.is_deleted = false - ORDER BY m.created_at DESC - LIMIT 1; - - IF NOT FOUND THEN - UPDATE public.conversations - SET last_message = NULL, - last_message_at = NULL, - last_message_sender_id = NULL - WHERE id = target_conversation; - ELSE - UPDATE public.conversations - SET last_message = COALESCE(newest.text, - 'Sent a ' || COALESCE(newest.media_type, 'file')), - last_message_at = newest.created_at, - last_message_sender_id = newest.sender_id - WHERE id = target_conversation; - END IF; - - RETURN NULL; -END; -$$; - -DROP TRIGGER IF EXISTS trg_sync_conversation_last_message ON public.messages; -CREATE TRIGGER trg_sync_conversation_last_message - AFTER INSERT OR UPDATE OF text, media_type, is_deleted OR DELETE - ON public.messages - FOR EACH ROW - EXECUTE FUNCTION public.sync_conversation_last_message(); - --- The fast path above needs no lookup at all; only edits/deletes of older --- messages touch the index below, and they resolve it in one index scan. - -CREATE INDEX IF NOT EXISTS idx_messages_conv_created - ON public.messages(conversation_id, created_at DESC); - -CREATE INDEX IF NOT EXISTS idx_conversations_last_message_at - ON public.conversations(last_message_at DESC NULLS LAST); - --- Legacy path only (used until the client detects `last_read_at`). -CREATE INDEX IF NOT EXISTS idx_messages_unread - ON public.messages(conversation_id) - WHERE is_read = false; - - --- ── 3. Stop broadcasting whole rows on UPDATE ────────────────────────────── --- `REPLICA IDENTITY FULL` makes every UPDATE emit the complete OLD row and the --- complete NEW row to every subscribed client. On `users` that payload includes --- `settings`, `lock` (passcode hash!) and `fcm_tokens`. DEFAULT sends the new --- row plus the primary key only — smaller, and no private columns on the wire. --- --- `messages` is deliberately NOT in this list. `useChatMessages` listens for --- DELETE events with a `conversation_id=eq.…` filter, and the filter column is --- only present in the `old` record when the identity is FULL — with DEFAULT the --- event cannot be matched and "delete for everyone" would stop propagating. --- The read-marker change (section 1) is what removes messages UPDATE traffic; --- deletes are rare, so FULL stays there. --- --- `conversations`, `users` and `calls` are only ever read via `payload.new` on --- the client (and a conversation DELETE also removes its participant rows, which --- ARE FULL), so DEFAULT is safe for them. Calls are status-UPDATEd, never --- deleted (`CallProvider` zombie sweep). The pair of `FULL` entries re-asserts --- the two tables whose filtered DELETEs the client depends on, so this file --- leaves the database correct no matter which earlier scripts were applied. - -DO $$ -DECLARE - target RECORD; -BEGIN - FOR target IN - SELECT * FROM (VALUES - ('users', 'DEFAULT'), - ('conversations', 'DEFAULT'), - ('calls', 'DEFAULT'), - ('call_candidates', 'DEFAULT'), - ('messages', 'FULL'), - ('conversation_participants','FULL') - ) AS t(tbl, identity) - LOOP - IF EXISTS (SELECT 1 FROM pg_class c - JOIN pg_namespace n ON n.oid = c.relnamespace - WHERE n.nspname = 'public' AND c.relname = target.tbl) THEN - EXECUTE format('ALTER TABLE public.%I REPLICA IDENTITY %s', - target.tbl, target.identity); - END IF; - END LOOP; -END; -$$; - - --- Advanced (optional, experimental): if messages UPDATE payloads ever matter --- again, `ALTER TABLE public.messages REPLICA IDENTITY USING INDEX --- messages_id_conversation_id_key;` (with a UNIQUE index on (id, --- conversation_id)) makes the `old` record carry just those two columns. Verify --- in the Realtime inspector that DELETE events still arrive before relying on --- it. - --- ── 4. Unread counts without a per-message scan (optional, recommended) ──── --- Call: supabase.rpc('get_unread_counts') --- Returns one row per conversation with a badge, instead of one row per unread --- message. `last_read_at` already removes the need; this is exact and cheap. - -CREATE OR REPLACE FUNCTION public.get_unread_counts() -RETURNS TABLE (conversation_id UUID, unread_count BIGINT) -LANGUAGE sql -STABLE -SECURITY DEFINER -SET search_path = public -AS $$ - SELECT m.conversation_id, COUNT(*) AS unread_count - FROM public.messages m - JOIN public.conversation_participants cp - ON cp.conversation_id = m.conversation_id - AND cp.user_id = auth.uid() - WHERE m.sender_id <> auth.uid() - AND m.is_deleted = false - AND (cp.last_read_at IS NULL OR m.created_at > cp.last_read_at) - GROUP BY m.conversation_id; -$$; - -GRANT EXECUTE ON FUNCTION public.get_unread_counts() TO authenticated; - - --- ── 5. Retention (run when you want it — nothing calls it automatically) ─── --- Egress is paid on read, not on storage, but a smaller table keeps the --- unread/latest queries from degrading. Deletes soft-deleted rows and anything --- older than `keep_days` for conversations that are inactive. - -CREATE OR REPLACE FUNCTION public.prune_old_messages(keep_days INTEGER DEFAULT 90) -RETURNS INTEGER -LANGUAGE plpgsql -SECURITY DEFINER -SET search_path = public -AS $$ -DECLARE - removed INTEGER := 0; - affected UUID[]; -BEGIN - SELECT array_agg(DISTINCT conversation_id) INTO affected - FROM ( - SELECT m.conversation_id - FROM public.messages m - JOIN public.conversations c ON c.id = m.conversation_id - WHERE m.created_at < NOW() - make_interval(days => keep_days) - AND c.updated_at < NOW() - make_interval(days => keep_days) - ORDER BY m.created_at - LIMIT 5000 - ) t; - - IF affected IS NULL THEN - RETURN 0; - END IF; - - -- The per-row last_message trigger would fire once per deleted row (5000 - -- index scans); the last_message of these inactive conversations is - -- recomputed in one pass below instead. DDL is transactional, so this rolls - -- back with the function if anything fails. - BEGIN - ALTER TABLE public.messages DISABLE TRIGGER trg_sync_conversation_last_message; - EXCEPTION WHEN OTHERS THEN - NULL; -- not the table owner; the trigger just stays on - END; - - DELETE FROM public.messages m - USING ( - SELECT m2.id - FROM public.messages m2 - JOIN public.conversations c ON c.id = m2.conversation_id - WHERE m2.created_at < NOW() - make_interval(days => keep_days) - AND c.updated_at < NOW() - make_interval(days => keep_days) - ORDER BY m2.created_at - LIMIT 5000 - ) stale - WHERE m.id = stale.id; - - GET DIAGNOSTICS removed = ROW_COUNT; - - BEGIN - ALTER TABLE public.messages ENABLE TRIGGER trg_sync_conversation_last_message; - EXCEPTION WHEN OTHERS THEN - NULL; - END; - - UPDATE public.conversations c - SET last_message = x.text, - last_message_at = x.created_at, - last_message_sender_id = x.sender_id - FROM ( - SELECT DISTINCT ON (m.conversation_id) - m.conversation_id, m.text, m.created_at, m.sender_id - FROM public.messages m - WHERE m.conversation_id = ANY(affected) - AND m.is_deleted = false - ORDER BY m.conversation_id, m.created_at DESC - ) x - WHERE c.id = x.conversation_id; - - RETURN removed; -END; -$$; - --- Example: keep the last 90 days. --- SELECT public.prune_old_messages(90); --- Scheduled (needs the pg_cron extension enabled in Dashboard → Database → --- Extensions): --- SELECT cron.schedule('prune-messages', '0 4 * * *', $$SELECT public.prune_old_messages(90)$$); - - --- ── 5b. Optional hardening (commented out — read before enabling) ────────── --- `conversation_participants` is readable by EVERY authenticated user --- (`FOR SELECT USING (true)`), which leaks who-talks-to-whom, and `users` is --- readable the same way, which leaks `email`, `phone`, `lock` (passcode hash!) --- and `fcm_tokens` of every account. Neither is an egress bug, but both are --- foundation mistakes worth closing. The membership check below needs a --- SECURITY DEFINER helper: a policy on the table cannot query the same table --- (Postgres raises "infinite recursion detected in policy"). --- --- CREATE OR REPLACE FUNCTION public.is_conversation_member(conv UUID, uid UUID) --- RETURNS BOOLEAN LANGUAGE sql STABLE SECURITY DEFINER SET search_path = public --- AS $$ SELECT EXISTS (SELECT 1 FROM public.conversation_participants --- WHERE conversation_id = conv AND user_id = uid); $$; --- --- DROP POLICY IF EXISTS "Allow auth users to inspect participants" --- ON public.conversation_participants; --- CREATE POLICY "Members can inspect their conversations' participants" --- ON public.conversation_participants FOR SELECT --- USING (public.is_conversation_member(conversation_id, auth.uid())); --- --- DROP POLICY IF EXISTS "Allow public read access on profiles" ON public.users; --- CREATE POLICY "Profiles are readable, secrets are not" ON public.users --- FOR SELECT USING (true); -- plus a view/column grants, see --- -- docs/EGRESS_AUDIT.md §6.4 - - --- ── 6. Sanity check ──────────────────────────────────────────────────────── --- Run this afterwards; every row should read like the expected value. -SELECT 'conversation_participants.last_read_at' AS what, - CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END AS state - FROM information_schema.columns - WHERE table_schema = 'public' AND table_name = 'conversation_participants' - AND column_name = 'last_read_at' -UNION ALL -SELECT 'conversations.last_message_sender_id', - CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END - FROM information_schema.columns - WHERE table_schema = 'public' AND table_name = 'conversations' - AND column_name = 'last_message_sender_id' -UNION ALL -SELECT 'replica identity: users', - COALESCE((SELECT CASE WHEN c.relreplident = 'f' THEN 'STILL FULL' ELSE 'OK (default)' END - FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace - WHERE n.nspname = 'public' AND c.relname = 'users'), 'MISSING') -UNION ALL -SELECT 'replica identity: conversations (expect default)', - COALESCE((SELECT CASE WHEN c.relreplident = 'f' THEN 'STILL FULL' ELSE 'OK (default)' END - FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace - WHERE n.nspname = 'public' AND c.relname = 'conversations'), 'MISSING') -UNION ALL -SELECT 'replica identity: messages (expect FULL)', - COALESCE((SELECT CASE WHEN c.relreplident = 'f' THEN 'OK (full)' ELSE 'CHANGED - deletes will stop reaching clients' END - FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace - WHERE n.nspname = 'public' AND c.relname = 'messages'), 'MISSING') -UNION ALL -SELECT 'sync trigger on messages', - CASE WHEN COUNT(*) > 0 THEN 'OK' ELSE 'MISSING' END - FROM pg_trigger - WHERE tgname = 'trg_sync_conversation_last_message' -UNION ALL -SELECT 'UPDATE policy on conversation_participants', - CASE WHEN COUNT(*) FILTER (WHERE cmd = 'UPDATE') > 0 THEN 'OK' ELSE 'MISSING' END - FROM pg_policies - WHERE schemaname = 'public' AND tablename = 'conversation_participants'; - - --- ══════════════════════════════════════════════════════════════════════════ --- DONE. Verify with the checklist in sql/00_master_instructions.md --- ══════════════════════════════════════════════════════════════════════════ diff --git a/sql/legacy/README.md b/sql/legacy/README.md index 21c2486..ac2f2b7 100644 --- a/sql/legacy/README.md +++ b/sql/legacy/README.md @@ -1,16 +1,16 @@ # Superseded SQL — **do not run these** Everything in this folder was replaced by the numbered files in `sql/` -(`01_core_schema.sql` … `09_egress_optimizations.sql`). It is kept only as a -record of what the database used to look like. +(`sql/01_schema.sql` + `sql/02_functions_realtime_storage.sql`). It is kept only +as a record of what the database used to look like. | File | What it is | Why it is here | |---|---|---| -| `grixchat_latest_db_updates.sql` | An older "run me" patch file with its own copies of the pruners, the `last_message` trigger and profiles policies | Its policies have different names from `01_core_schema.sql`; running both creates **duplicate, conflicting policies**. | -| `supabase_schema.sql` | The original all-in-one schema (create tables + RLS + indexes) | Byte-for-byte superseded by `01_core_schema.sql` + `04_triggers_functions_and_rpc.sql`. | -| `supabase_posts_schema.sql` | Original posts/likes/comments schema | Superseded by `02_posts_and_interactions_schema.sql`. | -| `supabase_support_tickets_schema.sql` | Original support-ticket schema | Superseded by `03_support_tickets_schema.sql`. | -| `superseded_complete_schema.sql` | `db/1_complete_schema.sql` — an early, divergent design (`users.email UNIQUE NOT NULL`, `users.status`, `group_call_participants`, `uuid-ossp`) | **Actively dangerous**: it defines `public.users` differently from `01_core_schema.sql`, so running it on a current project breaks the app. | +| `grixchat_latest_db_updates.sql` | An older "run me" patch file with its own copies of the pruners, the `last_message` trigger and profiles policies | Its policies have different names from `01_schema.sql`; running both creates **duplicate, conflicting policies**. | +| `supabase_schema.sql` | The original all-in-one schema (create tables + RLS + indexes) | Byte-for-byte superseded by `01_schema.sql` + `02_functions_realtime_storage.sql`. | +| `supabase_posts_schema.sql` | Original posts/likes/comments schema | Superseded by `01_schema.sql`. | +| `supabase_support_tickets_schema.sql` | Original support-ticket schema | Superseded by `01_schema.sql`. | +| `superseded_complete_schema.sql` | `db/1_complete_schema.sql` — an early, divergent design (`users.email UNIQUE NOT NULL`, `users.status`, `group_call_participants`, `uuid-ossp`) | **Actively dangerous**: it defines `public.users` differently from `01_schema.sql`, so running it on a current project breaks the app. | | `superseded_realtime_and_security.sql` | `db/2_realtime_and_security.sql` — the matching RLS/realtime pass for that early design | Same reason. | Rules that came out of this cleanup: diff --git a/src/__tests__/sqlMigrations.test.ts b/src/__tests__/sqlMigrations.test.ts index d81f6da..ddd30b5 100644 --- a/src/__tests__/sqlMigrations.test.ts +++ b/src/__tests__/sqlMigrations.test.ts @@ -1,19 +1,21 @@ /** * Guards for the database setup files in `sql/`. * - * These are the rules that keep the two supported scenarios true: + * The rules these tests enforce: * 1. a brand-new Supabase project can run the whole set and end up complete * 2. an existing project can run the SAME set again, at any time, without an * error and without losing data + * 3. every file stays between 600 and 1000 lines — append to the current file + * until it is full, then start the next number (no tiny files, no 2000-line + * files) + * 4. every file opens with a short "COVERS:" header; detail lives in the .md * - * Rule 2 was broken for a long time: `01_core_schema.sql` began with - * `DROP TABLE … CASCADE` for every core table, so re-running "the setup" on a - * live database silently deleted every user, message and post (it reported zero - * errors while doing it). There is a test for that now. + * Rule 2 was broken for a long time: the setup began with `DROP TABLE … CASCADE` + * for every core table, so re-running it on a live database silently deleted + * every user, message and post (it reported zero errors while doing it). * * @vitest-environment node */ -import {execFileSync} from 'node:child_process'; import {readFileSync, readdirSync} from 'node:fs'; import {fileURLToPath} from 'node:url'; import {dirname, join} from 'node:path'; @@ -21,25 +23,51 @@ import {describe, expect, it} from 'vitest'; const here = dirname(fileURLToPath(import.meta.url)); const sqlDir = join(here, '..', '..', 'sql'); -const repoRoot = join(here, '..', '..'); -/** Every numbered migration, in execution order. */ +/** Numbered migrations, in execution order. */ const migrations = readdirSync(sqlDir) .filter((f) => /^0\d_.+\.sql$/.test(f)) .sort(); const sqlOf = (name: string) => readFileSync(join(sqlDir, name), 'utf8'); +const linesOf = (name: string) => sqlOf(name).split('\n').length; -/** SQL with line/block comments removed, so prose about a rule cannot trip it. */ +/** SQL with comments removed, so prose about a rule cannot trip it. */ function code(sql: string) { return sql.replace(/\/\*[\s\S]*?\*\//g, '').replace(/--[^\n]*/g, ''); } +/** Upper bound from the file-size rule; the lower bound applies to every file but the current one. */ +const MAX_LINES = 1000; +const MIN_FULL_FILE_LINES = 600; + describe('sql/ migrations', () => { - it('covers 01 through 09 and nothing else is left loose', () => { - expect(migrations.map((f) => f.slice(0, 2))).toEqual( - ['01', '02', '03', '04', '05', '06', '07', '08', '09'], - ); + it('starts at 01 and is contiguous', () => { + const numbers = migrations.map((f) => Number(f.slice(0, 2))); + expect(numbers.length).toBeGreaterThan(0); + expect(numbers).toEqual(numbers.map((_, i) => i + 1)); + }); + + it('keeps every file between 600 and 1000 lines (the last one may still be filling up)', () => { + migrations.forEach((file, index) => { + const isLast = index === migrations.length - 1; + const lines = linesOf(file); + expect(lines, `${file} is over the ${MAX_LINES}-line limit — start the next file`).toBeLessThanOrEqual(MAX_LINES); + if (!isLast) { + expect( + lines, + `${file} is only ${lines} lines — append to it instead of starting a new file`, + ).toBeGreaterThanOrEqual(MIN_FULL_FILE_LINES); + } + }); + }); + + it('explains what it covers in a short header', () => { + for (const file of migrations) { + const head = sqlOf(file).split('\n').slice(0, 20).join('\n'); + expect(head, `${file} needs a short "COVERS:" header`).toMatch(/COVERS/); + expect(head, `${file} should name the file itself`).toContain(file); + } }); it('never drops or truncates a table — re-running must not delete data', () => { @@ -65,36 +93,28 @@ describe('sql/ migrations', () => { const body = code(sqlOf(file)); const created = body.match(/CREATE\s+POLICY\s+"([^"]+)"/gi) || []; const dropped = body.match(/DROP\s+POLICY\s+IF\s+EXISTS\s+"([^"]+)"/gi) || []; - // 01/02/03/06/09 own policies; each CREATE must have a matching DROP IF EXISTS. expect(created.length, `${file}: more CREATE POLICY than DROP POLICY IF EXISTS`).toBeLessThanOrEqual( dropped.length, ); } }); - it('indexes are created with IF NOT EXISTS', () => { + it('creates indexes with IF NOT EXISTS and triggers with DROP ... IF EXISTS', () => { for (const file of migrations) { - const creates = code(sqlOf(file)).match(/CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?!IF\s+NOT\s+EXISTS)/gi) || []; - expect(creates, `${file} has a CREATE INDEX without IF NOT EXISTS`).toEqual([]); + const body = code(sqlOf(file)); + expect(body.match(/CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?!IF\s+NOT\s+EXISTS)/gi) || [], `${file}: index`).toEqual([]); + const triggers = body.match(/CREATE\s+TRIGGER\s+(\w+)/gi) || []; + const dropped = body.match(/DROP\s+TRIGGER\s+IF\s+EXISTS\s+(\w+)/gi) || []; + expect(triggers.length, `${file}: trigger without DROP TRIGGER IF EXISTS first`).toBeLessThanOrEqual( + dropped.length, + ); } }); - it('the generated one-file bundle is in sync (npm run sql:bundle)', () => { - // Throws (non-zero exit) when the bundle is stale. - const out = execFileSync(process.execPath, [join(repoRoot, 'scripts', 'build-sql-bundle.mjs'), '--check'], { - cwd: repoRoot, - encoding: 'utf8', - }); - expect(out).toMatch(/up to date/); - }); - - it('the bundle contains every migration, in order', () => { - const bundle = readFileSync(join(sqlDir, 'grixchat_full_setup.sql'), 'utf8'); - let cursor = -1; - for (const file of migrations) { - const at = bundle.indexOf(`-- PART ${String(Number(file.slice(0, 2)))}/${migrations.length} — sql/${file}`); - expect(at, `${file} missing from the bundle`).toBeGreaterThan(cursor); - cursor = at; - } + it('does not leave two triggers doing the same conversation-preview write', () => { + const all = migrations.map(sqlOf).join('\n'); + // the insert-only duplicate from the old 05 file must be dropped, not created + expect(all).toMatch(/DROP TRIGGER IF EXISTS trg_update_conversation_on_message/); + expect(code(all)).not.toMatch(/CREATE TRIGGER trg_update_conversation_on_message/i); }); }); diff --git a/src/features/chat/hooks/useChatMessages.ts b/src/features/chat/hooks/useChatMessages.ts index a2cfabb..410a875 100644 --- a/src/features/chat/hooks/useChatMessages.ts +++ b/src/features/chat/hooks/useChatMessages.ts @@ -9,7 +9,7 @@ import { LocalDataCache } from '../../../services/LocalDataCache'; * with REPLICA IDENTITY FULL each of those rows was broadcast as a full * old+new payload *and* triggered a conversation-list refetch in every client. * One marker row replaces all of it — with a fallback until - * sql/09_egress_optimizations.sql is applied. See docs/EGRESS_AUDIT.md. + * sql/02_functions_realtime_storage.sql is applied. See docs/EGRESS_AUDIT.md. */ let readMarkerSupported: boolean | null = null; const readMarkerKey = (conversationId: string) => `read_at_${conversationId}`; diff --git a/src/features/chat/hooks/useConversations.ts b/src/features/chat/hooks/useConversations.ts index 4a9d74d..db23f24 100644 --- a/src/features/chat/hooks/useConversations.ts +++ b/src/features/chat/hooks/useConversations.ts @@ -24,7 +24,7 @@ const REALTIME_IN_FILTER_LIMIT = 60; /** * Does `conversation_participants.last_read_at` exist yet? - * `null` = untested. Until sql/09_egress_optimizations.sql is applied we fall + * `null` = untested. Until sql/02_functions_realtime_storage.sql is applied we fall * back to the legacy `messages.is_read` scan, so the app works either way. */ let participantsSupportReadMarker: boolean | null = null; @@ -187,7 +187,7 @@ export const useConversations = (activeFilter: string) => { participantsSupportReadMarker = true; haveReadMarker = true; } else { - // Column not there yet (sql/09_egress_optimizations.sql not applied). + // Column not there yet (sql/02_functions_realtime_storage.sql not applied). participantsSupportReadMarker = false; haveReadMarker = false; } diff --git a/src/features/notifications/NotificationsScreen.tsx b/src/features/notifications/NotificationsScreen.tsx index 54c47d0..7c918d3 100644 --- a/src/features/notifications/NotificationsScreen.tsx +++ b/src/features/notifications/NotificationsScreen.tsx @@ -41,7 +41,7 @@ export default function NotificationsScreen() { fromUserAvatar: n.from_user?.photo_url, createdAt: n.created_at, read: n.is_read, - // `sql/01_core_schema.sql` stores the action phrase in `content`. + // `sql/01_schema.sql` stores the action phrase in `content`. // `text` is only kept as a fallback for rows written by older builds. text: n.content || n.text || 'sent you a notification' })); diff --git a/src/services/db/notificationService.ts b/src/services/db/notificationService.ts index 8e58bdb..1f90850 100644 --- a/src/services/db/notificationService.ts +++ b/src/services/db/notificationService.ts @@ -6,7 +6,7 @@ import { supabase } from '../../lib/supabase'; * `NotificationsScreen` and `LikeNotificationsScreen` could never show * anything. This service is the single write path. * - * Column contract (matches `sql/01_core_schema.sql`): + * Column contract (matches `sql/01_schema.sql`): * user_id → recipient * from_user_id → actor * type → 'follow' | 'like' | 'comment' | 'system' From b6245655f5ce697824f01610ac914929012736dc Mon Sep 17 00:00:00 2001 From: GothwadTech <295316515+GothwadTech@users.noreply.github.com> Date: Sun, 11 Oct 2026 04:07:01 +0000 Subject: [PATCH 09/11] Task 6: real call lifecycle, live presence, typing, stories audit Calls - Ring once per visit to /call/:id. The screen re-dialled the peer the moment a call ended (`activeCall -> null`), which is why a call felt like it kept coming back by itself. - Delete the fake transport flag and its 1.8s auto-"connect": LiveKit is used when configured, otherwise the real peer-to-peer WebRTC session (`call-rtc:` broadcast: hello/offer/answer/candidate/bye). - One ringing timeout (45s) for both sides; the P2P connect clock now starts with the offer, so an unanswered call rings instead of erroring at 30s, and a 20s watchdog ends a call that was answered but never got media. Zombie sweep moved to 53s (it used to force-close at 40s while the caller was still ringing). - Every transport-driven teardown finalises the `calls` row through one idempotent helper, so no row is left `accepted` forever and only one side writes the "call ended" chat log. A failed accept closes as error. - Call history queried only `status = 'ended'`: declined (`rejected`) and interrupted (`error`) calls never showed up. Fixed in `useCalls` and `CallSyncService`. - Camera flip / screen share now hand the UI a fresh MediaStream (the preview kept the old track), the browser's own "Stop sharing" clears the button, and Switch Camera no longer looks enabled on voice calls. - Removed the duplicate incoming-call card for good (it wrote the status `denied`, which the CHECK constraint rejects, so decline never worked). Presence & typing - PresenceService is the single live roster (`grix-presence`); remove the legacy `online-users` channel AuthProvider opened just to watch itself. Search, discover, requests and the forward sheet now read the live roster through `useLivePresence` instead of `is_online` alone. - Typing was already one ref-counted topic per conversation; documented. Stories - Unbounded `select('*')` -> bounded columns, 24h cutoff, audience scope, 120-row cap, one cleanup per session, unseen-first rings, duration-aware progress, single view per story, mute wired, exit to /stories. - `view_story` records `auth.uid()`; a spoofed viewer param is ignored. Test infrastructure - `dev/mock/realtime.ts` parsed `in.(a,b)` with a regex that stripped backslashes instead of parentheses, so no `in.` filter ever matched and the chat-list realtime patch could not fire in tests. Fixed; the egress regression test is green again. - Full suite: 125 tests, 12 files, all passing. `npm run lint` (tsc --noEmit) clean, `npm run build` clean. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .env.example | 7 +- dev/mock/index.ts | 4 +- dev/mock/realtime.ts | 78 ++- dev/mock/rpc.ts | 7 +- docs/CONTEXT.md | 11 +- docs/DEAD_CODE.md | 39 ++ docs/DEV_SETUP.md | 11 +- docs/EGRESS_AUDIT.md | 2 + docs/KNOWN_ISSUES.md | 125 ++++- docs/TESTING.md | 5 +- sql/01_schema.sql | 2 + sql/02_functions_realtime_storage.sql | 16 +- src/App.tsx | 2 - src/__tests__/callSignaling.test.ts | 326 +++++++++++++ src/__tests__/presenceTyping.test.ts | 152 ++++++ src/components/chat-ui/ChatForwardOverlay.tsx | 9 +- .../IncomingCallNotification.tsx | 166 ------- src/components/layout/ChatBottom.tsx | 10 +- src/components/layout/ChatHeader.tsx | 13 +- src/features/call/CallScreen.tsx | 28 +- .../call/components/CallControlPanel.tsx | 129 ++--- src/features/call/components/VideoFeed.tsx | 15 +- src/features/call/services/CallSyncService.ts | 4 + .../call/services/WebRtcCallService.ts | 454 ++++++++++++++++++ src/features/chat/ChatScreen.tsx | 9 +- src/features/chat/MessageRequestsScreen.tsx | 15 +- src/features/chat/SearchUserScreen.tsx | 10 +- src/features/chat/components/ChatUserList.tsx | 108 ++--- src/features/chat/hooks/useCalls.ts | 5 +- src/features/chat/hooks/useChatSync.ts | 31 +- src/features/chat/hooks/useConversations.ts | 3 +- src/features/chat/hooks/useTypingStatus.ts | 135 +++--- src/features/grixai/GrixAIScreen.tsx | 1 - src/features/search/SearchTab.tsx | 10 +- src/features/stories/StoriesTab.tsx | 145 ++++-- src/features/stories/StoryCreationScreen.tsx | 5 +- src/features/stories/StoryWatcherScreen.tsx | 164 +++++-- src/providers/AppProviders.tsx | 9 +- src/providers/AuthProvider.tsx | 56 +-- src/providers/CallProvider.tsx | 454 ++++++++++++++---- src/providers/PresenceProvider.tsx | 77 +++ src/services/PresenceService.ts | 215 +++++++++ src/services/TypingService.ts | 262 ++++++++++ src/utils/presence.ts | 87 +++- 44 files changed, 2758 insertions(+), 658 deletions(-) create mode 100644 src/__tests__/callSignaling.test.ts create mode 100644 src/__tests__/presenceTyping.test.ts delete mode 100644 src/components/incoming-call/IncomingCallNotification.tsx create mode 100644 src/features/call/services/WebRtcCallService.ts create mode 100644 src/providers/PresenceProvider.tsx create mode 100644 src/services/PresenceService.ts create mode 100644 src/services/TypingService.ts diff --git a/.env.example b/.env.example index 1f71465..0999295 100644 --- a/.env.example +++ b/.env.example @@ -32,6 +32,11 @@ VITE_FIREBASE_VAPID_KEY= VITE_FIREBASE_DATABASE_URL= # ── LiveKit (client URL only; keys stay on the server) ─────────────────────── +# OPTIONAL. Leave empty and calls still work: CallProvider falls back to a real +# peer-to-peer WebRTC session signalled over Supabase Realtime +# (src/features/call/services/WebRtcCallService.ts). Set both this and the +# LIVEKIT_API_KEY / LIVEKIT_API_SECRET below to route calls through an SFU +# instead — that is what group calls and large rooms will need. VITE_LIVEKIT_URL= # ── Server-only secrets ────────────────────────────────────────────────────── @@ -50,7 +55,7 @@ GEMINI_API_KEY= # automatically. FIREBASE_SERVICE_ACCOUNT= -# LiveKit token signing, for /api/livekit-token +# LiveKit token signing, for /api/livekit-token. OPTIONAL — see above. LIVEKIT_API_KEY= LIVEKIT_API_SECRET= diff --git a/dev/mock/index.ts b/dev/mock/index.ts index d740566..d2e1002 100644 --- a/dev/mock/index.ts +++ b/dev/mock/index.ts @@ -101,8 +101,8 @@ class MockSupabaseClient { return callRpc(fn, args); } - channel(topic: string, _opts?: any) { - const ch = new MockChannel(topic); + channel(topic: string, opts?: any) { + const ch = new MockChannel(topic, opts); this.channels.add(ch); return ch as any; } diff --git a/dev/mock/realtime.ts b/dev/mock/realtime.ts index 567ad94..76a886f 100644 --- a/dev/mock/realtime.ts +++ b/dev/mock/realtime.ts @@ -5,12 +5,14 @@ * • `postgres_changes` — driven by writes to the mock store, honouring * `filter: 'receiver_id=eq.'` / `conversation_id=in.(a,b)` * • `broadcast` — an in-process pub/sub, used for typing indicators - * • `presence` — a local roster, used for online status + call signalling + * • `presence` — a roster shared by every channel on the topic, keyed by the + * `config.presence.key` (the user id), with sync/join/leave events — the + * same contract `PresenceService` relies on against real Supabase. * * Everything is single-tab: a real multi-device test still needs Supabase. */ import { store } from './store'; -import { clone, evalOp, Row, uuid } from './utils'; +import { clone, evalOp, Row } from './utils'; interface Sub { type: string; @@ -23,17 +25,21 @@ interface Sub { export class MockChannel { readonly topic: string; + /** Presence key for this connection (Supabase: `config.presence.key`). */ + readonly presenceKey: string; private subs: Sub[] = []; private unsubscribed = false; private state: 'closed' | 'joining' | 'joined' = 'closed'; - private presenceState: Record = {}; private unsubscribeStore?: () => void; /** Shared across channels so broadcast() reaches every subscriber on the topic. */ static registry = new Map>(); + /** Presence roster per topic — topic → key → payload list. */ + static presenceRegistry = new Map>(); - constructor(topic: string) { + constructor(topic: string, opts?: any) { this.topic = topic; + this.presenceKey = opts?.config?.presence?.key || `anon-${Math.random().toString(36).slice(2, 9)}`; if (!MockChannel.registry.has(topic)) MockChannel.registry.set(topic, new Set()); MockChannel.registry.get(topic)!.add(this); } @@ -61,6 +67,12 @@ export class MockChannel { this.state = 'closed'; this.unsubscribeStore?.(); MockChannel.registry.get(this.topic)?.delete(this); + // Dropping the socket drops the presence entry: announce it to the peers. + const roster = MockChannel.presenceRegistry.get(this.topic); + if (roster?.delete(this.presenceKey)) { + MockChannel.broadcastPresence(this.topic, 'leave', this.presenceKey, {}, {}); + MockChannel.broadcastPresence(this.topic, 'sync', '', {}, {}); + } return Promise.resolve('ok' as const); } @@ -76,20 +88,57 @@ export class MockChannel { } track(state: Record): Promise<'ok'> { - const key = uuid(); - this.presenceState[key] = [state]; - this.emitPresence('join', key, state, {}); + if (!MockChannel.presenceRegistry.has(this.topic)) { + MockChannel.presenceRegistry.set(this.topic, new Map()); + } + MockChannel.presenceRegistry.get(this.topic)!.set(this.presenceKey, [state]); + + (MockChannel.registry.get(this.topic) || new Set()).forEach((peer) => { + if (peer.unsubscribed) return; + peer.emitPresence('join', this.presenceKey, state, {}); + peer.emitPresence('sync', '', {}, {}); + }); return Promise.resolve('ok' as const); } untrack(): Promise<'ok'> { - const before = { ...this.presenceState }; - this.presenceState = {}; - this.emitPresence('leave', '', {}, before); + const roster = MockChannel.presenceRegistry.get(this.topic); + const before = roster?.get(this.presenceKey) || []; + roster?.delete(this.presenceKey); + + (MockChannel.registry.get(this.topic) || new Set()).forEach((peer) => { + if (peer.unsubscribed) return; + peer.emitPresence('leave', this.presenceKey, {}, before); + peer.emitPresence('sync', '', {}, {}); + }); return Promise.resolve('ok' as const); } + /** Same shape as the real client: key → array of tracked payloads. */ + presenceState(): Record { + const roster = MockChannel.presenceRegistry.get(this.topic); + const out: Record = {}; + roster?.forEach((payloads, key) => { + out[key] = clone(payloads); + }); + return out; + } + // --- internals ----------------------------------------------------------- + + private static broadcastPresence( + topic: string, + event: string, + key: string, + current: any, + prev: any, + ) { + (MockChannel.registry.get(topic) || new Set()).forEach((peer) => { + if (peer.unsubscribed) return; + peer.emitPresence(event, key, current, prev); + }); + } + private matchesFilter(sub: Sub, payload: any): boolean { if (sub.table && sub.table !== payload.table) return false; if (sub.event && sub.event !== '*' && sub.event !== payload.eventType) return false; @@ -98,7 +147,14 @@ export class MockChannel { if (!eq) return true; // unsupported filter shape → permissive const [, column, op, rawValue] = eq; if (op.toLowerCase() === 'in') { - const list = rawValue.replace(/^\(|\)$/g, '').split(',').map((s) => s.trim()); + // PostgREST: `column=in.(a,b,c)` — strip the parens, then the optional + // double quotes PostgREST adds around values that contain a comma. + const list = rawValue + .replace(/^\(/, '') + .replace(/\)$/, '') + .split(',') + .map((s) => s.trim().replace(/^"(.*)"$/, '$1')) + .filter((s) => s.length > 0); return evalOp(payload.new, column, 'in', list); } return evalOp(payload.new, column, op.toLowerCase(), rawValue); diff --git a/dev/mock/rpc.ts b/dev/mock/rpc.ts index 5ef5e2d..10485b9 100644 --- a/dev/mock/rpc.ts +++ b/dev/mock/rpc.ts @@ -86,16 +86,19 @@ function viewStory({ viewer_id_param, viewer_username_param, viewer_fullname_param, + viewer_photo_url_param, }: any) { const row = store.table('stories').find((r) => looseEq(r.id, story_id_param)); if (!row) return fail(`view_story: no story ${story_id_param}`); const before = clone(row); const views: Row[] = Array.isArray(row.views) ? row.views : []; - if (!views.some((v) => looseEq(v.viewer_id, viewer_id_param))) { + // Mirrors public.view_story() in sql/02: `id` is the viewer's user id. + if (!views.some((v) => looseEq(v.id, viewer_id_param))) { views.push({ - viewer_id: viewer_id_param, + id: viewer_id_param, username: viewer_username_param, full_name: viewer_fullname_param, + photo_url: viewer_photo_url_param, viewed_at: nowISO(), }); row.views = views; diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 2f36182..cf7e37a 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -145,7 +145,16 @@ Full map: **[ARCHITECTURE.md](./ARCHITECTURE.md)**. 13 tables, all defined in `sql/`: `users`, `follows`, `conversations`, `conversation_participants`, `messages`, `stories`, `calls`, `chat_settings`, `notifications`, `posts`, `post_likes`, `post_comments`, `support_tickets`. -(`call_candidates` is defined but unused — calling signals over Broadcast.) +(`call_candidates` is defined but unused — calling signals over Broadcast: +`call-rtc:` carries the SDP/ICE exchange for the peer-to-peer transport, +while a LiveKit room is used when `LIVEKIT_API_KEY`/`LIVEKIT_API_SECRET` and +`VITE_LIVEKIT_URL` are configured. Presence and typing are handled by +`src/services/PresenceService.ts` (one Realtime Presence channel for the whole +app) and `src/services/TypingService.ts` (ref-counted per-conversation broadcast +topics) — both 0 database bytes. `users.is_online`/`last_seen` are only the +*durable fallback* (both for the first paint before the roster syncs and for +"last seen" text); the heartbeat in `AuthProvider` is the only writer, and no +other component opens a presence channel of its own.) 3 RPCs, all defined: `get_direct_conversation_id`, `view_story`, `cleanup_expired_stories`. diff --git a/docs/DEAD_CODE.md b/docs/DEAD_CODE.md index fb84992..06bd532 100644 --- a/docs/DEAD_CODE.md +++ b/docs/DEAD_CODE.md @@ -253,3 +253,42 @@ Two things got better on the way, not just smaller: `src/__tests__/sqlMigrations.test.ts` now also enforces the new house rules: every file between 600 and 1000 lines (the newest one may still be filling up), and a short `COVERS:` header at the top of each file instead of long prose. + +## 2026-10-11 (later) — the second incoming-call card, and two fake call features + +**`src/components/incoming-call/IncomingCallNotification.tsx`** — deleted. +`App.tsx` mounted it *and* `CallProvider` rendered its own incoming-call card +for the very same event, so a ring produced two cards and two ringtones. Worse, +the App-level one only navigated to `/call/:id` without calling `acceptCall()` +(the call never actually started for the receiver) and declined with +`status: 'denied'`, which the `calls.status` CHECK constraint rejects +(`ringing | accepted | rejected | ended | error`). The provider card is the one +that works; the duplicate was routed around by nothing. + +**`useChatSync().receiverActiveChatId`** — deleted. It was state that nothing +ever set, and the chat header used it to render `online - for you` / +`online - for other` in place of a real presence label. The header now says +`online`, or `last seen …`, or `typing…`. + +**Two call-screen controls that did nothing** — removed from +`CallControlPanel`: `HD Video Calling` (toggled local state and printed +"Premium HD Active"; no track was touched) and `Active Vocal Equalizer` +(four filters that changed a label). `Switch Camera` was fake too and is now +wired to the real `flipCamera()`; `Share Your Screen` is real (LiveKit +`setScreenShareEnabled`, or `replaceTrack(getDisplayMedia())` on the P2P +transport) and is disabled with an explanation on voice calls, where there is no +video m-line to carry a shared screen. + +**The "Simulated Private Terminal" overlay** in `VideoFeed` was rendered +unconditionally *on top of* the remote video (z-1 over z-0), so a live video +call was hidden behind a blurred placeholder that said the call was still +connecting. It now renders only while there is no remote video track. + +## 2026-10-11 — the call simulator gave way to real WebRTC + +| Removed | Why | +|---|---| +| `isSandboxSimulated` (state, context field, `setIsSandboxSimulated` calls) | It described the **fake** transport: a 1.8 s timer that flipped both phones to "connected" with no media. Calling now runs on either a real LiveKit room (when `LIVEKIT_*` + `VITE_LIVEKIT_URL` exist) or a real peer-to-peer `RTCPeerConnection` over `call-rtc:` (`src/features/call/services/WebRtcCallService.ts`), so there is no simulation left to flag. `CallScreen` keys the `LiveKitRoom` wrapper on `transport === 'livekit'` instead. | +| The "Simulated Private Terminal" overlay branch in `VideoFeed` | It was keyed on that flag, so a real P2P video call showed a fake "waiting" panel *over* the live stream. The hairline-glass placeholder is now tied to `hasRemoteVideo` (a live remote video track) — wait vs. real. | +| The caller's blind `connected` transition on the database's `accepted` row | On the peer-to-peer path nothing may report `connected` before ICE does; the media path now owns that transition and the `accepted` row only stops the ringtone. Without this, an answered-but-dead call started its duration counter on a silent line. | + diff --git a/docs/DEV_SETUP.md b/docs/DEV_SETUP.md index c189a39..f5b637b 100644 --- a/docs/DEV_SETUP.md +++ b/docs/DEV_SETUP.md @@ -130,8 +130,8 @@ npm run dev | `VITE_FIREBASE_MESSAGING_SENDER_ID` | `src/lib/firebase.ts`, `NotificationHandler.tsx` | | `VITE_FIREBASE_APP_ID` | `src/lib/firebase.ts`, `NotificationHandler.tsx` | | `VITE_FIREBASE_VAPID_KEY` | `NotificationHandler.tsx` | -| `VITE_FIREBASE_DATABASE_URL` | presence code | -| `VITE_LIVEKIT_URL` | `src/providers/CallProvider.tsx` | +| `VITE_FIREBASE_DATABASE_URL` | **unused** — keep it out of new setups. Presence runs on Supabase Realtime (`src/services/PresenceService.ts`), not the Firebase RTDB. | +| `VITE_LIVEKIT_URL` | *optional* calling. With it (plus `LIVEKIT_API_KEY`/`LIVEKIT_API_SECRET` server-side) calls use a LiveKit SFU room; without it they run peer-to-peer over WebRTC signalled on a Supabase Broadcast topic. | | `VITE_BASE_URL` | build-time path prefix. Cloudflare serves from the domain root — leave empty. | > ⚠️ Any `VITE_`-prefixed variable is inlined into the shipped bundle in @@ -150,7 +150,7 @@ npm run dev |---|---| | `GEMINI_API_KEY` | `/api/grix-ai` | | `FIREBASE_SERVICE_ACCOUNT` | `/api/send-notification` (JSON, newlines may be escaped) | -| `LIVEKIT_API_KEY` / `LIVEKIT_API_SECRET` | `/api/livekit-token` | +| `LIVEKIT_API_KEY` / `LIVEKIT_API_SECRET` | `/api/livekit-token` — optional, see above | | `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` | `/api/github/auth-url` | | `SUPABASE_SERVICE_ROLE_KEY` | privileged reads/writes (FCM token cleanup). Falls back to the anon key + the caller's JWT. | | `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` | **required server-side too** — every `/api` route verifies the caller's JWT against the project | @@ -232,10 +232,11 @@ redeploy), the rest is read per request by the Functions. | Variable | Needed for | |---|---| | `VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY` | The client, **and** the API's JWT verification. Without them the Supabase SDK is tree-shaken out of the bundle — the build prints a loud warning. | -| `VITE_FIREBASE_*`, `VITE_LIVEKIT_URL` | Push registration and calling | +| `VITE_FIREBASE_*` | Push registration | +| `VITE_LIVEKIT_URL` | *(optional)* SFU calling — peer-to-peer WebRTC is the default | | `GEMINI_API_KEY` | `/api/grix-ai` | | `FIREBASE_SERVICE_ACCOUNT` | `/api/send-notification` (whole JSON, escaped `\n` is healed) | -| `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET` | `/api/livekit-token` | +| `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET` | *(optional)* `/api/livekit-token` — calls work without them | | `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET` | The GitHub browser's OAuth popup | | `SUPABASE_SERVICE_ROLE_KEY` | Push fan-out + FCM token cleanup | | `APP_URL` | `https://grixchat.gothwadtech.com` — OAuth redirect base and the CORS allowlist | diff --git a/docs/EGRESS_AUDIT.md b/docs/EGRESS_AUDIT.md index 0798fdc..78754f9 100644 --- a/docs/EGRESS_AUDIT.md +++ b/docs/EGRESS_AUDIT.md @@ -116,6 +116,8 @@ Read receipts sat on top of that, unbounded by the unread backlog. | **Read receipts are one row**: `conversation_participants.last_read_at`. Falls back to the old per-message update (bounded by the last marker) until the SQL is applied. | `useChatMessages.ts` → `executeUpdate` in `markAsRead` | | **Unread is a comparison**, not a scan — exact count from messages already cached on the device. | `useConversations.ts` → the `unreadMap` builder in `fetchConversations()` | | **Focus/visibility re-sync** replaces the "refetch on every event" habit. | `useConversations.ts` → structural effect | +| **Presence moved off the database.** `PresenceService` keeps one Realtime Presence channel for the whole app (`grix-presence`, presence key = user id); join/leave/sync are websocket frames, 0 DB bytes. `users.is_online`/`last_seen` stay as the offline fallback and are written at most once per heartbeat (5 min). The online window was also wrong: it was 150 s against a 300 s heartbeat, so an online user read as offline for 90 s out of every 240 — it is now 360 s (`PRESENCE_ONLINE_WINDOW_MS`), one constant shared by every surface. | `src/services/PresenceService.ts`, `src/providers/PresenceProvider.tsx`, `src/utils/presence.ts` | +| **Typing channels are ref-counted.** One broadcast topic per conversation is shared by the chat screen and its list row (before: a fresh channel per component per conversation), `true` is announced at most every 2.5 s, and `false` is sent explicitly on send/blur/unmount/tab-hide instead of relying on a timeout. Typing still costs 0 database rows. | `src/services/TypingService.ts`, `src/features/chat/hooks/useTypingStatus.ts` | | **No more re-render refetch loop**: deps use stable values; the presence heartbeat is 5 min (was 60 s) and the write throttle 4 min (was 45 s). | `AuthProvider.tsx` → `PRESENCE_HEARTBEAT_MS`, `userProfileService.ts` → `STATUS_WRITE_THROTTLE_MS` | | **Photos are downscaled to 1600 px / JPEG 0.82 before upload**, and stored with a 1-year immutable cache (objects are already uniquely named). | `ImageService.ts` → `compressImage()`, `SupabaseStorageService.ts` → `cacheControl` | | **Tab-bar unread scan capped** at 500 rows. | `TabBottom.tsx` → legacy unread scan | diff --git a/docs/KNOWN_ISSUES.md b/docs/KNOWN_ISSUES.md index c436622..b677951 100644 --- a/docs/KNOWN_ISSUES.md +++ b/docs/KNOWN_ISSUES.md @@ -21,9 +21,9 @@ dashboard, Supabase, or a decision. | # | Task | Where | Why it matters | |---|---|---|---| | A | Add the **build-time** variables: `VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY`, `VITE_FIREBASE_*`, `VITE_LIVEKIT_URL`, `NODE_VERSION=22` | Cloudflare → Workers & Pages → gtwdchat → Settings → Environment variables (Production **and** Preview) | They are inlined into the bundle. **Without `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` the Supabase SDK is compiled out and the deployed app cannot sign in** — the build prints a loud warning. Changing one requires a redeploy. | -| B | Add the **runtime secrets** for the API: `GEMINI_API_KEY`, `FIREBASE_SERVICE_ACCOUNT`, `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET`, `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `SUPABASE_SERVICE_ROLE_KEY`, `APP_URL=https://grixchat.gothwadtech.com` | same screen as above | The API verifies JWTs against `VITE_SUPABASE_URL` + `VITE_SUPABASE_ANON_KEY`, so those two must be present **server-side as well**. Without any of these the matching feature returns a clear "not configured" error instead of crashing. Step-by-step: [DEV_SETUP.md](./DEV_SETUP.md#deploy--cloudflare-pages). | +| B | Add the **runtime secrets** for the API: `GEMINI_API_KEY`, `FIREBASE_SERVICE_ACCOUNT`, `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `SUPABASE_SERVICE_ROLE_KEY`, `APP_URL=https://grixchat.gothwadtech.com` — and *optionally* `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET` | same screen as above | The API verifies JWTs against `VITE_SUPABASE_URL` + `VITE_SUPABASE_ANON_KEY`, so those two must be present **server-side as well**. Without any of these the matching feature returns a clear "not configured" error instead of crashing. `LIVEKIT_*` is **no longer required for calling**: without it calls run peer-to-peer over WebRTC with Supabase Realtime as the signalling channel (issue 15). Step-by-step: [DEV_SETUP.md](./DEV_SETUP.md#deploy--cloudflare-pages). | | C | Confirm the Pages build settings: build command `npm run build`, output `dist`, root `/`; production branch = your main branch; custom domain `grixchat.gothwadtech.com` attached | Cloudflare → the project's Settings / Custom domains | `wrangler.toml` pins the output dir and compatibility date, but the dashboard values win. | -| D | Decide the fate of `call_candidates` (issue 7) | Supabase SQL editor | It is defined but unused. Drop it with:
`DROP TABLE IF EXISTS public.call_candidates CASCADE;`
or keep it and adopt the table-based signalling in [`docs/legacy/3_webrtc_signaling_architecture.md`](./legacy/3_webrtc_signaling_architecture.md). | +| D | Decide the fate of `call_candidates` (issue 7) | Supabase SQL editor | It is defined but unused — and it stays unused: calling signals over a Broadcast topic (`call-rtc:`, see `src/features/call/services/WebRtcCallService.ts`), which costs nothing and needs no schema. Drop it with:
`DROP TABLE IF EXISTS public.call_candidates CASCADE;` | | E | Add a **Cloudflare Rate Limiting Rule** on `/api/*` (optional, but recommended before scaling) | Cloudflare → Security → WAF | The limiter in `server/api.ts` counts in memory, i.e. per isolate — a speed bump, not a hard global quota. | | F | Run **`sql/01_schema.sql`** then **`sql/02_functions_realtime_storage.sql`** (2 minutes, idempotent, `02` ends with a self-check) | Supabase → SQL Editor | Creates anything missing and updates every policy/function. For the egress work specifically: read receipts become one row instead of one per unread message, the chat-list preview is maintained by a trigger, `REPLICA IDENTITY` stops shipping whole rows + the passcode hash, and the missing RLS UPDATE policy on `conversation_participants` gets created. Runbook: [`../sql/00_master_instructions.md`](../sql/00_master_instructions.md). Full analysis: [EGRESS_AUDIT.md](./EGRESS_AUDIT.md). | | G | Decide whether to enable the **RLS hardening** block at the end of that same file (commented out) | Supabase → SQL Editor | Today `users` and `conversation_participants` are readable by every authenticated account: `email`, `phone`, `lock` (passcode hash), `fcm_tokens`, and the whole follow/participant graph. | @@ -120,10 +120,38 @@ the mock keeps mirroring `sql/`. ### 7. `call_candidates` is defined but never used — ❌ STILL OPEN (needs SQL) -The live calling path (`providers/CallProvider.tsx`) signals over Broadcast -channels, so the table is dead weight. Dropping it is a one-line migration the -repo cannot run for you — see task **C** at the top. No code change is pending -on either side of the decision. +The live calling path signals over a Realtime Broadcast topic +(`call-rtc:`, see `src/features/call/services/WebRtcCallService.ts`), so +the table is dead weight. Dropping it is a one-line migration the repo cannot +run for you — see task **D** at the top. No code change is pending on either +side of the decision. + +### 15. Calling only worked when LiveKit was configured — ✅ FIXED + +Two separate problems, both fixed: + +- **Silent fake calls.** Without `LIVEKIT_API_KEY`/`LIVEKIT_API_SECRET` (and + `VITE_LIVEKIT_URL`), `connectToLiveKitSession()` fell back to a *simulator* + that put both phones into a "connected" state after 1.8 s — an outgoing call + looked answered while the other device was still ringing, and no media ever + moved. The fallback is now a real WebRTC peer-to-peer session: only the caller + offers, the receiver answers, ICE candidates are buffered until the remote + description lands, and `connected` is only ever reported by the actual + `RTCPeerConnection` (see `src/__tests__/callSignaling.test.ts`). LiveKit is + still used, unchanged, whenever it *is* configured. +- **A duplicated incoming-call card.** `App.tsx` mounted + `IncomingCallNotification`, and `CallProvider` rendered its own card for the + same event: two ringtones, two cards, and the App-level one wrote the status + `denied`, which the `calls.status` CHECK constraint rejects — so "decline" + from that card never reached the database. The duplicate is deleted; the + provider's card is the single source, and declines write `rejected`. + +**Remaining human step (only if calls must work on strict corporate/mobile +networks):** the P2P transport uses public STUN servers and no TURN relay. Most +home/mobile networks connect directly; symmetric-NAT or locked-down networks +need a TURN server. Add one to `ICE_SERVERS` in +`src/features/call/services/WebRtcCallService.ts` (e.g. Cloudflare Calls TURN or +a self-hosted coturn) — it is a one-line change with no other moving parts. ### 8. Password reset had no path — ✅ FIXED @@ -331,6 +359,87 @@ with it: --- +## 🔵 Task 6 — calls, presence & typing (2026-10-11) + +Everything below is fixed in code; the only remaining item is the optional TURN +note under issue 15. + +### 21. The call screen re-dialled the peer after a call ended — ✅ FIXED + +`CallScreen` started a call whenever `activeCall` was `null`. The moment a call +ended, `handleEndCallLocally()` sets exactly that — so hanging up (or being hung +up on) immediately placed a **new** call to the same person, which looked like +"the call keeps coming back". Ringing is now guarded by a `ringStartedRef`: one +ring per visit to the screen, and an already-running call is adopted rather than +re-dialled. Pinned by *ringing is not a failure* in +`src/__tests__/callSignaling.test.ts`. + +### 22. Timeouts disagreed, so calls died at the wrong moment — ✅ FIXED + +| Was | Now | +|---|---| +| Zombie sweep force-closed a `ringing` row after **40 s** while the caller's own give-up was **45 s** | one constant: `RING_TIMEOUT_MS = 45_000`, sweep threshold = ring timeout + 8 s | +| The P2P caller's connect clock started at ring time, so an unanswered call showed an error at 30 s with the phone still ringing | the clock starts with the offer (i.e. when the receiver actually picked up); an unanswered call is handled by the ring timeout | +| The receiver's stale-ring check was 30 s | the ringing window: a call that reconnects inside it still rings | +| An answered call whose media never arrived rang forever (`accepted` disabled the ring timeout) | `CONNECT_WATCHDOG_MS = 20 s` — then the call ends honestly and the row is finalised | + +### 23. A call could stay `accepted` forever, and declines were invisible — ✅ FIXED + +- `webRtcCallService`'s `bye`/ICE-failure path only cleared local state; the + `calls` row stayed `accepted`, so the history showed a call that never ended. + Every transport-driven teardown now finalises the row through one **idempotent** + helper (`closeCallRow`, guarded by `.in('status', ['ringing','accepted'])`), + which also decides who writes the single "call ended" chat log — both sides + notice a hang-up at the same instant. +- The call history fetched `.eq('status','ended')` only, so a **declined** call + (stored as `rejected`) and an interrupted one (`error`) never appeared. + `useCalls` and `CallSyncService` now use `.in('status', ['ended','rejected','error'])`. +- A receiver whose accept failed (no camera permission, dead tab) left the row + `accepted`; it is now closed as `error`. + +### 24. Chat list lost every realtime event in the mock — ✅ FIXED + +Not app code: `dev/mock/realtime.ts` parsed `filter: conversation_id=in.(a,b)` +with a regex that stripped *backslashes* instead of parentheses, so the parsed +list was `["(a", "b)"]` and no event ever matched. The list-row patch (the whole +point of the egress fix) could therefore never fire in tests or `dev:mock` — it +is what made `src/__tests__/egressRealtime.test.tsx` fail. Fixed, and that test +is now the regression guard. + +### 25. Presence and typing, one source of truth — ✅ FIXED + +- Live roster: `src/services/PresenceService.ts` owns **one** Realtime Presence + channel (`grix-presence`) for the whole app; `PresenceProvider` exposes it + (`useIsUserOnline`, `useLivePresence`). The legacy `online-users` channel + `AuthProvider` opened (which only watched *yourself* and wrote `is_online`) + is gone — `AuthProvider` now only runs the durable heartbeat. +- Every online dot reads the roster first and falls back to + `users.is_online`/`last_seen` through the single helper `isUserOnline`: + chat list, chat header, search results, discover, message requests, forward + sheet, profile, read receipts. When the roster is authoritative, a user who + closes their tab goes offline **instantly** instead of after the 6-minute + fallback window. +- Typing: one ref-counted broadcast topic per conversation + (`src/services/TypingService.ts`) shared by the chat header and the chat-list + row, `typing…` in the header, explicit `false` on send/blur/unmount/tab-hidden, + and a 6 s receiver-side TTL as the safety net. + +### 26. Stories — the only content feature left, reviewed end to end — ✅ FIXED + +With the post system deleted, stories carry the whole "look what I did" surface, +so they were walked through as a feature rather than as a screen: + +| Step | What was wrong | Now | +|---|---|---| +| Ring list | `select('*')` with no time bound and no audience bound: every story ever posted by everybody, every time the tab was focused | bounded column list, 24 h cutoff, audience = you + the people you follow + your chat partners (≤ 200 ids), 120-row cap, cache-first paint, one `cleanup_expired_stories()` per session, unseen-first ordering with Telegram-style rings | +| Watching | progress ran on a fixed timer regardless of the video length, a view could be recorded twice, the mute button did nothing for the music track, the exit went to a route that no longer exists | duration-aware progress that resumes correctly, a duplicate `view_story` is skipped, mute drives the `