Skip to content

Run the app on Cloudflare Pages + fix the code-only KNOWN_ISSUES items - #2

Merged
GothwadTech merged 11 commits into
mainfrom
arena/75eeb86b-grixchat
Oct 11, 2026
Merged

GothwadTech merged 11 commits into
mainfrom
arena/75eeb86b-grixchat

Conversation

@GothwadTech

@GothwadTech GothwadTech commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

Implements every issue in docs/KNOWN_ISSUES.md that can be fixed from the repository alone. The three items that need SQL / secrets / a decision are listed at the top of that file for you.

Security (P0 — all of it)

Route Before After
/api/send-notification open relay to any FCM token Supabase JWT required; recipients + title derived from the DB; 200-char body; 20 req/min
/api/upload-file anonymous, 100 MB/file, any MIME auth required; MIME allowlist; 15/25/50 MB caps; 8 req/min
/api/livekit-token anonymous token minting auth + participant check, identity from the session
/api/grix-ai anonymous, burns Gemini quota auth required, 20 req/min
everything no headers, no CORS, no limits helmet + CORS allowlist + origin guard (403) + express-rate-limit on every surface

Request bodies are now parsed per route (256 kB default instead of a blanket 50 MB), and malformed/oversized bodies return JSON errors.

Correctness (P1)

  • notifications had no write path → services/db/notificationService.ts, wired into follow requests, accepted requests and the offline follow worker. 6 new tests.
  • Readers use the content column the SQL schema defines (text was never a column).
  • users.saved_posts (never in the schema) dropped from code + mock.
  • /forgot-password now renders the working reset form instead of a dead redirect.

Deploy & CI (P2)

  • GitHub Pages builds with VITE_BASE_URL=/grixchat/.
  • CI runs npm run lint + npm test before the build.
  • VITE_* values wired from Actions secrets — and a build-time warning for a nasty silent trap found on the way: without VITE_SUPABASE_URL/ANON_KEY, Rollup constant-folds the null client and tree-shakes the entire Supabase SDK out of the bundle.

Performance (P2)

  • manualChunks: entry chunk 1,148 kB → 170 kB; livekit/emoji/supabase/react now load on demand.
  • emoji-picker-react is React.lazy (own 309 kB chunk).
  • console/debugger dropped from production builds.

Quality (P3)

  • Dead Reels/Tube UI and the stale reel.likes_count removed from SearchUserScreen, /search-user route reconnected, sitemap no longer advertises deleted routes.

Supabase setup — re-runnable (P0)

The SQL setup used to start with DROP TABLE ... CASCADE, which silently wiped every
message and profile of a live project with zero errors (the whole file ran green).
It is now non-destructive: re-running sql/ on an existing project creates what is
missing, updates what changed, and never drops data. Verified against a real
PostgreSQL for three scenarios — fresh install, re-run on seeded data, and upgrade
from the old install shape — plus behaviour checks on the history cap, the preview
trigger, read-marker RLS isolation and get_unread_counts().

Two foundations were wrong and are fixed in the same pass:

  • the auth trigger and the preview trigger both fired on every message INSERT and
    both wrote conversations (double work, double realtime traffic) — only one trigger
    is created now, and the old one is dropped;
  • the last-message picks are tie-broken by id, so equal timestamps resolve to a
    deterministic preview.

Layout follows the repo house rules (sql/00_master_instructions.md): one MD runbook,
then numbered files that grow to 600–1000 lines before the next one starts, each with
a short COVERS: header — 01_schema.sql (710 lines) and
02_functions_realtime_storage.sql (843 lines). The generated one-file bundle and
scripts/build-sql-bundle.mjs were deleted (with two files it was a sync surface for
no benefit). src/__tests__/sqlMigrations.test.ts enforces all of this in CI.

Verification

npm run lint   → 0 errors
npm test       → 128/128 (13 files)
npm run build  → clean, no chunk-size warning
sql/           → fresh + re-run + old-shape upgrade verified on a real PostgreSQL
                 (data intact, objects stable, no "already exists" errors)

Task 6 — calling, presence/typing and stories (2026-10-11)

The call system was the headline complaint ("work nahi karta"), so it was traced
from the ring to the database row instead of patched at the surface.

