diff --git a/.dev.vars.example b/.dev.vars.example new file mode 100644 index 0000000..11c8f5c --- /dev/null +++ b/.dev.vars.example @@ -0,0 +1,34 @@ +# ───────────────────────────────────────────────────────────────────────────── +# Cloudflare Pages — local edge-runtime secrets +# +# cp .dev.vars.example .dev.vars +# npx wrangler pages dev dist +# +# `wrangler pages dev` does NOT read `.env` — only this file (`.dev.vars`, +# gitignored). These are the *runtime* values the Functions see; the VITE_* +# ones are baked into the bundle by `npm run build/`vite already. +# +# In production these live in the Cloudflare dashboard: +# Workers & Pages → gtwdchat → Settings → Environment variables +# ───────────────────────────────────────────────────────────────────────────── + +# Optional: run the API without any credentials at all. +# Mock mode is a local-dev convenience and is ignored on any Cloudflare +# deployment, so it can stay in this file safely. +MOCK_SUPABASE=1 +NODE_ENV=development + +# Origin used for OAuth redirects and the CORS allowlist. +APP_URL=http://localhost:8788 + +# ── Real credentials (only needed to exercise the live integrations) ───────── +GEMINI_API_KEY= +FIREBASE_SERVICE_ACCOUNT= +LIVEKIT_API_KEY= +LIVEKIT_API_SECRET= +GITHUB_CLIENT_ID= +GITHUB_CLIENT_SECRET= +SUPABASE_SERVICE_ROLE_KEY= +VITE_SUPABASE_URL= +VITE_SUPABASE_ANON_KEY= +ALLOWED_ORIGINS= diff --git a/.env.example b/.env.example index 5c6e705..0999295 100644 --- a/.env.example +++ b/.env.example @@ -1,10 +1,15 @@ # ───────────────────────────────────────────────────────────────────────────── # GrixChat environment template # -# cp .env.example .env +# cp .env.example .env # local development # -# Everything prefixed VITE_ is inlined into the browser bundle — never put a -# real secret there. +# Production runs on **Cloudflare Pages** (https://grixchat.gothwadtech.com). +# Every variable below goes into the Pages project: +# 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 — +# never put a real secret there. Changing one requires a redeploy. # # 💡 You do not need any of this for local development. `npm run dev:mock` # runs the full app against an in-memory mock with seeded data. @@ -27,20 +32,30 @@ 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 ────────────────────────────────────────────────────── -# Never prefix these with VITE_. +# Never prefix these with VITE_. On Cloudflare these are Pages environment +# variables; the Functions read them per request (they are not inlined). +# +# ⚠️ These CANNOT be read from a local `.env` inside the edge Functions — only +# the Node dev server (`npm run dev`) loads `.env`. For `wrangler pages dev` +# put them in `.dev.vars` (gitignored). # Gemini, for the /api/grix-ai proxy GEMINI_API_KEY= # FCM service account, for /api/send-notification. # Paste the whole JSON object; literal \n sequences in private_key are healed -# automatically by server.ts. +# 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= @@ -48,16 +63,41 @@ LIVEKIT_API_SECRET= GITHUB_CLIENT_ID= GITHUB_CLIENT_SECRET= -# Server-side Supabase client (bypasses RLS — server only) +# Server-side Supabase client (bypasses RLS — server only). +# Needed for push fan-out and FCM token cleanup. SUPABASE_SERVICE_ROLE_KEY= -# Base URL used to build OAuth redirects +# Canonical origin: OAuth redirect base and the first entry of the CORS / +# origin allowlist. https://grixchat.gothwadtech.com APP_URL= -# Set to "production" to serve dist/ instead of the Vite dev middleware +# Extra browser origins allowed to call /api/* (comma-separated). +# Same-origin requests are always allowed, so this is only needed when the +# frontend and the API live on different hosts. +ALLOWED_ORIGINS= + +# ── Runtime flags ──────────────────────────────────────────────────────────── +# Node dev server only: "production" serves dist/ instead of Vite middleware. +# Not needed on Cloudflare — but if you want the diagnostic route +# `/api/github/debug` to 404 everywhere, set NODE_ENV=production in the Pages +# environment as well (it is already hidden on any Pages deployment). NODE_ENV= +# Node dev server only (`npm run dev:mock`) — skips JWT verification for the +# in-memory mock. Ignored on Cloudflare: the edge has no mock database, so it +# always verifies. +MOCK_SUPABASE= + +# Port for the Node dev server. Cloudflare ignores it. +PORT= + +# 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 ───────────────────────────────────────────────────────────────── -# Path prefix when deploying to a sub-path (e.g. GitHub Pages "/grixchat/"). -# Leave empty or "/" for a root deploy. +# Path prefix for a sub-path deploy. Cloudflare Pages serves from the domain +# root, so leave this alone unless you deliberately deploy under a prefix. +# Cloudflare Pages serves from the domain root — leave empty. VITE_BASE_URL= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..10adf68 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,71 @@ +# Continuous integration only — Cloudflare Pages builds and deploys the site +# 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. +# +# There is deliberately no deploy step here. Deploying from two places is how +# you end up shipping a stale bundle, and the GitHub Pages deploy that used to +# live in `deploy.yml` could never work anyway: the API only exists on +# Cloudflare (`functions/`), so a github.io build would have a dead backend. +name: CI + +on: + push: + branches: [ "main" ] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: "ci-${{ github.ref }}" + cancel-in-progress: true + +jobs: + verify: + runs-on: ubuntu-latest + steps: + - name: Checkout + 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@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 + # Pages Functions bundle check below. + node-version: 22 + cache: 'npm' + + - name: Install dependencies + run: npm ci + + # `vite build` does not typecheck, so without this an entire class of + # breakage ships silently. + - name: Typecheck + run: npm run lint + + - name: Test + run: npm test + + # Verifies the Pages Functions actually bundle for the Workers runtime + # (no Node built-ins, no accidental `nodejs_compat` dependency). + - name: Build Pages Functions + # `pages functions build` needs to find `functions/` and `wrangler.toml`, + # so it runs from the repo root. Fails on any Node-only import. + run: npx wrangler pages functions build --outdir .wrangler/functions-build + + - name: Build client bundle + # Dummy values so this compiles the real Supabase-backed code path and + # skips the "credentials are missing" build warning. The artifact is + # never deployed — Cloudflare builds separately with the real values + # from the project's environment variables. + env: + VITE_SUPABASE_URL: https://example.supabase.co + VITE_SUPABASE_ANON_KEY: ci-placeholder-anon-key + run: npm run build diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml deleted file mode 100644 index 530b56b..0000000 --- a/.github/workflows/deploy.yml +++ /dev/null @@ -1,55 +0,0 @@ -name: Deploy to GitHub Pages - -on: - push: - branches: [ "main" ] - workflow_dispatch: - -permissions: - contents: read - pages: write - id-token: write - -concurrency: - group: "pages" - cancel-in-progress: true - -jobs: - build: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Set up Node - uses: actions/setup-node@v4 - with: - node-version: 20 - cache: 'npm' - - - name: Install dependencies - run: npm install - - - name: Build - run: | - npm run build - cp dist/index.html dist/404.html - - - name: Setup Pages - uses: actions/configure-pages@v4 - - - name: Upload artifact - uses: actions/upload-pages-artifact@v3 - with: - path: './dist' - - deploy: - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - runs-on: ubuntu-latest - needs: build - steps: - - name: Deploy to GitHub Pages - id: deployment - uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore index 7cf5fad..218ef1e 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,9 @@ dist/ # test / tooling caches .vite/ *.tsbuildinfo + +# Cloudflare: `wrangler pages dev` state, build output, and .dev.vars secrets +.wrangler/ +.dev.vars +!.dev.vars.example + diff --git a/AGENTS.md b/AGENTS.md index 3b8cd84..328f7db 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,8 +12,9 @@ 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 # 99 tests, ~14s npm run lint # tsc --noEmit → 0 errors +npx wrangler pages dev dist # optional: the API in the real Cloudflare runtime ``` `npm run dev:mock` runs the real app against an in-memory Supabase mock @@ -33,9 +34,17 @@ code path your change exercised. - **Firebase is FCM-only.** No Firestore, no Firebase Auth, no Firebase Storage. (`firestore.rules` and `firebase-blueprint.json` at the repo root are historical leftovers — ignore them.) -- **The Express server holds no application data.** It exists only to keep - secrets server-side: Gemini, FCM service account, LiveKit tokens, GitHub - OAuth. See `server.ts`. +- **Production is Cloudflare Pages.** The static site is `dist/`, the API is + `functions/` (Pages Functions), and both deploy from this repo to + . There is no other deploy target to keep in + sync. +- **The API holds no application data.** It exists only to keep secrets + server-side: Gemini, FCM service account, LiveKit tokens, GitHub OAuth. All of + it is `server/api.ts`, written against the Web `Request`/`Response` API so the + exact same file runs on Cloudflare *and* under Express (`server.ts`, used for + `npm run dev`). **Add a route there — never in an adapter.** Nothing in + `server/api.ts` may import a Node built-in (`fs`, `path`, `crypto`, `Buffer`); + Node-only abilities are injected as capabilities (`REPO_FS`). - **Calling:** WebRTC, signalled over Supabase channels, state in `providers/CallProvider.tsx` so a call survives navigation. - **Platform target:** PWA + an Android WebView (TWA) wrapper with an @@ -75,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 @@ -97,7 +140,16 @@ 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 API verifies. Never call the API routes with a bare + `fetch` — you will get a 401. +- Adding a server route? Put it in `server/api.ts` and make sure it bundles for + 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_schema.sql` has no `text`). ### File size @@ -135,7 +187,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 # 99 tests, 7 files npm run test:watch ``` @@ -143,6 +195,7 @@ npm run test:watch |---|---|---| | Mock contract | `dev/mock/__tests__/` | pins PostgREST semantics so the mock cannot silently drift | | Real services | `src/__tests__/chatService.test.ts` | the shipped `ChatService` against seeded data | +| Real API | `src/__tests__/apiRoutes.test.ts` | `handleApiRequest` — auth, CORS/origin guard, body caps, routing | | Real UI | `src/__tests__/app.smoke.test.tsx` | renders ``, drives the login form, asserts the chat list | Rules: @@ -161,16 +214,20 @@ Rules: |---|---| | `npm run build` | ✅ passes | | `npm run dev` / `dev:mock` | ✅ passes | -| `npm test` | ✅ 78/78 | +| `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 | ✅ `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 | -| 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 | +| Cloudflare Pages deploy | ✅ `dist/` + `functions/` → | +| Node self-host path | ✅ `npm run build:all && npm run start` | +| `/api/send-notification`, `/api/upload-file` | ✅ **authenticated** + rate limited + allowlisted (see `authenticate` in `server/api.ts`) | +| 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 | +| 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)**. @@ -195,5 +252,7 @@ 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 | +| [`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 1ce1b2d..4444d9a 100644 --- a/README.md +++ b/README.md @@ -39,9 +39,17 @@ 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. +- `/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. - `/dev`: The mock Supabase (`dev/mock/`) and test setup (`dev/test/`). See [docs/TESTING.md](./docs/TESTING.md). @@ -68,14 +76,31 @@ seeded social graph. Nothing touches the network. cp .env.example .env # fill in VITE_SUPABASE_URL and VITE_SUPABASE_ANON_KEY npm run dev ``` -`.env.example` documents all 22 variables, frontend and server. +`.env.example` documents every variable, frontend and server — including the +ones that live in the Cloudflare Pages dashboard in production. ### 4. Test and build ```bash -npm test # 78 tests +npm test # 99 tests npm run lint # tsc --noEmit -npm run build # vite build + server bundle +npm run build # vite build → dist/ (what Cloudflare Pages builds) ``` +### 5. Deploy + +Cloudflare Pages builds this repository and serves + — `dist/` as the static site and `functions/` +as the API. Build command `npm run build`, output directory `dist`, and the +project's environment variables. Full checklist: +[`docs/DEV_SETUP.md`](./docs/DEV_SETUP.md#deploy--cloudflare-pages). + +```bash +npx wrangler pages functions build # check the API bundles for the edge +npx wrangler pages dev dist # run it locally in workerd on :8788 +``` + +CI (`.github/workflows/ci.yml`) typechecks, tests and bundle-checks every push; +it does not deploy. + --- 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/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/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/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/dev/mock/seed.ts b/dev/mock/seed.ts index 8ff5bcf..87ef799 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: [], }, ]; @@ -368,6 +360,9 @@ export function buildSeed() { id: `p${String(pIdx++).padStart(35, '0')}`, conversation_id, user_id, + // 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), joined_at: daysAgo(28), }); diff --git a/dev/test/setup.ts b/dev/test/setup.ts index c579ebc..23147cc 100644 --- a/dev/test/setup.ts +++ b/dev/test/setup.ts @@ -7,8 +7,12 @@ import {afterEach, beforeEach, vi} from 'vitest'; import {cleanup} from '@testing-library/react'; import {store} from '../mock/store'; +// The API contract tests run in the Node environment (jsdom has no +// Request/Response), so every browser-only shim below is guarded. +const hasDom = typeof window !== 'undefined'; + // --- Browser APIs jsdom does not implement --------------------------------- -if (!window.matchMedia) { +if (hasDom && !window.matchMedia) { window.matchMedia = ((query: string) => ({ matches: false, media: query, @@ -30,16 +34,18 @@ class MockObserver { (globalThis as any).IntersectionObserver = (globalThis as any).IntersectionObserver || MockObserver; (globalThis as any).ResizeObserver = (globalThis as any).ResizeObserver || MockObserver; -if (!window.scrollTo) window.scrollTo = (() => {}) as any; -if (!Element.prototype.scrollIntoView) Element.prototype.scrollIntoView = function () {}; +if (hasDom) { + if (!window.scrollTo) window.scrollTo = (() => {}) as any; + if (!Element.prototype.scrollIntoView) Element.prototype.scrollIntoView = function () {}; +} -if (!window.HTMLMediaElement.prototype.play) { +if (hasDom && !window.HTMLMediaElement.prototype.play) { window.HTMLMediaElement.prototype.play = (() => Promise.resolve()) as any; window.HTMLMediaElement.prototype.pause = (() => {}) as any; } // getUserMedia is used by the camera + call screens. -if (!navigator.mediaDevices) { +if (hasDom && !navigator.mediaDevices) { Object.defineProperty(navigator, 'mediaDevices', { value: { getUserMedia: () => Promise.reject(new Error('no camera in tests')), @@ -64,5 +70,5 @@ beforeEach(() => { }); afterEach(() => { - cleanup(); + if (hasDom) cleanup(); }); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f89627a..cb30863 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -15,19 +15,59 @@ actually reachable. Supabase JS │ │ fetch('/api/…') ▼ ▼ ┌──────────────────┐ ┌──────────────────────────┐ - │ Supabase │ │ Express (server.ts) │ - │ Postgres │ │ /api/grix-ai → Gemini│ - │ Realtime (WS) │ │ /api/send-notif → FCM │ - │ Auth │ │ /api/livekit-token │ - │ Storage │ │ /api/upload-file→catbox │ - └──────────────────┘ │ /api/github/* → proxy │ + │ Supabase │ │ Cloudflare Pages │ + │ Postgres │ │ Functions (functions/) │ + │ Realtime (WS) │ │ /api/grix-ai → Gemini│ + │ Auth │ │ /api/send-notif → FCM │ + │ Storage │ │ /api/livekit-token │ + └──────────────────┘ │ /api/upload-file→catbox │ + │ /api/github/* → proxy │ └──────────────────────────┘ ``` -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 +The API layer 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. +### One API, two runtimes + +`server/api.ts` is the whole API and is written against the Web +`Request`/`Response` API. Two thin adapters reach it: + +``` +functions/api/[[path]].ts ─┐ +functions/auth/[[path]].ts ─┤→ server/api.ts (routing, auth, limits, routes) +server.ts ─────────────────┘ +``` + +- **Cloudflare Pages Functions** run it in production + () — `dist/` is the static site, `functions/` + is the API, and both deploy from this repo on every push. +- **Express** (`server.ts`) runs it for `npm run dev` / `npm run dev:mock` and + for optional self-hosting. It converts the incoming Express request into a + Fetch `Request` and streams the Fetch `Response` back — nothing else. + +Because the edge has no filesystem, the repository-browser's "Sync Tool" +(`/api/github/list-files`, `/api/github/get-file-content`) needs a capability the +Node adapter injects (`REPO_FS`) and answers `501` on Cloudflare. Everything +else — including multipart uploads, FCM's service-account JWT and LiveKit token +signing — runs on both. Pushing secrets into the browser to make the edge happy +was not an option. + +Every `/api` route runs the same security chain, in `handleApiRequest`: + +``` +security headers → cors(allowlist) → origin guard (403 on cross-origin writes) + → rate limit (per IP, per route family) → size-capped body parse + → authenticate (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 @@ -218,10 +258,12 @@ lock/ AppLock, GlobalLock, SetupLock, VerifyLock | Target | Entry | Status | |---|---|---| -| `npm run dev` | `server.ts` → Vite middleware on :3000 | ✅ works | -| `npm run build` | `vite build` + esbuild → `dist/server.cjs` | ✅ works | -| Vercel | `vercel.json` → `server.ts` | ✅ fixed — the duplicate server was deleted | -| GitHub Pages | `.github/workflows/deploy.yml` | ⚠️ needs `VITE_BASE_URL=/grixchat/` | +| **Cloudflare Pages** (production) | `dist/` + `functions/` | ✅ | +| `npm run dev` / `dev:mock` | `server.ts` → Vite middleware on :3000 | ✅ works | +| `npm run build` | `vite build` → `dist/` (this is what Pages builds) | ✅ works | +| `npm run build:server` | esbuild → `dist/server.cjs` for self-hosting | ✅ works | +| `wrangler pages dev dist` | Local workerd runtime on :8788 | ✅ same code as production | +| `.github/workflows/ci.yml` | typecheck + test + bundle check | ✅ no deploy step, by design | | Android TWA/WebView | external wrapper, not in this repo | — | -Details and fixes: **[DEV_SETUP.md](./DEV_SETUP.md#deploy-targets)**. +Details: **[DEV_SETUP.md](./DEV_SETUP.md#deploy--cloudflare-pages)**. diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index bb4fe98..cf7e37a 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 # 99 tests, 7 files, ~14s — includes a real login→chat-list render npm run lint # tsc --noEmit → 0 errors npm run build # production bundle ``` @@ -57,33 +57,47 @@ All three currently pass. | Check | Result | |---|---| | `npm run lint` | ✅ 0 errors | -| `npm test` | ✅ 78/78 | +| `npm test` | ✅ 99/99 | | `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 | -| Vercel deploy | ✅ fixed (`vercel.json` → root `server.ts`) | -| GitHub Pages deploy | ⚠️ needs `VITE_BASE_URL=/grixchat/` | +| Unauthenticated API routes | ✅ **0** — every `/api` route verifies a Supabase JWT (credential-free local mock excepted) | +| Notifications inbox | ✅ has a write path (`services/db/notificationService.ts`) | +| Cloudflare Pages deploy | ✅ `dist/` + `functions/` → | +| Edge compatibility | ✅ the API bundles for workerd with no Node built-ins | +| CI | ✅ typecheck + test + Functions bundle check + 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 `/api` routes verify a Supabase JWT. That means `VITE_SUPABASE_URL`, +`VITE_SUPABASE_ANON_KEY` (and the rest of `.env.example`) have to exist as +**environment variables on the Cloudflare Pages project** — 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 are per-isolate on the edge -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`. +The limiter in `server/api.ts` counts in memory, so on Cloudflare the real quota +is spread across however many isolates are warm. Treat it as a speed bump; add a +native Cloudflare Rate Limiting Rule on `/api/*` for the real ceiling. + +### 3. The GitHub Sync Tool is Node-only + +`/api/github/list-files` and `/api/github/get-file-content` read the checked-out +repository, which Cloudflare has no filesystem for. They answer `501` on the +edge and work under `npm run dev`. Everything else runs identically on both. + +### 4. Nothing else. Really. + +The notification tables, the reset-password route, the bundle split and the open +endpoints were the outstanding items; each is fixed and covered in +**[KNOWN_ISSUES.md](./KNOWN_ISSUES.md)**. --- @@ -99,6 +113,14 @@ src/ ├── components/ # cross-feature UI: layout/, chat-ui/, common/ └── features/ # 13 domains — see below +server/ +├── api.ts # THE API — runtime-neutral, Web Request/Response only +└── (server.ts at the root is its Node/Express adapter) + +functions/ +├── api/[[path]].ts # Cloudflare Pages Function → server/api.ts +└── auth/[[path]].ts # GitHub OAuth callback → the same router + dev/ ├── mock/ # the mock Supabase (query engine, auth, realtime, rpc, seed) └── test/setup.ts # jsdom polyfills + per-test DB reset @@ -123,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`. @@ -141,12 +172,20 @@ 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 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/`.** 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: + [../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). @@ -164,5 +203,7 @@ 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 | +| [../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 c692029..017cd5d 100644 --- a/docs/DATA_MODEL.md +++ b/docs/DATA_MODEL.md @@ -1,7 +1,18 @@ # 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: [`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 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`. --- @@ -26,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 | @@ -47,8 +58,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)`. @@ -75,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`), @@ -85,7 +97,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`, @@ -95,19 +107,22 @@ 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`. - -### `posts` — `sql/02_posts_and_interactions_schema.sql` +> ✅ 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_schema.sql` already grants +> `INSERT` on `notifications` to `authenticated`, and `UPDATE` to the row owner +> (used to mark notifications read). + +### `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 5c69983..06bd532 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` | **99/99 pass** | | `npm run build` | **exit 0** | | Dev server module graph | **55 modules walked, 0 failures** | | `npm install` | 103 packages removed (7 unused deps) | @@ -94,12 +94,34 @@ part of the 5-tab app. ### ⚠️ `src/server/server.ts` — this also fixed a deploy bug -Two Express servers existed. `vercel.json` deployed `src/server/server.ts`, -which was **missing `/api/grix-ai` and `/api/livekit-token`** — so GrixAI and -calling would have 404'd on Vercel while working locally. +Two Express servers existed. The deploy config of the day pointed at +`src/server/server.ts`, which was **missing `/api/grix-ai` and +`/api/livekit-token`** — so GrixAI and calling would have 404'd in production +while working locally. -Deleting it and repointing `vercel.json` at the root `server.ts` removes the -divergence entirely. `vercel.json` was updated in the same change. +Deleting it and repointing the deploy config at the root `server.ts` removed the +divergence. + +### ⚠️ `vercel.json` and `.github/workflows/deploy.yml` + +Both were deploy targets for hosts that are not used any more, and both were +broken in ways that only showed up after a deploy: + +- `vercel.json` described a Node server that no longer held the only copy of the + API. Keeping it meant maintaining a route table for a platform nothing ships + to. +- The GitHub Pages workflow could never serve the app: `functions/` — the API — + only exists on Cloudflare, so a `github.io` build would have had a dead + backend. Its build step also required `VITE_BASE_URL=/grixchat/` because Pages + serves from a sub-path. + +Deployment is now **Cloudflare Pages** (static `dist/` + `functions/`), and the +API itself moved into `server/api.ts` so the edge and the Node dev server run +the same code. `.github/workflows/ci.yml` replaced the deploy workflow and only +verifies — Cloudflare builds from the repository. + +Removed alongside: `vercel.json` (2 build entries + 9 route rules), +`.github/workflows/deploy.yml`. ## Deleted — non-source files @@ -182,3 +204,91 @@ 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_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) | + +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_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. + +## 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 4834873..f5b637b 100644 --- a/docs/DEV_SETUP.md +++ b/docs/DEV_SETUP.md @@ -50,6 +50,12 @@ Verified: the dev server serves and a `npm run build:mock` bundle contains the mock marker and no real Supabase client. +The mock lives in the **browser** bundle, so it also mocks `auth.getSession()`. +That is what lets `npm run dev:mock` exercise the JWT-protected API routes: +the client attaches its mock session token and the Node API skips verification +in this mode (see `isCredentialFreeMock` in `server/api.ts`). Cloudflare never +takes that path — an edge deployment always verifies. + ### What is seeded 8 users · 5 direct chats · 2 groups · ~28 messages (one of them a real reply, @@ -93,14 +99,23 @@ 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 → 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:** + ```bash cp .env.example .env # fill in the values 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) @@ -115,14 +130,19 @@ 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_IMGBB_API_KEY` | `features/reels/grixtube/TubeUploadScreen.tsx` — ⚠️ see note | +| `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. | -> ⚠️ **`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) @@ -130,19 +150,137 @@ 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` | 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 and first CORS allowlist entry (`https://grixchat.gothwadtech.com`) | +| `ALLOWED_ORIGINS` | extra comma-separated browser origins allowed to call `/api/*` | +| `MOCK_SUPABASE` | Node dev server only: `1` skips JWT verification for the credential-free loop. Ignored on Cloudflare, which always verifies. | +| `NODE_ENV` | Node: `production` serves `dist/`. Also hides the `/api/github/debug` diagnostic route (already hidden on any Pages deployment). | +| `CF_PAGES` | Set to `1` automatically by Cloudflare. The API treats it as "never skip verification here". | +| `PORT` | Node dev server port (default `3000`) | 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. + +--- + +## 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: -> **`VITE_GROQ_API_KEY`** appears in `.env.example` but is read nowhere in the -> codebase. `groq-sdk` is installed and unused. Both are dead. +| Half | Source | What it serves | +|---|---|---| +| Static site | `dist/` (`npm run build`) | The React PWA — `index.html`, hashed assets, `sw.js`, `manifest.json` | +| API | `functions/` (Pages Functions) | Every `/api/*` route plus `/auth/github/callback` | + +There is **one** API implementation: `server/api.ts` is written against the Web +`Request`/`Response` API, `functions/api/[[path]].ts` hands Cloudflare's request +straight to it, and `server.ts` does the same for the Node dev server. Nothing +needs porting between environments, and there is no second server to drift. + +### Project settings + +Cloudflare dashboard → **Workers & Pages → gtwdchat → Settings**: + +| Setting | Value | +|---|---| +| Build command | `npm run build` | +| Build output directory | `dist` | +| Root directory | `/` (repo root) | +| Framework preset | None / Vite | +| 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 +`npx wrangler pages deploy dist` and `npx wrangler pages dev dist` behave the +same as the dashboard build. Only a **build** (`npm run build` → `dist/`) +triggers the Pages build; the Node server bundle is not part of it (see +"Commands" below). + +### Repository files that make the deploy work + +| File | Purpose | +|---|---| +| `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 | +| `public/_headers` | Security headers + cache policy for static assets | +| `public/.well-known/assetlinks.json` | Android TWA verification, served straight from the edge | +| `public/sitemap.xml`, `public/robots.txt` | SEO, pointing at the canonical domain | + +> **No SPA redirect rule on purpose.** Cloudflare serves `index.html` for +> unknown paths natively, and a `/* → /index.html 200` rule is actually turned +> into a **308 permanent redirect** that browsers cache forever. Deep links +> (`/chats`, `/chat/:id`) are verified to return the shell with a `200`. + +### Environment variables + +Pages → **Settings → Environment variables**. Add each one to **Production** +*and* **Preview**; the `VITE_*` half is inlined at build time (a change needs a +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_*` | 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` | *(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 | +| `ALLOWED_ORIGINS` | Optional extra origins | +| `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 +simulated or explicit error rather than crashing. The exception is +authentication: without `VITE_SUPABASE_URL` + `VITE_SUPABASE_ANON_KEY` on the +server side, `/api/*` answers `503` on purpose. + +> **Secrets named `VITE_*` are still public.** They are baked into the browser +> bundle. The anon key is designed for that; nothing else belongs there. + +### Custom domain + +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 + +```bash +npm run build # produces dist/ +npx wrangler pages functions build # type/bundle-check the Functions +npx wrangler pages dev dist # real workerd runtime on :8788 +``` + +`wrangler pages dev` runs the **same** `functions/` code Cloudflare runs, on the +real workerd runtime. A plain `.env` is only read by the Node dev server, so +edge secrets go in `.dev.vars` (gitignored): + +```bash +cp .dev.vars.example .dev.vars # MOCK_SUPABASE=1 works with zero credentials +npx wrangler pages dev dist --binding APP_URL=http://localhost:8788 +``` + +### GitHub Actions + +`.github/workflows/ci.yml` typechecks, tests and builds on every push. It does +**not** deploy — Cloudflare Pages builds from the repository itself. To deploy +from Actions instead, add `cloudflare/wrangler-action` with a +`CLOUDFLARE_API_TOKEN` secret and run `wrangler pages deploy dist`. --- @@ -150,11 +288,12 @@ also means **a misconfigured deploy looks like it is working.** | Port | What | Where it is set | |---|---|---| -| **3000** | Express + Vite middleware (the app) | `server.ts:797` — hardcoded | +| **3000** | Node dev server (Express + Vite middleware) | `server.ts` — `PORT` env | +| **8788** | `wrangler pages dev` (local Cloudflare runtime) | `--port` flag | | 24678 | Vite HMR websocket | Vite default | -The server binds `0.0.0.0`, so it is reachable from other interfaces / preview -proxies. +Both servers bind `0.0.0.0`, so they are reachable from other interfaces and +preview proxies. --- @@ -162,39 +301,39 @@ proxies. | Command | What it does | |---|---| -| `npm run dev` | Express + Vite, **real** Supabase | -| `npm run dev:mock` | Express + Vite, **mock** Supabase | -| `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 dev` | Node dev server, **real** Supabase | +| `npm run dev:mock` | Node dev server, **mock** Supabase (no credentials) | +| `npm run build` | `vite build` → `dist/`. **This is what Cloudflare Pages runs.** | +| `npm run build:server` | esbuild bundle of `server.ts` → `dist/server.cjs` (self-hosting / `npm run start`) | +| `npm run build:all` | both of the above | +| `npm run build:mock` | static bundle wired to the mock (demoing without a backend) | +| `npm run start` | serve `dist/` + the API from `dist/server.cjs` (needs `build:server`) | +| `npm run test` | `vitest run` — 99 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 | +| `npm run lint` | `tsc --noEmit` — **0 errors** | +| `npm run preview` / `preview:mock` | `vite preview` — static files only, **no API** | + +> `npm run build` deliberately does **not** emit `dist/server.cjs`. Pages +> uploads all of `dist/`, so a server bundle (and its sourcemap) would be +> publicly downloadable. Use `build:all` when you actually self-host. --- ## Deploy targets -### Vercel (`vercel.json`) +### Cloudflare Pages — production -⚠️ **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. +See the section above. This is the only place the site is served from. -### GitHub Pages (`.github/workflows/deploy.yml`) +### Node host — optional self-hosting -⚠️ **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. +`npm run build:all && npm run start` serves `dist/` plus the same `/api` routes +from a single Node process, with the same endpoints and the same security +chain. Useful for running the API closer to a database, or for local +end-to-end testing with real Supabase credentials. Set the server-side +variables from the table above in the host's environment. -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. +### Android (TWA / WebView) ### Android (TWA / WebView) diff --git a/docs/EGRESS_AUDIT.md b/docs/EGRESS_AUDIT.md new file mode 100644 index 0000000..78754f9 --- /dev/null +++ b/docs/EGRESS_AUDIT.md @@ -0,0 +1,268 @@ +# 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/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 +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/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 | +| 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 | +| **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 | + +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/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_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 `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 + 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 + `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 `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 +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 ce19556..b677951 100644 --- a/docs/KNOWN_ISSUES.md +++ b/docs/KNOWN_ISSUES.md @@ -1,243 +1,475 @@ # 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 +**Legend:** ✅ fixed in code · ⚠️ partly fixed · ❌ still open · 🧑 needs a +human step (SQL run, secret, or a product decision) + --- -## 🔴 P0 — Security +## 🧑 Read this first — what code cannot do -### 1. `/api/send-notification` is an open push relay +The app is deployed on **Cloudflare Pages** (): +`dist/` is the static PWA, `functions/` is the API. Everything that could be +fixed from the repository alone **has been**; these tasks need the Cloudflare +dashboard, Supabase, or a decision. -`server.ts:153`. No authentication, no origin check, no rate limit. +| # | 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`, `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 — 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. | -```bash -curl -X POST https:///api/send-notification \ - -H 'Content-Type: application/json' \ - -d '{"tokens":[""],"title":"Alert","body":"Tap here"}' -``` +Optional: set `ALLOWED_ORIGINS=https://your-domain.tld,https://your-other.tld` +(comma-separated) to extend the CORS/origin allowlist beyond same-origin + +`APP_URL`. -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. +--- -**Fix:** verify a Supabase JWT (`Authorization: Bearer`) and confirm the caller -participates in the conversation; add a per-IP rate limit. +## ✅ P0 — Security (all fixed) -### 2. `/api/upload-file` is an open file host +### 1. `/api/send-notification` was an open push relay — ✅ FIXED -`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. +It is no longer a token relay at all: -**Fix:** require auth; cap size per media type; rate limit; preferably upload -straight to Supabase Storage with a signed URL. +- **Auth:** requires `Authorization: Bearer `, verified + with `supabase.auth.getUser()` (`server/api.ts` → `authenticate`). +- **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', [...])`. -### 3. No server hardening at all +Client side: `pushNotificationService.ts` and `NotificationsSettingsScreen.tsx` +go through the new `src/lib/apiClient.ts`, which attaches the session token. -``` -grep -n "cors\|helmet\|rate" server.ts → 0 results -``` +### 2. `/api/upload-file` was an open 100 MB file host — ✅ FIXED -No CORS policy, no security headers, no rate limiting on any route. +- Auth required (`authenticate`). +- **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`). -**Fix:** `helmet()` + an explicit `cors({origin})` allowlist + `express-rate-limit`. +> No caller in this repository uses this route. It is kept for the Android +> WebView wrapper, but now requires a signed-in session. ---- +### 3. No server hardening at all — ✅ FIXED -## 🟠 P1 — Correctness +`server.ts` now runs: -### 4. Nothing writes to `notifications` +| Layer | What | +|---|---| +| Security headers | Applied by the API itself (they are part of the `Response`), and by `public/_headers` for static files: nosniff, referrer policy, CORP `cross-origin`. There is deliberately no `X-Frame-Options`/CSP — the Android WebView (TWA) wrapper embeds the app and the popup flow needs `window.opener`. | +| CORS | An origin is reflected only when it is same-origin with the request or allowlisted (`APP_URL` + `ALLOWED_ORIGINS` + localhost). Unknown origins get no CORS headers at all. | +| 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. | +| Rate limiting | API 60/min · notifications 20/min · uploads 8/min · AI 20/min, per IP (`server/api.ts`). The counter is in-memory, so on Cloudflare the effective ceiling is per isolate — add a native Cloudflare Rate Limiting Rule on `/api/*` if you need a hard global quota. The client IP is read from `cf-connecting-ip` / `x-forwarded-for`, so it is the real caller behind the proxy. | +| 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. -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**: +--- -``` -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) -``` +## 🟠 P1 — Correctness -`grep -rn "from('notifications')" src | grep -c insert` → **0** +### 4. Nothing wrote to `notifications` — ✅ FIXED + +New `src/services/db/notificationService.ts` is the single write path +(`create`, `notifyFollow`, `notifySystem`). It is wired into every place a +connection is created: + +- `features/profile/UserProfileScreen.tsx` — send request, and accept request +- `features/chat/MessageRequestsScreen.tsx` — accept +- `services/db/transactionQueueService.ts` — the offline follow worker + +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). + +### 5. `notifications` column mismatch — ✅ FIXED + +`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. + +### 6. `users.saved_posts` was not in the schema — ✅ FIXED + +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/`. + +### 7. `call_candidates` is defined but never used — ❌ STILL OPEN (needs SQL) + +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 + +`/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`. -So the notification screens will always be empty. +--- -**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. +## 🟡 P2 — Deploy & CI (all fixed) -### 5. `notifications` column mismatch +### 9. Deploy target could not serve the app — ✅ FIXED (now Cloudflare Pages) -`sql/01_core_schema.sql:157` defines `title` and **`content`**. -`NotificationsScreen.tsx:118` reads **`notif.text`**. +The site is served by **Cloudflare Pages** at +: `dist/` is the static PWA and `functions/` +is the API (Pages Functions). What that changed: -```tsx -{notif.text} -``` +- `vercel.json` is gone — it described a Node host nothing deploys to any more. + The old GitHub Pages workflow is gone too: it could never have worked, because + `functions/` (the API) exists only on Cloudflare, so a `github.io` build would + have shipped a dead backend. CI (`.github/workflows/ci.yml`) now verifies only; + Cloudflare builds from the repository. +- **No SPA rewrite rule.** Cloudflare serves `index.html` for unknown paths + natively. A `/* → /index.html 200` rule is turned into a **308 permanent + redirect** (browsers cache it forever), so it is deliberately absent — + `public/` ships `_headers` and `_routes.json` instead. Deep links (`/chats`, + `/chat/:id`) were verified against workerd to return the shell with a `200`. +- `public/_routes.json` scopes Functions to `/api/*` and `/auth/*`, so static + traffic never spins up a Function. -Whatever write path you add must agree with the reader and the schema. Pick -`content` (matches the migration) and change the reader. +### 10. The API had to run somewhere Cloudflare can too — ✅ FIXED -### 6. `users.saved_posts` is not in the schema +The old `server.ts` was Express + `axios` + `google-auth-library` + `multer` + +`livekit-server-sdk`: none of that runs on Workers. Rather than maintain two +implementations, the routes moved to **`server/api.ts`**, written against the Web +`Request`/`Response` API, and two thin adapters reach it: -`services/db/userProfileService.ts:192` reads and writes it; `sql/` does not -define it. Either add the column or drop the field. +| Adapter | Used by | +|---|---| +| `functions/api/[[path]].ts`, `functions/auth/[[path]].ts` | Cloudflare Pages (production) | +| `server.ts` | `npm run dev` / `dev:mock`, optional self-hosting | -### 7. `call_candidates` is defined but never used +That removed five Node-only dependencies (`axios` server-side, +`google-auth-library`, `multer`, `form-data`, `livekit-server-sdk`) plus +`helmet`/`cors`/`express-rate-limit` — FCM signing, LiveKit tokens, multipart +parsing, security headers, CORS and rate limiting are all Web-platform code now, +so the behaviour cannot drift between the two runtimes. `npx wrangler pages +functions build` (run in CI) proves the bundle has **zero Node built-ins**. -`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. +The one genuinely Node-only feature — the GitHub Sync Tool reading the source +tree — is injected as a capability (`REPO_FS`) and answers `501` on the edge +instead of pretending to work. -### 8. Password reset has no path +### 11. CI did not typecheck or test — ✅ FIXED -```tsx -// App.tsx -} /> -``` +`.github/workflows/ci.yml` runs `npm run lint`, `npm test`, a Functions bundle +check and `npm run build` on every push and PR. No deploy step: Cloudflare Pages +builds the repository itself, and deploying from two places is how you ship a +stale bundle. -`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. +`npm run build` also stopped emitting `dist/server.cjs`: Pages uploads all of +`dist/`, so a server bundle (and its sourcemap) would have been publicly +downloadable. `npm run build:server` / `build:all` do that for self-hosting. --- -## 🟡 P2 — Deploy & CI - -### 9. GitHub Pages base path +## 🟡 P2 — Performance (all 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. +### 12. Main bundle was 1.14 MB — ✅ FIXED -**Fix:** add to the workflow's Build step: +`build.rollupOptions.output.manualChunks` splits the heavyweights. With +credentials configured, the build now emits: -```yaml -env: - VITE_BASE_URL: /grixchat/ ``` - -or add a `CNAME` for a custom domain. - -> *Static analysis — an actual Pages deploy was not executed.* - -### 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 +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) ``` -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. +### 13. `emoji-picker-react` statically imported twice — ✅ FIXED ---- +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. -## 🟡 P2 — Performance +### 14. ~350 `console.*` calls shipped to production — ✅ FIXED -### 12. Main bundle is 1.14 MB (317 KB gzip) +`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. -``` -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 -``` - -`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` is statically imported twice +## 🔴 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 + +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. + +- **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. +- **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 + `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). -`ChatMessageMenu.tsx:18` and `EmojiPickerMenu.tsx:3`. A heavy dependency pulled -into the chat chunk. +--- -**Fix:** `React.lazy`. +## 🟠 P0 — Egress (fixed in code; SQL is a 2-minute step) -### 14. 350 `console.*` statements ship to production +### 19. 5 GB of Supabase egress in a month with 2–3 users — ✅ FIXED in code, 🧑 needs one SQL run -`grep -rn "console\.\(log\|warn\|error\)" src | wc -l` → **350** (was 499). +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. -**Fix:** `esbuild.drop: ['console']` for the client build, or a logger that -no-ops in production. +- **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/02_functions_realtime_storage.sql` (row F above). +- **Analysis, measurements, database-foundation mistakes, caching plan:** + [EGRESS_AUDIT.md](./EGRESS_AUDIT.md). --- ## 🟢 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 +``` + +Then prefer those row types over hand-written shapes. -**Fix:** `npx supabase gen types typescript --project-id > src/types/database.types.ts` +### 17. Giant files — ❌ STILL OPEN -### 17. Giant files +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 +### 18. Stale reference in a live file — ✅ FIXED -`features/chat/SearchUserScreen.tsx:73` renders `reel.likes_count` but the -screen only queries `users` — a leftover variable from the Reels feature. +`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: + +- 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. --- +## 🔵 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 `