Calling

  • The call screen re-dialled the peer the instant a call ended (activeCall → null
    re-triggered its initiate effect). Ringing is now once per visit; an already-running
    call is adopted.
  • The fake transport is gone: without LiveKit credentials the fallback used to be a
    1.8 s timer that marked both phones "connected" with no media. The fallback is
    now a real peer-to-peer RTCPeerConnection signalled over the call-rtc:<callId>
    broadcast topic (caller offers after the receiver's hello, ICE buffered until the
    remote description lands, connected only from the actual connection). LiveKit is
    still used whenever it is configured.
  • Timeouts agreed: one RING_TIMEOUT_MS = 45 s for the ring, the P2P connect clock
    starts with the offer (an unanswered call rings instead of erroring at 30 s), a
    20 s watchdog ends a call that was answered but never got media, and the zombie
    sweep no longer force-closes calls at 40 s while the caller is still ringing.
  • Every transport-driven teardown finalises the calls row through one idempotent
    helper: no row is left accepted forever, and only one side writes the "call
    ended" chat log. A failed accept closes as error.
  • Call history queried .eq('status','ended') only, so declined (rejected) and
    interrupted (error) calls were invisible — fixed in both history loaders.
  • Camera flip / screen share hand the UI a fresh MediaStream (the preview kept the
    old track), the browser's own "Stop sharing" clears the button, and Switch Camera
    no longer looks enabled on a voice call.
  • The duplicate incoming-call card is deleted for good: it wrote the status denied,
    which the calls.status CHECK constraint rejects — declining from that card never
    reached the database.

Presence & typing

  • One Realtime Presence channel owns the live roster (grix-presence); the legacy
    online-users channel (which only ever watched yourself) is removed. Search,
    discover, message requests and the forward sheet read the roster through
    useLivePresence instead of trusting is_online; chat list/header/profile use the
    same helper, so all surfaces agree. A closed tab goes offline instantly instead of
    after the fallback window.
  • Typing: one ref-counted broadcast topic per conversation shared by the chat header
    and its chat-list row, typing… in the header, explicit false on
    send/blur/unmount/tab-hidden, 6 s receiver TTL. Zero database rows.

Stories (the only content feature left) — bounded select (24 h, audience-scoped,
120-row cap) with unseen-first rings, duration-aware progress, one view per story per
viewer enforced by auth.uid() in view_story, mute wired to the music track, and
exits that land on /stories.

Test infrastructure — dev/mock/realtime.ts parsed in.(a,b) filters with a
regex that stripped backslashes instead of parentheses, so no in. filter ever
matched: the chat-list realtime patch could not fire in tests or dev:mock. Fixed,
which is what made the egress regression test green again.

New tests: callFlow.test.tsx (incoming ring → decline writes rejected; answer
writes accepted + one chat log; end closes the row and does not re-dial),
callSignaling.test.ts (ringing is not a failure; the answered-but-dead handshake
fails honestly), presenceTyping.test.ts (roster + typing semantics).

Security (P0)
- /api/send-notification: requires a verified Supabase JWT, derives the
  recipients and the notification title from the database, caps the body and
  is rate limited. It is no longer an open push relay.
- /api/upload-file: auth required, MIME allowlist, per-media-type size caps
  (15/25/50 MB instead of a 100 MB free-for-all), 8 req/min.
- Server hardening: helmet, cors allowlist + origin guard (403 on
  cross-origin writes), express-rate-limit on every surface, per-route JSON
  limits (256 kB default), JSON 404/400/413 handlers, trust proxy.
- /api/livekit-token now verifies the caller participates in the call and
  takes the token identity from the session; /api/grix-ai requires auth;
  /api/github/debug is dev-only; FCM token cleanup no longer scans users.

Correctness (P1)
- notifications finally has a write path (services/db/notificationService.ts),
  wired into follow requests, request accepts and the offline worker.
- Readers use the `content` column the schema actually defines.
- users.saved_posts removed from code and mock (the column never existed).
- /forgot-password renders the reset form instead of bouncing to /login.

Deploy & CI (P2)
- Pages builds with VITE_BASE_URL=/grixchat/; CI typechecks and tests first.
- VITE_* values wired from Actions secrets, plus a loud build-time warning for
  the silent trap where missing Supabase creds tree-shake the whole SDK out.

Performance (P2)
- manualChunks: entry chunk 1.14 MB -> 170 kB.
- emoji-picker-react is lazy (own chunk, loaded on tap).
- console/debugger dropped from production builds.

Quality (P3)
- Removed the dead Reels/Tube leftovers in SearchUserScreen, reconnected the
  /search-user route, and fixed the sitemap advertising deleted routes.

Verification: npm run lint 0 errors · npm test 85/85 (6 files) · npm run build
clean. Remaining items need SQL, secrets or a product decision - see the top of
docs/KNOWN_ISSUES.md.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Deploying gtwdchat with  Cloudflare Pages  Cloudflare Pages

Latest commit: cc1966e
Status: ✅  Deploy successful!
Preview URL: https://7f401adc.gtwdchat.pages.dev
Branch Preview URL: https://arena-75eeb86b-grixchat.gtwdchat.pages.dev

View logs

GothwadTech and others added 4 commits October 11, 2026 01:41
Production is Cloudflare Pages (https://grixchat.gothwadtech.com), not a
Node host: `dist/` is the static PWA and `functions/` is the API. That
required the API to stop being Express-shaped.

The API is now one runtime-neutral file
----------------------------------------
`server/api.ts` holds every route and is written against the Web
`Request`/`Response` API. Two thin adapters reach it:

  functions/api/[[path]].ts, functions/auth/[[path]].ts  → Cloudflare Pages
  server.ts                                               → Node dev / self-host

`npx wrangler pages functions build` compiles the whole API for workerd
with zero Node built-ins (no `nodejs_compat`), so nothing is ported twice
and the two runtimes cannot drift. Verified on the workerd runtime:
health, routing, 404/400/413, CORS + origin guard, MIME rejection, and
deep links returning the SPA shell with a 200.

Removed the Node-only dependencies this made redundant: express shape
stayed, but helmet, cors, express-rate-limit, multer, form-data,
google-auth-library, @google/genai and livekit-server-sdk are gone
(jose signs both the LiveKit HS256 token and the FCM/Google
service-account assertion). The one genuinely Node-only feature — the
GitHub Sync Tool reading the source tree — is injected as a `REPO_FS`
capability and answers 501 on the edge instead of pretending to work.

Deleted: vercel.json, the GitHub Pages workflow
----------------------------------------------
Both targeted hosts nothing ships to. `.github/workflows/ci.yml`
replaces the deploy workflow and only verifies (typecheck, 99 tests,
Functions bundle, build) — Cloudflare Pages builds the repository.

Also for the edge
-----------------
- public/_headers  — security headers + immutable caching for hashed assets
- public/_routes.json — Functions only for /api/* and /auth/*, so static
  traffic never wakes a Function
- public/.well-known/assetlinks.json — Android TWA verification
- sitemap/robots, canonical + OG tags and the in-app legal links all point
  at grixchat.gothwadtech.com instead of the old workers.dev host
- `npm run build` no longer emits dist/server.cjs / .map: Pages uploads all
  of dist/, so a server bundle would have been publicly downloadable.
  `npm run build:server` / `build:all` keep that for self-hosting.
- mock mode can never silence auth on the edge (`CF_PAGES` is set on every
  Pages deployment, and the debug route 404s there too)

New coverage: src/__tests__/apiRoutes.test.ts (14 cases) exercises the
shared handler directly — routing, CORS/origin guard, body caps and the
auth decision. docs/ and AGENTS.md now describe Cloudflare Pages as the
only deploy target.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
The PR's Cloudflare Pages check links to the project `gtwdchat`, so
wrangler.toml's `name` and every doc that told you to look under
'Workers & Pages → grixchat' were pointing at the wrong project. The
custom domain is unchanged (grixchat.gothwadtech.com).

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
The new 'Build Pages Functions' step failed on the runner while passing
locally: wrangler@4.149.0 declares engines.node >= 22.0.0 and exits
non-zero on Node 20, which the workflow pinned. Move CI to Node 22 and
recommend NODE_VERSION=22 for the Pages build so the toolchain matches
whatever installs the devDependencies.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
The v4 pair targets Node 20, which the runners now force onto Node 24 and
flag as deprecated on every run. No behaviour change.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
@GothwadTech GothwadTech changed the title Fix the code-only items from docs/KNOWN_ISSUES.md Run the app on Cloudflare Pages + fix the code-only KNOWN_ISSUES items Oct 11, 2026
GothwadTech and others added 6 commits October 11, 2026 02:29
5 GB in a month with 2-3 active users was never the messages, it was the
reaction to them: every message INSERT *and* every read receipt row made each
open client re-run the whole conversation list (6 queries, ~127 KB, no
debounce, users(*) per participant, plus a separate newest-messages query).

Client (0 bytes per message now):
- useConversations patches the list row straight from the Realtime payload
  (preview, time, order, unread); one debounced structural refetch on
  mount/focus/structural changes, one channel instead of one per chat.
- Conversation list = 1 round trip with CONVERSATION_LIST_SELECT: no users(*),
  no message rows. Measured 41 KB vs 127 KB before.
- Read receipts write one row (conversation_participants.last_read_at) instead
  of one UPDATE per unread message; legacy path bounded by the last marker.
- follows cached for 5 min; presence heartbeat 60s -> 5min; profile write
  throttle 45s -> 4min; photos downscaled to 1600px/JPEG 0.82 and stored with a
  1-year immutable cache; TabBottom unread scan capped at 500 rows.

Database (user-run, idempotent): sql/09_egress_optimizations.sql adds the read
marker + the RLS UPDATE policy it needs (RLS is on and no UPDATE policy
existed, so the write would have silently changed 0 rows), the last_message*
sync trigger, REPLICA IDENTITY fixes (FULL only where a filtered DELETE must
reach clients), indexes, an optional unread-count RPC and a retention pruner.
Verified against a real Postgres: applies clean, re-runs clean, trigger fast
and slow paths, RLS isolation, prune.

Docs: docs/EGRESS_AUDIT.md (measurements, ranked causes, six plus two
database-foundation mistakes incl. the world-readable users table and the
missing UPDATE policy, caching plan, maintenance rules); AGENTS.md rules "a
Realtime event patches state, never triggers a list-wide query" and "narrow
selects, always"; KNOWN_ISSUES hand-off rows F/G.

Tests: src/__tests__/egressBudget.test.ts (query stays narrow, message-free and
under 48 KB) and src/__tests__/egressRealtime.test.tsx (an incoming message
patches the visible list with zero list queries). 104/104 green.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
…pe the database

`01_core_schema.sql` opened with `DROP TABLE IF EXISTS public.users CASCADE;`
and the same for every other core table (`02` and `03` did it for posts and
tickets). Since the documented flow is "run these in order", re-running the
setup to apply a schema update — the normal thing to do — silently deleted every
user, message, conversation, post and ticket, while reporting zero errors.

Now, for both supported scenarios:
  * new fork + new Supabase project -> paste sql/grixchat_full_setup.sql, done
  * existing project -> paste the same file again: missing tables/columns/
    indexes/constraints/buckets are created, policies and functions are
    re-created so updates apply, existing rows are never touched

- 01/02/03: no drops; CREATE TABLE IF NOT EXISTS + ADD COLUMN IF NOT EXISTS for
  every column an older install may lack, missing constraints added (guarded),
  every policy re-created via DROP POLICY IF EXISTS, NOT NULL only when the data
  already satisfies it.
- 04: header, SET search_path on both SECURITY DEFINER functions.
- 05: replica identity + publication membership as guarded DO blocks (correct
  values, no dependency on a table still existing), loud warning about the
  40-message history cap and how to skip it.
- 06: header documenting the deliberately permissive storage policies.
- 09: call_candidates joins the identity list; the last_message trigger now
  skips the recompute when a deleted row was not the newest (the 40-message cap
  deletes in batches on every insert).
- New sql/grixchat_full_setup.sql, generated from 01..09 by
  scripts/build-sql-bundle.mjs (`npm run sql:bundle`) — checked in and kept in
  sync, so a forker has one paste.
- sql/00_master_instructions.md rewritten as the runbook: both scenarios, what
  each file does, a verification query block, troubleshooting, and the rules for
  adding migrations.
- Superseded SQL parked in sql/legacy/ (grixchat_latest_db_updates,
  supabase_schema, supabase_posts_schema, supabase_support_tickets_schema,
  db/1_complete_schema, db/2_realtime_and_security) with a README explaining
  that they must not be run — db/1 defined public.users differently and would
  have broken a current project. db/3_webrtc_signaling_architecture.md moved to
  docs/legacy/.
- src/__tests__/sqlMigrations.test.ts guards all of it: no DROP TABLE/TRUNCATE,
  no CREATE without IF NOT EXISTS, every policy dropped before re-created, and
  the bundle in sync.

Verified against a real PostgreSQL: fresh install clean (9/9 files), re-run on
seeded data clean with data intact (users 2->2, messages 2->2, 43 policies,
5 triggers, 2 buckets, 6 published tables unchanged), re-run again after
dropping a column + index + policy + trigger (all restored), the one-file bundle
clean twice, plus behaviour checks on the message cap, preview trigger, read
marker RLS isolation and get_unread_counts(). 111/111 tests green.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
…_storage.sql

The setup had grown to nine files of wildly different sizes (9 to 832 lines) and
the run order was easy to get wrong when forking. Project house rules now:

  1. the .md is written first — detail lives there, never in the SQL
  2. a file grows until it is 600-1000 lines, then the next number starts
  3. every SQL file opens with a short "COVERS:" header

Both files were assembled from the previous content and verified against a real
PostgreSQL (fresh install, re-run on seeded data, upgrade from the old install
shape, repair of missing columns/indexes/policies/triggers) plus behaviour checks
on the history cap, the preview trigger, read-marker RLS isolation and
get_unread_counts().

- 01_schema.sql (710 lines): core tables, later columns, column upgrades,
  constraints, RLS + every policy, indexes, posts/likes/comments, support_tickets.
- 02_functions_realtime_storage.sql (843 lines): auth trigger + RPCs, story RPCs,
  read marker + its RLS UPDATE policy, the single chat-list preview trigger,
  history cap pruners + sweep, get_unread_counts(), prune_old_messages() +
  optional hardening, replica identity, realtime publication, storage buckets,
  self-check.

Fixed on the way:
- 05's insert-only trg_update_conversation_on_message and 09's preview trigger both
  fired on every message INSERT and both wrote `conversations` (double work, double
  realtime traffic). Only one trigger is created now, the old one is dropped, and it
  keeps conversations.updated_at current.
- The last_message picks are tie-broken by id, so equal timestamps resolve to a
  deterministic preview.
- 02's §1 re-creates the auth trigger, so the DROP TRIGGER statements moved into
  the merged file (the first merge attempt lost them and failed on re-run).

Removed: the generated one-file bundle and scripts/build-sql-bundle.mjs (with two
files it was a sync surface for no benefit), plus the `sql:bundle` npm script.

src/__tests__/sqlMigrations.test.ts now enforces all three house rules: no
DROP TABLE/TRUNCATE, idempotent CREATEs, policy dropped before re-created, every
file 600-1000 lines (the newest may still be filling up), a COVERS: header, and no
duplicate preview trigger. 112/112 tests green.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
Calls
- Ring once per visit to /call/:id. The screen re-dialled the peer the
  moment a call ended (`activeCall -> null`), which is why a call felt
  like it kept coming back by itself.
- Delete the fake transport flag and its 1.8s auto-"connect": LiveKit is
  used when configured, otherwise the real peer-to-peer WebRTC session
  (`call-rtc:<callId>` broadcast: hello/offer/answer/candidate/bye).
- One ringing timeout (45s) for both sides; the P2P connect clock now
  starts with the offer, so an unanswered call rings instead of erroring
  at 30s, and a 20s watchdog ends a call that was answered but never got
  media. Zombie sweep moved to 53s (it used to force-close at 40s while
  the caller was still ringing).
- Every transport-driven teardown finalises the `calls` row through one
  idempotent helper, so no row is left `accepted` forever and only one
  side writes the "call ended" chat log. A failed accept closes as error.
- Call history queried only `status = 'ended'`: declined (`rejected`) and
  interrupted (`error`) calls never showed up. Fixed in `useCalls` and
  `CallSyncService`.
- Camera flip / screen share now hand the UI a fresh MediaStream (the
  preview kept the old track), the browser's own "Stop sharing" clears
  the button, and Switch Camera no longer looks enabled on voice calls.
- Removed the duplicate incoming-call card for good (it wrote the status
  `denied`, which the CHECK constraint rejects, so decline never worked).

Presence & typing
- PresenceService is the single live roster (`grix-presence`); remove the
  legacy `online-users` channel AuthProvider opened just to watch itself.
  Search, discover, requests and the forward sheet now read the live
  roster through `useLivePresence` instead of `is_online` alone.
- Typing was already one ref-counted topic per conversation; documented.

Stories
- Unbounded `select('*')` -> bounded columns, 24h cutoff, audience scope,
  120-row cap, one cleanup per session, unseen-first rings, duration-aware
  progress, single view per story, mute wired, exit to /stories.
- `view_story` records `auth.uid()`; a spoofed viewer param is ignored.

Test infrastructure
- `dev/mock/realtime.ts` parsed `in.(a,b)` with a regex that stripped
  backslashes instead of parentheses, so no `in.` filter ever matched and
  the chat-list realtime patch could not fire in tests. Fixed; the egress
  regression test is green again.
- Full suite: 125 tests, 12 files, all passing. `npm run lint`
  (tsc --noEmit) clean, `npm run build` clean.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
`src/__tests__/callFlow.test.tsx` drives the real app against the mock
database with a stubbed media stack: an incoming `calls` row rings the
receiver, Decline writes `rejected` (not the invalid `denied` the deleted
duplicate card used), Answer writes `accepted` plus exactly one chat log,
End Call closes the row as `ended`/not-missed — and no new call is placed
afterwards (the re-dial regression).

Also fixes the now-stale "sandbox mode" wording in the LiveKit probe logs:
the fallback is the peer-to-peer transport, not a simulation.

128 tests / 13 files, all passing.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
@GothwadTech
GothwadTech merged commit 5a5757f into main Oct 11, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant