diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..3979440 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,87 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + backend: + name: Backend + runs-on: ubuntu-latest + timeout-minutes: 20 + services: + postgres: + image: postgres:16 + env: + POSTGRES_USER: grit + POSTGRES_PASSWORD: grit + POSTGRES_DB: grit + ports: ['5432:5432'] + options: >- + --health-cmd "pg_isready -U grit" + --health-interval 5s + --health-timeout 5s + --health-retries 10 + env: + # A throwaway database for migrations and the database tests + DATABASE_URL: postgresql://grit:grit@localhost:5432/grit + DIRECT_URL: postgresql://grit:grit@localhost:5432/grit + SHADOW_DATABASE_URL: postgresql://grit:grit@localhost:5432/grit_shadow + defaults: + run: + working-directory: packages/backend + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - name: Install + working-directory: . + run: npm install --no-audit --no-fund + - name: Generate Prisma client + run: npx prisma generate + - name: Apply migrations + run: npx prisma migrate deploy + - name: Check the schema matches the migrations + run: | + PGPASSWORD=grit psql -h localhost -U grit -d grit -c 'CREATE DATABASE grit_shadow' + npx prisma migrate diff --from-migrations prisma/migrations --to-schema-datamodel prisma/schema.prisma --shadow-database-url "$SHADOW_DATABASE_URL" --exit-code + - name: Format + run: npx prettier --check "src/**/*.ts" "test/**/*.ts" + - name: Lint + run: npx eslint "src/**/*.ts" + - name: Typecheck + run: npx tsc --noEmit -p tsconfig.json + - name: Unit tests + run: npm test + - name: Database tests + run: npm run test:db + - name: Build + run: npm run build && test -f dist/main.js + + mobile: + name: Mobile + runs-on: ubuntu-latest + timeout-minutes: 20 + defaults: + run: + working-directory: apps/mobile + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - name: Install + working-directory: . + run: npm install --no-audit --no-fund + - name: Typecheck + run: npx tsc --noEmit + - name: Lint + run: npx eslint . + - name: Unit tests + run: npm test -- --ci diff --git a/README.md b/README.md index c915eb2..9cb57a2 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,7 @@ The `preview` profile outputs a plain `.apk` (~10–15 min cloud build via EAS). | `progress` | `GET/POST /weight`, `DELETE /weight/:id`, `GET /stats/trends?days=7\|30\|90` | | `ai` | `POST /ai/message` (streamed), `GET /ai/messages`, `GET /ai/nudge` — AI coach | | `notifications` | `GET /notifications`, `GET /notifications/unread-count`, `POST /notifications/read`, `POST/DELETE /notifications/register` (one row per phone), Expo push sending | +| `app` | `GET /health`, `POST /client-errors` (crash reports from the app, no sign-in, throttled) | | `alerts` | Hourly job: challenge results, 8pm streak-at-risk and Sunday 6pm weekly check-in, in each user's local time | **Data models:** User · FoodLog · ActivityLog · Kudos · Habit · HabitLog · Challenge · ChallengeParticipant · AIMessage · Follow · Block · WorkoutPlan · PushDevice · Notification · WeightLog · FavoriteFood @@ -142,6 +143,9 @@ cd packages/backend && npm run start:dev # Unit tests, and database tests against DATABASE_URL (a throwaway Postgres) cd packages/backend && npm test && npm run test:db + +# Mobile lint and unit tests +cd apps/mobile && npm run lint && npm test ``` ### Environment @@ -150,7 +154,9 @@ cd packages/backend && npm test && npm run test:db cp packages/backend/.env.example packages/backend/.env ``` -See [`packages/backend/.env.example`](./packages/backend/.env.example). The app refuses to boot without `DATABASE_URL`, `DIRECT_URL`, `SUPABASE_URL`, `SUPABASE_ANON_KEY`, `AZURE_OPENAI_ENDPOINT` and `AZURE_OPENAI_API_KEY`. `SUPABASE_SERVICE_KEY` and the Upstash vars are not read by the code yet. Optional: `EXPO_ACCESS_TOKEN` (if push security is on for the Expo project) and `PUSH_DISABLED=true` (don't send pushes, e.g. locally). +See [`packages/backend/.env.example`](./packages/backend/.env.example). The app refuses to boot without `DATABASE_URL`, `DIRECT_URL`, `SUPABASE_URL`, `SUPABASE_ANON_KEY`, `AZURE_OPENAI_ENDPOINT` and `AZURE_OPENAI_API_KEY`. `SUPABASE_SERVICE_KEY` and the Upstash vars are not read by the code yet. Optional: `EXPO_ACCESS_TOKEN` (if push security is on for the Expo project), `PUSH_DISABLED=true` (don't send pushes, e.g. locally), `RATE_LIMIT_PER_MINUTE` (default 300 per signed-in session) and `CORS_ORIGINS` (comma-separated web origins; default any). The server checks its settings at boot and lists anything missing or malformed. + +Every response carries an `x-request-id` (also in error bodies), matching one log line per request. Logs are JSON when `NODE_ENV=production`. Sign-in tokens are verified locally against the Supabase project's published signing key. `GET /health` reports the API and database; `POST /client-errors` records crashes reported by the app. Profile photos go to a public Supabase Storage bucket, `avatars`, which the privacy migration creates along with rules that let each user write only to their own folder. @@ -211,7 +217,13 @@ A cloud instance can't run a simulator. Use it for type-checking and linting, or ### Deploying the backend (Railway) -[`packages/backend/railway.toml`](./packages/backend/railway.toml) builds with Nixpacks (`npm run build`) and starts `node dist/main`. Set the root directory to `packages/backend`, add the env vars above in Railway, and run `npx prisma migrate deploy` before or as part of each release. +[`packages/backend/railway.toml`](./packages/backend/railway.toml) builds with Nixpacks (`npm run build`) and starts `node dist/main`. Set the root directory to `packages/backend`, add the env vars above in Railway, and run `npx prisma migrate deploy` before or as part of each release. Railway's health check calls `GET /health`, which also checks the database. + +**One migration waits for a deploy:** `20261105130000_drop_users_push_token` drops a column that Phase 2 servers read. Apply it only after Railway is running Phase 3 or later. + +### CI + +[`.github/workflows/ci.yml`](./.github/workflows/ci.yml) runs on every pull request and push to `main`: the backend job applies the migrations to a throwaway Postgres, checks they match the schema, and runs prettier, eslint, tsc, unit tests, database tests and the build; the mobile job runs tsc, eslint and unit tests. --- diff --git a/apps/mobile/__tests__/challenges.test.ts b/apps/mobile/__tests__/challenges.test.ts new file mode 100644 index 0000000..3323a42 --- /dev/null +++ b/apps/mobile/__tests__/challenges.test.ts @@ -0,0 +1,21 @@ +import { amount, daysLeftLabel, hasEnded, measureName } from '@/lib/challenges'; + +describe('challenge labels', () => { + it('formats amounts by type', () => { + expect(amount('steps', 12400)).toBe('12,400 steps'); + expect(amount('group_steps', 1)).toBe('1 step'); + expect(amount('active_minutes', 95)).toBe('95 min'); + expect(amount('workouts', 1)).toBe('1 workout'); + expect(measureName('workouts')).toBe('workouts'); + }); + it('knows when a challenge has ended', () => { + const soon = new Date(Date.now() + 3600_000).toISOString(); + const past = new Date(Date.now() - 1000).toISOString(); + expect(hasEnded({ endedAt: null, endDate: soon })).toBe(false); + expect(hasEnded({ endedAt: null, endDate: past })).toBe(true); + expect(hasEnded({ endedAt: past, endDate: soon })).toBe(true); + expect(daysLeftLabel(soon)).toBe('Last day'); + expect(daysLeftLabel(new Date(Date.now() + 3.5 * 86_400_000).toISOString())).toBe('4d left'); + expect(daysLeftLabel(past)).toBe('Ended'); + }); +}); diff --git a/apps/mobile/__tests__/date.test.ts b/apps/mobile/__tests__/date.test.ts new file mode 100644 index 0000000..8aa35ce --- /dev/null +++ b/apps/mobile/__tests__/date.test.ts @@ -0,0 +1,26 @@ +import { addDaysStr, dayLabel, loggedAtFor, weekLabel, weekStartStr } from '@/lib/date'; + +describe('local dates', () => { + it('adds days across months and years', () => { + expect(addDaysStr('2026-12-31', 1)).toBe('2027-01-01'); + expect(addDaysStr('2026-03-01', -1)).toBe('2026-02-28'); + expect(addDaysStr('2028-03-01', -1)).toBe('2028-02-29'); + }); + it('labels days', () => { + expect(dayLabel('2026-11-04', '2026-11-04')).toBe('Today'); + expect(dayLabel('2026-11-03', '2026-11-04')).toBe('Yesterday'); + expect(dayLabel('2026-11-02', '2026-11-04')).toBe('Mon 2 Nov'); + }); + it('finds the Monday and labels the week', () => { + expect(weekStartStr('2026-11-08')).toBe('2026-11-02'); // Sunday + expect(weekStartStr('2026-11-02')).toBe('2026-11-02'); + expect(weekLabel('2026-11-02')).toBe('2 – 8 Nov'); + expect(weekLabel('2026-10-26')).toBe('26 Oct – 1 Nov'); + }); + it('back-dated logs land at local midday; today uses the server clock', () => { + expect(loggedAtFor('2026-11-04', '2026-11-04')).toBeUndefined(); + const iso = loggedAtFor('2026-11-01', '2026-11-04')!; + expect(new Date(iso).getHours()).toBe(12); + expect(new Date(iso).getDate()).toBe(1); + }); +}); diff --git a/apps/mobile/__tests__/notificationRoute.test.ts b/apps/mobile/__tests__/notificationRoute.test.ts new file mode 100644 index 0000000..4b3b499 --- /dev/null +++ b/apps/mobile/__tests__/notificationRoute.test.ts @@ -0,0 +1,17 @@ +import { notificationRoute } from '@/lib/notificationRoute'; + +describe('where an alert opens', () => { + it('sends each type to its screen', () => { + expect(notificationRoute('follow_request')).toEqual({ pathname: '/friends', params: { tab: 'requests' } }); + expect(notificationRoute('kudos', { userId: 'u1' })).toEqual({ pathname: '/profile/[id]', params: { id: 'u1' } }); + expect(notificationRoute('challenge_ended', { challengeId: 'c1' })).toEqual({ pathname: '/challenge/[id]', params: { id: 'c1' } }); + expect(notificationRoute('streak_at_risk')).toBe('/(tabs)/habits'); + expect(notificationRoute('weekly_progress')).toBe('/(tabs)/activity'); + }); + it('falls back to the inbox when ids are missing or the type is unknown', () => { + expect(notificationRoute('follow')).toBe('/notifications'); + expect(notificationRoute('challenge_joined')).toBe('/(tabs)/social'); + expect(notificationRoute('something_new')).toBe('/notifications'); + expect(notificationRoute(undefined)).toBe('/notifications'); + }); +}); diff --git a/apps/mobile/__tests__/quickFoods.test.ts b/apps/mobile/__tests__/quickFoods.test.ts new file mode 100644 index 0000000..7f63a07 --- /dev/null +++ b/apps/mobile/__tests__/quickFoods.test.ts @@ -0,0 +1,17 @@ +import { foodKey, portionAsFood, portionLabel } from '@/lib/quickFoods'; + +describe('quick foods', () => { + it('matches the server key', () => { + expect(foodKey(' Greek Yogurt ', 'Fage')).toBe('greek yogurt|fage'); + expect(foodKey('Oats')).toBe('oats|'); + }); + it('labels portions', () => { + expect(portionLabel({ servingQty: 150, servingUnit: 'g' })).toBe('150 g'); + expect(portionLabel({ servingQty: 1, servingUnit: 'serving' })).toBe('1 serving'); + expect(portionLabel({ servingQty: 2.25, servingUnit: 'serving' })).toBe('2.3 servings'); + }); + it('turns a saved portion into a loggable food', () => { + const food = portionAsFood({ name: 'Oats', brand: null, barcode: null, calories: 300, proteinG: 10, carbsG: 50, fatG: 6, servingQty: 80, servingUnit: 'g' }); + expect(food).toMatchObject({ portion: true, offId: '', calories: 300, servingQty: 80 }); + }); +}); diff --git a/apps/mobile/__tests__/tdee.test.ts b/apps/mobile/__tests__/tdee.test.ts new file mode 100644 index 0000000..a72cf66 --- /dev/null +++ b/apps/mobile/__tests__/tdee.test.ts @@ -0,0 +1,35 @@ +import { calcAdjustedCalories, calcBMR, calcMacros, calcTDEE, calcTimeline } from '@/lib/tdee'; + +describe('calorie maths', () => { + it('Mifflin-St Jeor BMR', () => { + // 10*80 + 6.25*180 - 5*30 = 1775 + expect(calcBMR('male', 80, 180, 30)).toBe(1780); + expect(calcBMR('female', 80, 180, 30)).toBe(1614); + expect(calcBMR('other', 80, 180, 30)).toBe(1697); + }); + + it('TDEE by activity level, sedentary when unknown', () => { + expect(calcTDEE(1780, 'active')).toBe(2759); + expect(calcTDEE(1780, 'nonsense')).toBe(2136); + }); + + it('deficit or surplus by goal and pace, never under 1200 to lose', () => { + expect(calcAdjustedCalories(2500, 'lose_weight', 'moderate')).toBe(1950); + expect(calcAdjustedCalories(2500, 'build_muscle', 'slow')).toBe(2775); + expect(calcAdjustedCalories(2500, 'maintain', 'aggressive')).toBe(2500); + expect(calcAdjustedCalories(1500, 'lose_weight', 'aggressive')).toBe(1200); + }); + + it('macro splits match the backend', () => { + expect(calcMacros(2000, 'high_protein')).toEqual({ proteinG: 200, carbsG: 150, fatG: 67 }); + expect(calcMacros(2000, 'balanced')).toEqual({ proteinG: 150, carbsG: 200, fatG: 67 }); + expect(calcMacros(2000, 'low_carb')).toEqual({ proteinG: 150, carbsG: 100, fatG: 111 }); + expect(calcMacros(2000)).toEqual(calcMacros(2000, 'balanced')); + }); + + it('weeks to goal', () => { + expect(calcTimeline(90, 80, 'moderate')).toBe(20); + expect(calcTimeline(80, 80, 'moderate')).toBeNull(); + expect(calcTimeline(90, 80, 'unknown')).toBeNull(); + }); +}); diff --git a/apps/mobile/__tests__/units.test.ts b/apps/mobile/__tests__/units.test.ts new file mode 100644 index 0000000..a019afa --- /dev/null +++ b/apps/mobile/__tests__/units.test.ts @@ -0,0 +1,15 @@ +import { formatHeight, formatWeight, kgToUnit, unitToKg } from '@/lib/units'; + +describe('units', () => { + it('converts weight both ways to one decimal', () => { + expect(kgToUnit(80, 'lb')).toBe(176.4); + expect(unitToKg(176.4, 'lb')).toBe(80); + expect(kgToUnit(80, 'kg')).toBe(80); + }); + it('formats weight and height', () => { + expect(formatWeight(78.46, 'kg')).toBe('78.5 kg'); + expect(formatWeight(null, 'lb')).toBe('—'); + expect(formatHeight(175, 'cm')).toBe('175 cm'); + expect(formatHeight(175, 'ft')).toBe('5′9″'); + }); +}); diff --git a/apps/mobile/app.config.js b/apps/mobile/app.config.js new file mode 100644 index 0000000..bfe47e9 --- /dev/null +++ b/apps/mobile/app.config.js @@ -0,0 +1,13 @@ +// Adds build-specific settings on top of app.json. +// +// Plain-HTTP traffic is only allowed in development builds, which may talk to +// a backend on the local network. Store builds (EAS "preview" and +// "production") only use HTTPS. +module.exports = ({ config }) => { + const profile = process.env.EAS_BUILD_PROFILE; + const development = profile ? profile === 'development' : process.env.NODE_ENV !== 'production'; + return { + ...config, + android: { ...config.android, usesCleartextTraffic: development }, + }; +}; diff --git a/apps/mobile/app.json b/apps/mobile/app.json index 68980e8..55b4126 100644 --- a/apps/mobile/app.json +++ b/apps/mobile/app.json @@ -18,18 +18,48 @@ "usesAppleSignIn": true, "infoPlist": { "ITSAppUsesNonExemptEncryption": false + }, + "privacyManifests": { + "NSPrivacyAccessedAPITypes": [ + { + "NSPrivacyAccessedAPIType": "NSPrivacyAccessedAPICategoryUserDefaults", + "NSPrivacyAccessedAPITypeReasons": [ + "CA92.1" + ] + }, + { + "NSPrivacyAccessedAPIType": "NSPrivacyAccessedAPICategoryFileTimestamp", + "NSPrivacyAccessedAPITypeReasons": [ + "C617.1" + ] + }, + { + "NSPrivacyAccessedAPIType": "NSPrivacyAccessedAPICategorySystemBootTime", + "NSPrivacyAccessedAPITypeReasons": [ + "35F9.1" + ] + }, + { + "NSPrivacyAccessedAPIType": "NSPrivacyAccessedAPICategoryDiskSpace", + "NSPrivacyAccessedAPITypeReasons": [ + "E174.1" + ] + } + ] } }, "android": { "package": "com.gritapp.mobile", "minSdkVersion": 26, - "usesCleartextTraffic": true, + "usesCleartextTraffic": false, "adaptiveIcon": { "backgroundColor": "#0D0D0D", "foregroundImage": "./assets/android-icon-foreground.png" }, "permissions": [ - "android.permission.CAMERA", + "android.permission.CAMERA" + ], + "blockedPermissions": [ "android.permission.RECORD_AUDIO" ] }, @@ -44,7 +74,9 @@ [ "expo-camera", { - "cameraPermission": "GRIT uses your camera to scan food barcodes." + "cameraPermission": "GRIT uses your camera to scan food barcodes.", + "microphonePermission": false, + "recordAudioAndroid": false } ], [ @@ -59,7 +91,8 @@ "expo-image-picker", { "photosPermission": "GRIT uses your photos so you can choose a profile picture.", - "cameraPermission": false + "cameraPermission": false, + "microphonePermission": false } ] ], diff --git a/apps/mobile/app/(auth)/login.tsx b/apps/mobile/app/(auth)/login.tsx index 13e61fa..bdd7568 100644 --- a/apps/mobile/app/(auth)/login.tsx +++ b/apps/mobile/app/(auth)/login.tsx @@ -163,7 +163,7 @@ export default function LoginScreen() { New here? - + { const event = navigation.emit({ diff --git a/apps/mobile/app/(tabs)/activity.tsx b/apps/mobile/app/(tabs)/activity.tsx index 5d102b0..db8632d 100644 --- a/apps/mobile/app/(tabs)/activity.tsx +++ b/apps/mobile/app/(tabs)/activity.tsx @@ -259,7 +259,7 @@ export default function ActivityScreen() { {/* Log button */} - { Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); setShowSheet(true); diff --git a/apps/mobile/app/(tabs)/food.tsx b/apps/mobile/app/(tabs)/food.tsx index 7b72e54..db3b1d9 100644 --- a/apps/mobile/app/(tabs)/food.tsx +++ b/apps/mobile/app/(tabs)/food.tsx @@ -177,7 +177,7 @@ export default function FoodScreen() { Food - router.push('/barcode-scanner' as never)} style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1, @@ -189,7 +189,7 @@ export default function FoodScreen() { > 📷 - openManualEntry()} accessibilityLabel="Log food manually" style={{ width: 40, height: 40, borderRadius: 12, backgroundColor: Colors.orange, alignItems: 'center', justifyContent: 'center' }} @@ -263,7 +263,7 @@ export default function FoodScreen() { const isEmpty = section.data.length === 0; return ( - toggleSection(section.title)} style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingVertical: 2, marginBottom: isOpen ? 8 : 0 }} > @@ -278,7 +278,7 @@ export default function FoodScreen() { )} - openManualEntry(section.key)} hitSlop={8}> + openManualEntry(section.key)} hitSlop={8}> + Add {isOpen ? '▲' : '▼'} diff --git a/apps/mobile/app/(tabs)/habits.tsx b/apps/mobile/app/(tabs)/habits.tsx index e4893bd..2d7a19c 100644 --- a/apps/mobile/app/(tabs)/habits.tsx +++ b/apps/mobile/app/(tabs)/habits.tsx @@ -166,7 +166,7 @@ export default function HabitsScreen() { Habits {canAddMore && ( - { Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); setShowCreate(true); @@ -233,7 +233,7 @@ export default function HabitsScreen() { Start tiny — one habit beats zero. - setShowCreate(true)} style={{ backgroundColor: Colors.orange, borderRadius: 999, paddingHorizontal: 20, paddingVertical: 12, marginTop: 4 }} > diff --git a/apps/mobile/app/(tabs)/index.tsx b/apps/mobile/app/(tabs)/index.tsx index 6c232d0..381d475 100644 --- a/apps/mobile/app/(tabs)/index.tsx +++ b/apps/mobile/app/(tabs)/index.tsx @@ -310,7 +310,7 @@ export default function HomeScreen() { Calories today - router.push('/(tabs)/food')}> + router.push('/(tabs)/food')}> Log food → @@ -365,7 +365,7 @@ export default function HomeScreen() { {/* Stats bento */} - router.push('/(tabs)/activity')} style={({ pressed }) => ({ flex: 1, backgroundColor: Colors.surface, borderRadius: 20, @@ -392,7 +392,7 @@ export default function HomeScreen() { Goal: {activeGoal} min - router.push('/(tabs)/habits')} style={({ pressed }) => ({ flex: 1, backgroundColor: Colors.surface, borderRadius: 20, @@ -430,13 +430,13 @@ export default function HomeScreen() { Today's meals - router.push('/(tabs)/food')}> + router.push('/(tabs)/food')}> See all → {mealGroups.map((m) => ( - router.push('/(tabs)/food')} style={({ pressed }) => ({ @@ -459,7 +459,7 @@ export default function HomeScreen() { ))} - router.push('/(tabs)/food')} style={({ pressed }) => ({ backgroundColor: 'transparent', borderRadius: 14, diff --git a/apps/mobile/app/(tabs)/profile.tsx b/apps/mobile/app/(tabs)/profile.tsx index fda4ebb..2cf179a 100644 --- a/apps/mobile/app/(tabs)/profile.tsx +++ b/apps/mobile/app/(tabs)/profile.tsx @@ -25,7 +25,7 @@ import { confirmAction, notify } from '../../lib/confirm'; import Constants from 'expo-constants'; import { Avatar } from '../../components/ui/Avatar'; import { pickAndUploadAvatar, removeAvatarFile } from '../../lib/avatar'; -import { useHabits, useHabitSummary } from '../../hooks/useHabits'; +import { useHabitSummary } from '../../hooks/useHabits'; import { useWeeklySummary } from '../../hooks/useActivityLog'; type BackendUser = Me; @@ -206,7 +206,6 @@ export default function ProfileScreen() { { label: 'Phase', value: isLoading ? '—' : labelCase(me?.primaryGoal).split(' ')[0], unit: '', color: Colors.teal }, ]; - const { data: habits } = useHabits(); const { data: habitSummary } = useHabitSummary(); const { refreshing, onRefresh } = usePullToRefresh([['me'], ['habits'], ['habit-streaks'], ['activity-week']]); const streak = habitSummary?.maxStreak ?? 0; @@ -271,7 +270,7 @@ export default function ProfileScreen() { {streak > 0 ? `🔥 ${streak} day streak` : 'Start a streak today'} - ({ backgroundColor: Colors.surface2, @@ -319,7 +318,7 @@ export default function ProfileScreen() { This week - router.push('/(tabs)/activity')} hitSlop={8}> + router.push('/(tabs)/activity')} hitSlop={8}> Details → @@ -367,7 +366,7 @@ export default function ProfileScreen() { ))} {/* Log out */} - ({ flexDirection: 'row', diff --git a/apps/mobile/app/(tabs)/social.tsx b/apps/mobile/app/(tabs)/social.tsx index 587a502..e4704fe 100644 --- a/apps/mobile/app/(tabs)/social.tsx +++ b/apps/mobile/app/(tabs)/social.tsx @@ -1,7 +1,7 @@ import React, { useState } from 'react'; import { View, Text, ScrollView, Pressable, RefreshControl, TextInput, Alert } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; -import { useFocusEffect } from 'expo-router'; +import { router, useFocusEffect } from 'expo-router'; import * as Haptics from 'expo-haptics'; import { useFeed, useFollowRequests, useWeeklyLeaderboard } from '@/hooks/useSocialFeed'; import { useChallenges, useJoinChallenge } from '@/hooks/useChallenges'; @@ -16,7 +16,6 @@ import { CreateChallengeSheet } from '@/components/social/CreateChallengeSheet'; import { Colors } from '@/constants/colors'; import { InboxBell } from '@/components/ui/InboxBell'; import { hasEnded } from '@/lib/challenges'; -import { router } from 'expo-router'; type Tab = 'feed' | 'challenges' | 'leaderboard'; @@ -94,7 +93,7 @@ export default function SocialScreen() { )} {activeTab === 'challenges' && ( - { Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); setShowCreateChallenge(true); @@ -118,7 +117,7 @@ export default function SocialScreen() { {/* Tab switcher */} {(['feed', 'challenges', 'leaderboard'] as Tab[]).map(t => ( - setActiveTab(t)} style={{ @@ -194,7 +193,7 @@ export default function SocialScreen() { paddingVertical: 10, color: Colors.text, fontFamily: 'DMSans-Regular', fontSize: 14, }} /> - Create one or get an invite link from a friend. - setShowCreateChallenge(true)} style={{ backgroundColor: Colors.orange, borderRadius: 999, paddingHorizontal: 20, paddingVertical: 12, marginTop: 4 }} > diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx index 6b47116..b025e5b 100644 --- a/apps/mobile/app/_layout.tsx +++ b/apps/mobile/app/_layout.tsx @@ -1,6 +1,6 @@ import '../global.css'; import React, { useEffect } from 'react'; -import { Stack, SplashScreen, router, useSegments } from 'expo-router'; +import { Stack, SplashScreen, router, useSegments, usePathname } from 'expo-router'; import { QueryClientProvider } from '@tanstack/react-query'; import { GestureHandlerRootView } from 'react-native-gesture-handler'; import { StatusBar } from 'expo-status-bar'; @@ -19,12 +19,22 @@ import { queryClient } from '@/lib/queryClient'; import { useAuthStore } from '@/stores/authStore'; import { usePushNotifications } from '@/hooks/usePushNotifications'; import { Toast } from '@/components/ui/Toast'; +import { OfflineBanner } from '@/components/ui/OfflineBanner'; +import { CrashScreen } from '@/components/ui/CrashScreen'; +import { installGlobalCrashHandler, setCrashScreen } from '@/lib/crashReporter'; + +installGlobalCrashHandler(); + +/** A crash anywhere below shows a recovery screen instead of a blank app. */ +export const ErrorBoundary = CrashScreen; SplashScreen.preventAutoHideAsync(); export default function RootLayout() { const { session, isLoading, onboardingLoading, setSession, onboardingComplete, loadOnboardingState, setOnboardingComplete } = useAuthStore(); const segments = useSegments(); + const pathname = usePathname(); + useEffect(() => setCrashScreen(pathname), [pathname]); // Register for push only once signed in; the backend rejects anonymous calls usePushNotifications(!!session); @@ -117,6 +127,7 @@ export default function RootLayout() { + ); diff --git a/apps/mobile/app/barcode-scanner.tsx b/apps/mobile/app/barcode-scanner.tsx index 8f9074d..bb4f842 100644 --- a/apps/mobile/app/barcode-scanner.tsx +++ b/apps/mobile/app/barcode-scanner.tsx @@ -59,10 +59,10 @@ export default function BarcodeScannerScreen() { GRIT uses the camera to scan food barcodes — free forever, never paywalled. - + Allow camera access - router.back()} style={{ marginTop: 12 }}> + router.back()} style={{ marginTop: 12 }}> Go back @@ -89,7 +89,7 @@ export default function BarcodeScannerScreen() { {/* Overlay UI */} {/* Close button */} - router.back()} style={styles.closeBtn} > @@ -115,7 +115,7 @@ export default function BarcodeScannerScreen() { {/* Rescan button */} {scannedCode && !showSheet && ( - setScannedCode(null)} style={styles.rescanBtn} > diff --git a/apps/mobile/app/challenge/[id].tsx b/apps/mobile/app/challenge/[id].tsx index 78cb48a..3688c81 100644 --- a/apps/mobile/app/challenge/[id].tsx +++ b/apps/mobile/app/challenge/[id].tsx @@ -122,7 +122,7 @@ export default function ChallengeDetailScreen() { {/* Back */} - router.back()} hitSlop={12}> + router.back()} hitSlop={12}> ← Back @@ -223,7 +223,7 @@ export default function ChallengeDetailScreen() { {/* Share invite */} {!ended && ( - ({ opacity: pressed ? 0.7 : 1, diff --git a/apps/mobile/app/challenges/join/[code].tsx b/apps/mobile/app/challenges/join/[code].tsx index f68c2c8..83aa3e1 100644 --- a/apps/mobile/app/challenges/join/[code].tsx +++ b/apps/mobile/app/challenges/join/[code].tsx @@ -28,7 +28,7 @@ export default function JoinChallengeScreen() { {error} - router.replace('/(tabs)/social')}> + router.replace('/(tabs)/social')}> Go to challenges diff --git a/apps/mobile/app/coach.tsx b/apps/mobile/app/coach.tsx index 4cbe0ff..c0e3237 100644 --- a/apps/mobile/app/coach.tsx +++ b/apps/mobile/app/coach.tsx @@ -96,7 +96,7 @@ export default function CoachScreen() { borderBottomColor: Colors.border, gap: 12, }}> - router.back()} hitSlop={12}> + router.back()} hitSlop={12}> ← @@ -222,7 +222,7 @@ export default function CoachScreen() { blurOnSubmit={false} editable={!isStreaming} /> - ({ diff --git a/apps/mobile/app/onboarding/activity.tsx b/apps/mobile/app/onboarding/activity.tsx index 0e3aeb6..06f0066 100644 --- a/apps/mobile/app/onboarding/activity.tsx +++ b/apps/mobile/app/onboarding/activity.tsx @@ -48,7 +48,7 @@ export default function ActivityScreen() { {LEVELS.map((level) => { const selected = activityLevel === level.value; return ( - set({ activityLevel: level.value })} style={{ @@ -89,7 +89,7 @@ export default function ActivityScreen() { })} - { if (activityLevel) router.push('/onboarding/goal'); }} @@ -108,7 +108,7 @@ export default function ActivityScreen() { - router.back()} style={{ alignItems: 'center', paddingBottom: 8 }}> + router.back()} style={{ alignItems: 'center', paddingBottom: 8 }}> ← Back diff --git a/apps/mobile/app/onboarding/advanced.tsx b/apps/mobile/app/onboarding/advanced.tsx index 7a0d5d3..7ba5679 100644 --- a/apps/mobile/app/onboarding/advanced.tsx +++ b/apps/mobile/app/onboarding/advanced.tsx @@ -25,7 +25,7 @@ function ToggleRow({ onToggle: () => void; }) { return ( - - router.push('/onboarding/notifications')} style={({ pressed }) => ({ backgroundColor: Colors.orange, @@ -107,7 +107,7 @@ export default function AdvancedScreen() { - router.back()} style={{ alignItems: 'center', paddingBottom: 8 }}> + router.back()} style={{ alignItems: 'center', paddingBottom: 8 }}> ← Back diff --git a/apps/mobile/app/onboarding/age.tsx b/apps/mobile/app/onboarding/age.tsx index e2961f0..744563f 100644 --- a/apps/mobile/app/onboarding/age.tsx +++ b/apps/mobile/app/onboarding/age.tsx @@ -80,7 +80,7 @@ export default function AgeScreen() { - router.back()} style={{ width: 40, height: 40, borderRadius: 12, backgroundColor: Colors.surface, borderWidth: 1, borderColor: Colors.border, alignItems: 'center', justifyContent: 'center' }} > @@ -110,7 +110,7 @@ export default function AgeScreen() { Scroll to adjust - ({ backgroundColor: Colors.orange, diff --git a/apps/mobile/app/onboarding/basics.tsx b/apps/mobile/app/onboarding/basics.tsx index 06bedbe..6528f83 100644 --- a/apps/mobile/app/onboarding/basics.tsx +++ b/apps/mobile/app/onboarding/basics.tsx @@ -28,7 +28,7 @@ export default function GenderScreen() { - router.back()} style={{ width: 40, height: 40, borderRadius: 12, backgroundColor: Colors.surface, borderWidth: 1, borderColor: Colors.border, alignItems: 'center', justifyContent: 'center' }} > @@ -49,7 +49,7 @@ export default function GenderScreen() { {GENDERS.map(g => { const sel = gender === g.v; return ( - set({ gender: g.v })} style={{ @@ -71,7 +71,7 @@ export default function GenderScreen() { - { if (gender) router.push('/onboarding/age'); }} disabled={!gender} style={({ pressed }) => ({ diff --git a/apps/mobile/app/onboarding/body.tsx b/apps/mobile/app/onboarding/body.tsx index 1fc99de..81a8fc1 100644 --- a/apps/mobile/app/onboarding/body.tsx +++ b/apps/mobile/app/onboarding/body.tsx @@ -31,7 +31,7 @@ function UnitToggle({ options, value, onChange }: { options: string[]; value: st return ( {options.map(u => ( - onChange(u)} style={{ @@ -174,7 +174,7 @@ export default function BodyScreen() { - router.back()} style={{ width: 40, height: 40, borderRadius: 12, backgroundColor: Colors.surface, borderWidth: 1, borderColor: Colors.border, alignItems: 'center', justifyContent: 'center' }} > @@ -224,7 +224,7 @@ export default function BodyScreen() { ← drag to adjust → - ({ backgroundColor: Colors.orange, diff --git a/apps/mobile/app/onboarding/friction.tsx b/apps/mobile/app/onboarding/friction.tsx index 64574b4..7ad65e2 100644 --- a/apps/mobile/app/onboarding/friction.tsx +++ b/apps/mobile/app/onboarding/friction.tsx @@ -42,7 +42,7 @@ export default function FrictionScreen() { {OPTIONS.map((o) => { const selected = friction === o.value; return ( - set({ friction: o.value })} style={{ @@ -74,7 +74,7 @@ export default function FrictionScreen() { })} - { if (friction) router.push('/onboarding/nutrition'); }} disabled={!friction} style={({ pressed }) => ({ @@ -91,7 +91,7 @@ export default function FrictionScreen() { - router.back()} style={{ alignItems: 'center', paddingBottom: 8 }}> + router.back()} style={{ alignItems: 'center', paddingBottom: 8 }}> ← Back diff --git a/apps/mobile/app/onboarding/goal.tsx b/apps/mobile/app/onboarding/goal.tsx index d7b6575..f7ec792 100644 --- a/apps/mobile/app/onboarding/goal.tsx +++ b/apps/mobile/app/onboarding/goal.tsx @@ -48,7 +48,7 @@ export default function GoalScreen() { {/* Header nav */} - router.back()} style={{ width: 40, height: 40, borderRadius: 12, backgroundColor: Colors.surface, borderWidth: 1, borderColor: Colors.border, alignItems: 'center', justifyContent: 'center' }} > @@ -71,7 +71,7 @@ export default function GoalScreen() { {GOALS.map(g => { const selected = primaryGoal === g.value; return ( - set({ primaryGoal: g.value })} style={{ @@ -146,7 +146,7 @@ export default function GoalScreen() { )} - ({ diff --git a/apps/mobile/app/onboarding/index.tsx b/apps/mobile/app/onboarding/index.tsx index 6ed26d2..dbf3702 100644 --- a/apps/mobile/app/onboarding/index.tsx +++ b/apps/mobile/app/onboarding/index.tsx @@ -48,7 +48,7 @@ export default function WelcomeScreen() { {/* CTA */} - router.push('/onboarding/basics')} style={({ pressed }) => ({ backgroundColor: Colors.orange, @@ -67,7 +67,7 @@ export default function WelcomeScreen() { Already have an account? - + Sign in diff --git a/apps/mobile/app/onboarding/notifications.tsx b/apps/mobile/app/onboarding/notifications.tsx index 5aa2697..de6252c 100644 --- a/apps/mobile/app/onboarding/notifications.tsx +++ b/apps/mobile/app/onboarding/notifications.tsx @@ -53,7 +53,7 @@ export default function NotificationsScreen() { {ITEMS.map((item) => { const val = values[item.key] as boolean; return ( - set({ [item.key]: !val } as any)} style={{ @@ -91,7 +91,7 @@ export default function NotificationsScreen() { {/* Off-track only toggle */} - set({ notifOffTrackOnly: !notifOffTrackOnly })} style={{ backgroundColor: Colors.surface, @@ -117,7 +117,7 @@ export default function NotificationsScreen() { /> - { // Ask now, while the user has just chosen to get notifications if (notifWorkout || notifMeal || notifProgress || notifStreak) { @@ -139,7 +139,7 @@ export default function NotificationsScreen() { - router.back()} style={{ alignItems: 'center', paddingBottom: 8 }}> + router.back()} style={{ alignItems: 'center', paddingBottom: 8 }}> ← Back diff --git a/apps/mobile/app/onboarding/nutrition.tsx b/apps/mobile/app/onboarding/nutrition.tsx index 9649dde..dabc924 100644 --- a/apps/mobile/app/onboarding/nutrition.tsx +++ b/apps/mobile/app/onboarding/nutrition.tsx @@ -33,7 +33,7 @@ function SelectGroup({ {options.map((o) => { const isSelected = selected === o.value; return ( - onSelect(o.value)} style={{ @@ -114,7 +114,7 @@ export default function NutritionScreen() { ]} /> - { if (isValid) router.push('/onboarding/advanced'); }} disabled={!isValid} style={({ pressed }) => ({ @@ -131,7 +131,7 @@ export default function NutritionScreen() { - router.back()} style={{ alignItems: 'center', paddingBottom: 8 }}> + router.back()} style={{ alignItems: 'center', paddingBottom: 8 }}> ← Back diff --git a/apps/mobile/app/onboarding/pace.tsx b/apps/mobile/app/onboarding/pace.tsx index eaf1b7c..6452a4e 100644 --- a/apps/mobile/app/onboarding/pace.tsx +++ b/apps/mobile/app/onboarding/pace.tsx @@ -51,7 +51,7 @@ export default function PaceScreen() { {PACES.map((p) => { const selected = pace === p.value; return ( - set({ pace: p.value })} style={{ @@ -106,7 +106,7 @@ export default function PaceScreen() { )} - { if (pace) router.push('/onboarding/friction'); }} disabled={!pace} style={({ pressed }) => ({ @@ -123,7 +123,7 @@ export default function PaceScreen() { - router.back()} style={{ alignItems: 'center', paddingBottom: 8 }}> + router.back()} style={{ alignItems: 'center', paddingBottom: 8 }}> ← Back diff --git a/apps/mobile/app/onboarding/reveal.tsx b/apps/mobile/app/onboarding/reveal.tsx index e8d3a41..aa4c1ca 100644 --- a/apps/mobile/app/onboarding/reveal.tsx +++ b/apps/mobile/app/onboarding/reveal.tsx @@ -14,13 +14,6 @@ function ProgressBar({ step, total }: { step: number; total: number }) { ); } -const GOAL_LABELS: Record = { - lose_weight: 'Lose Weight', - build_muscle: 'Build Muscle', - maintain: 'Maintain', - recomp: 'Recomp', -}; - export default function RevealScreen() { const store = useOnboardingStore(); @@ -71,7 +64,7 @@ export default function RevealScreen() { Missing information — please go back. - router.back()} style={{ marginTop: 16 }}> + router.back()} style={{ marginTop: 16 }}> ← Back @@ -138,7 +131,7 @@ export default function RevealScreen() { ))} - router.push('/onboarding/signup')} style={({ pressed }) => ({ width: '100%', @@ -154,7 +147,7 @@ export default function RevealScreen() { - router.back()} style={{ alignItems: 'center', paddingTop: 16, paddingBottom: 8 }}> + router.back()} style={{ alignItems: 'center', paddingTop: 16, paddingBottom: 8 }}> ← Back diff --git a/apps/mobile/app/onboarding/signup.tsx b/apps/mobile/app/onboarding/signup.tsx index 5c7ba45..01e0683 100644 --- a/apps/mobile/app/onboarding/signup.tsx +++ b/apps/mobile/app/onboarding/signup.tsx @@ -117,7 +117,7 @@ export default function SignupScreen() { - ({ @@ -141,14 +141,14 @@ export default function SignupScreen() { Already have an account? - router.push('/(auth)/login')}> + router.push('/(auth)/login')}> Sign in - router.back()} style={{ alignItems: 'center', paddingBottom: 8 }}> + router.back()} style={{ alignItems: 'center', paddingBottom: 8 }}> ← Back diff --git a/apps/mobile/components/activity/LogActivitySheet.tsx b/apps/mobile/components/activity/LogActivitySheet.tsx index 6e4a0e3..a58dd88 100644 --- a/apps/mobile/components/activity/LogActivitySheet.tsx +++ b/apps/mobile/components/activity/LogActivitySheet.tsx @@ -1,5 +1,5 @@ import React, { useRef, useState, useCallback } from 'react'; -import { View, Text, Pressable, ScrollView, Alert } from 'react-native'; +import { View, Text, Pressable, Alert } from 'react-native'; import BottomSheet, { BottomSheetScrollView } from '@gorhom/bottom-sheet'; import { SheetTextInput, sheetKeyboardProps } from '@/components/ui/SheetTextInput'; import * as Haptics from 'expo-haptics'; @@ -124,7 +124,7 @@ export function LogActivitySheet({ onClose, editing, date }: LogActivitySheetPro {(types ?? Object.keys(ACTIVITY_LABELS)).map((type) => ( - setSelectedType(type)} style={{ @@ -155,7 +155,7 @@ export function LogActivitySheet({ onClose, editing, date }: LogActivitySheetPro {[15, 30, 45, 60].map((min) => ( - setDuration(String(min))} style={{ diff --git a/apps/mobile/components/activity/WeeklyBarChart.tsx b/apps/mobile/components/activity/WeeklyBarChart.tsx deleted file mode 100644 index 2944716..0000000 --- a/apps/mobile/components/activity/WeeklyBarChart.tsx +++ /dev/null @@ -1,67 +0,0 @@ -import React from 'react'; -import { View, Text } from 'react-native'; -import Svg, { Rect } from 'react-native-svg'; -import { Colors } from '@/constants/colors'; -import type { WeekDay } from '@/hooks/useActivityLog'; -import { localDateStr } from '@/lib/date'; - -interface WeeklyBarChartProps { - days: WeekDay[]; -} - -const CHART_HEIGHT = 120; -const BAR_WIDTH = 28; -const DAY_LABELS = ['M', 'T', 'W', 'T', 'F', 'S', 'S']; - -export function WeeklyBarChart({ days }: WeeklyBarChartProps) { - const maxMinutes = Math.max(...days.map((d) => d.activeMinutes), 1); - const today = localDateStr(); - - return ( - - - {days.map((day, i) => { - const barH = Math.max((day.activeMinutes / maxMinutes) * CHART_HEIGHT, 4); - const isToday = day.date === today; - const hasActivity = day.activeMinutes > 0; - - return ( - - {/* Minute label on top of bar */} - {hasActivity && ( - - {day.activeMinutes}m - - )} - {/* Bar */} - - - - {/* Day label */} - - {DAY_LABELS[i]} - - - ); - })} - - - ); -} diff --git a/apps/mobile/components/coach/NudgeCard.tsx b/apps/mobile/components/coach/NudgeCard.tsx index bb397ef..26173cc 100644 --- a/apps/mobile/components/coach/NudgeCard.tsx +++ b/apps/mobile/components/coach/NudgeCard.tsx @@ -8,7 +8,7 @@ export function NudgeCard() { const { data, isLoading } = useAINudge(); return ( - router.push('/coach')} style={({ pressed }) => ({ opacity: pressed ? 0.85 : 1, diff --git a/apps/mobile/components/food/FoodLogItem.tsx b/apps/mobile/components/food/FoodLogItem.tsx index fc6720a..869e531 100644 --- a/apps/mobile/components/food/FoodLogItem.tsx +++ b/apps/mobile/components/food/FoodLogItem.tsx @@ -70,7 +70,7 @@ export function FoodLogItem({ item, onDelete }: FoodLogItemProps) { {Math.round(item.calories)} - onDelete(item.id)} hitSlop={12} style={({ pressed }) => ({ opacity: pressed ? 0.5 : 1 })} diff --git a/apps/mobile/components/food/FoodSearchBar.tsx b/apps/mobile/components/food/FoodSearchBar.tsx index f68278a..fe320a5 100644 --- a/apps/mobile/components/food/FoodSearchBar.tsx +++ b/apps/mobile/components/food/FoodSearchBar.tsx @@ -20,7 +20,7 @@ export function FoodSearchBar({ onSelect }: FoodSearchBarProps) { const renderItem = useCallback( ({ item }: { item: NormalizedFood }) => ( - { onSelect(item); setQuery(''); @@ -106,7 +106,7 @@ export function FoodSearchBar({ onSelect }: FoodSearchBarProps) { /> {isLoading && } {query.length > 0 && !isLoading && ( - setQuery('')} hitSlop={8}> + setQuery('')} hitSlop={8}> × )} @@ -145,7 +145,7 @@ export function FoodSearchBar({ onSelect }: FoodSearchBarProps) { No results for "{query}" - onSelect({ offId: '', name: query, brand: null, barcode: null, calories: 0, proteinG: 0, carbsG: 0, fatG: 0, servingQty: 1, servingUnit: 'serving', imageUrl: null })}> + onSelect({ offId: '', name: query, brand: null, barcode: null, calories: 0, proteinG: 0, carbsG: 0, fatG: 0, servingQty: 1, servingUnit: 'serving', imageUrl: null })}> Log "{query}" manually → diff --git a/apps/mobile/components/food/LogFoodSheet.tsx b/apps/mobile/components/food/LogFoodSheet.tsx index f5ad111..f19541b 100644 --- a/apps/mobile/components/food/LogFoodSheet.tsx +++ b/apps/mobile/components/food/LogFoodSheet.tsx @@ -264,7 +264,7 @@ export function LogFoodSheet({ food, initialMeal, date, onClose }: LogFoodSheetP {MEAL_TYPES.map((m) => ( - setMealType(m)} style={{ diff --git a/apps/mobile/components/habits/CreateHabitSheet.tsx b/apps/mobile/components/habits/CreateHabitSheet.tsx index f9cf2a2..c53ba45 100644 --- a/apps/mobile/components/habits/CreateHabitSheet.tsx +++ b/apps/mobile/components/habits/CreateHabitSheet.tsx @@ -75,7 +75,7 @@ export function CreateHabitSheet({ onClose, editing }: CreateHabitSheetProps) { {/* Mode toggle */} {!editing && {(['presets', 'custom'] as Mode[]).map((m) => ( - setMode(m)} style={{ @@ -103,7 +103,7 @@ export function CreateHabitSheet({ onClose, editing }: CreateHabitSheetProps) { {mode === 'presets' ? ( {(presets ?? []).map((p) => ( - setSelectedPreset(p.key)} style={{ diff --git a/apps/mobile/components/social/ChallengeCard.tsx b/apps/mobile/components/social/ChallengeCard.tsx index 0c8ca20..af71c99 100644 --- a/apps/mobile/components/social/ChallengeCard.tsx +++ b/apps/mobile/components/social/ChallengeCard.tsx @@ -28,7 +28,7 @@ export function ChallengeCard({ challenge, myUserId }: ChallengeCardProps) { } return ( - router.push(`/challenge/${challenge.id}` as never)} style={({ pressed }) => ({ backgroundColor: Colors.surface, diff --git a/apps/mobile/components/social/CreateChallengeSheet.tsx b/apps/mobile/components/social/CreateChallengeSheet.tsx index cecc0b2..90b6eb5 100644 --- a/apps/mobile/components/social/CreateChallengeSheet.tsx +++ b/apps/mobile/components/social/CreateChallengeSheet.tsx @@ -106,7 +106,7 @@ export function CreateChallengeSheet({ onClose }: CreateChallengeSheetProps) { {DURATIONS.map((d) => ( - setDuration(d)} style={{ diff --git a/apps/mobile/components/social/KudosButton.tsx b/apps/mobile/components/social/KudosButton.tsx index 6f0e684..b752ee9 100644 --- a/apps/mobile/components/social/KudosButton.tsx +++ b/apps/mobile/components/social/KudosButton.tsx @@ -1,5 +1,5 @@ import React, { useState } from 'react'; -import { Pressable, Text, View } from 'react-native'; +import { Pressable, Text } from 'react-native'; import Animated, { useSharedValue, useAnimatedStyle, @@ -45,7 +45,9 @@ export function KudosButton({ logId, initialCount, initialGiven }: KudosButtonPr return ( - 0 ? `, ${count} total` : ''}` : `Give kudos${count > 0 ? `, ${count} so far` : ''}`} + aria-pressed={given} onPress={handlePress} style={{ flexDirection: 'row', diff --git a/apps/mobile/components/ui/Button.tsx b/apps/mobile/components/ui/Button.tsx index 97b1589..cc8611f 100644 --- a/apps/mobile/components/ui/Button.tsx +++ b/apps/mobile/components/ui/Button.tsx @@ -33,7 +33,7 @@ export function Button({ ]; return ( - [ baseContainer, fullWidth ? { width: '100%' as const } : null, diff --git a/apps/mobile/components/ui/CrashScreen.tsx b/apps/mobile/components/ui/CrashScreen.tsx new file mode 100644 index 0000000..36e26ec --- /dev/null +++ b/apps/mobile/components/ui/CrashScreen.tsx @@ -0,0 +1,34 @@ +import React, { useEffect } from 'react'; +import { View, Text, Pressable } from 'react-native'; +import type { ErrorBoundaryProps } from 'expo-router'; +import { reportCrash } from '@/lib/crashReporter'; +import { Colors } from '@/constants/colors'; + +/** + * Shown instead of a blank screen when a screen crashes. The crash is + * reported, and Try again re-renders the screen. + */ +export function CrashScreen({ error, retry }: ErrorBoundaryProps) { + useEffect(() => { + reportCrash(error); + }, [error]); + + return ( + + 😵 + + Something went wrong + + + This screen hit an error. We've been told about it. Your data is safe. + + retry()} + accessibilityRole="button" + style={({ pressed }) => ({ marginTop: 8, backgroundColor: Colors.orange, borderRadius: 999, paddingHorizontal: 28, paddingVertical: 13, opacity: pressed ? 0.85 : 1 })} + > + Try again + + + ); +} diff --git a/apps/mobile/components/ui/Input.tsx b/apps/mobile/components/ui/Input.tsx index 245f2ae..dbe793d 100644 --- a/apps/mobile/components/ui/Input.tsx +++ b/apps/mobile/components/ui/Input.tsx @@ -3,7 +3,6 @@ import { TextInput, View, Text, - Pressable, type TextInputProps, } from 'react-native'; import { Colors } from '@/constants/colors'; diff --git a/apps/mobile/components/ui/OfflineBanner.tsx b/apps/mobile/components/ui/OfflineBanner.tsx new file mode 100644 index 0000000..842a1ea --- /dev/null +++ b/apps/mobile/components/ui/OfflineBanner.tsx @@ -0,0 +1,31 @@ +import React, { useSyncExternalStore } from 'react'; +import { Text, View } from 'react-native'; +import { onlineManager } from '@tanstack/react-query'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; +import { Colors } from '@/constants/colors'; + +const subscribe = (cb: () => void) => onlineManager.subscribe(cb); +const isOnline = () => onlineManager.isOnline(); +// The floating tab bar's height plus its gap from the bottom edge +const TAB_BAR_CLEARANCE = 84; + +/** + * A strip near the bottom while there's no connection, above the floating + * tab bar. It doesn't take touches, so nothing under it is blocked. + */ +export function OfflineBanner() { + const online = useSyncExternalStore(subscribe, isOnline, isOnline); + const insets = useSafeAreaInsets(); + if (online) return null; + return ( + + + You're offline. Showing your last saved data; changes need a connection. + + + ); +} diff --git a/apps/mobile/eslint.config.js b/apps/mobile/eslint.config.js new file mode 100644 index 0000000..be5e878 --- /dev/null +++ b/apps/mobile/eslint.config.js @@ -0,0 +1,20 @@ +// https://docs.expo.dev/guides/using-eslint/ +const { defineConfig } = require('eslint/config'); +const expoConfig = require('eslint-config-expo/flat'); + +module.exports = defineConfig([ + expoConfig, + { + ignores: ['dist/*', '.expo/*', 'node_modules/*'], + }, + { + rules: { + // Quotes and apostrophes in are fine in React Native; this rule is for HTML + 'react/no-unescaped-entities': 'off', + }, + }, + { + files: ['__tests__/**/*.ts'], + languageOptions: { globals: { describe: 'readonly', it: 'readonly', expect: 'readonly', jest: 'readonly' } }, + }, +]); diff --git a/apps/mobile/hooks/useHealthKit.ts b/apps/mobile/hooks/useHealthKit.ts index d3591df..cda641b 100644 --- a/apps/mobile/hooks/useHealthKit.ts +++ b/apps/mobile/hooks/useHealthKit.ts @@ -1,20 +1,21 @@ /** * Health data integration — Apple HealthKit (iOS) + Google Health Connect (Android) * - * ⚠️ REQUIRES BARE WORKFLOW - * These packages use native modules that are NOT available in Expo Go or the - * managed workflow. To activate: - * 1. Run: npx expo prebuild - * 2. For iOS: cd apps/mobile/ios && pod install - * 3. Add entitlement in Xcode: HealthKit capability - * 4. Uncomment the imports and real implementation below + * Not built yet, so react-native-health and react-native-health-connect are + * not installed: linking HealthKit into a build that never uses it gets App + * Store builds rejected. To build it: + * 1. npx expo install react-native-health react-native-health-connect + * 2. Add the HealthKit entitlement and NSHealthShareUsageDescription / + * NSHealthUpdateUsageDescription in app.json, and the Health Connect + * permissions and config plugin for Android + * 3. Uncomment the imports and real implementation below, and test on + * real devices with a development build * * Until then, the hook returns empty/safe defaults so the rest of the app compiles. */ import { useCallback } from 'react'; -import { Platform } from 'react-native'; -import { api } from '@/lib/api'; +// The real implementation also needs Platform (react-native) and api (@/lib/api) // ─── Bare-workflow implementation (uncomment after prebuild) ───────────────── // import AppleHealthKit, { HealthKitPermissions, HealthUnit } from 'react-native-health'; diff --git a/apps/mobile/hooks/useQuickFoods.ts b/apps/mobile/hooks/useQuickFoods.ts index d719556..b704917 100644 --- a/apps/mobile/hooks/useQuickFoods.ts +++ b/apps/mobile/hooks/useQuickFoods.ts @@ -1,19 +1,9 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { api } from '@/lib/api'; -import type { NormalizedFood } from '@/hooks/useFoodLog'; +import type { QuickFood } from '@/lib/quickFoods'; -/** A saved portion: the amounts are for the whole portion, not per 100 g. */ -export interface QuickFood { - name: string; - brand: string | null; - barcode: string | null; - calories: number; - proteinG: number; - carbsG: number; - fatG: number; - servingQty: number; - servingUnit: string; -} +export type { QuickFood } from '@/lib/quickFoods'; +export { foodKey, portionAsFood, portionLabel } from '@/lib/quickFoods'; export interface RecentFood extends QuickFood { key: string; @@ -27,36 +17,6 @@ export interface FavoriteFood extends QuickFood { key: string; } -/** Matches the server's: same name and brand, ignoring case and spacing. */ -export function foodKey(name: string, brand?: string | null) { - const norm = (s: string) => s.trim().toLowerCase().replace(/\s+/g, ' '); - return `${norm(name)}|${norm(brand ?? '')}`; -} - -/** A saved portion in the shape the log sheet takes. */ -export function portionAsFood(f: QuickFood): NormalizedFood { - return { - offId: '', - portion: true, - name: f.name, - brand: f.brand, - barcode: f.barcode, - calories: f.calories, - proteinG: f.proteinG, - carbsG: f.carbsG, - fatG: f.fatG, - servingQty: f.servingQty, - servingUnit: f.servingUnit, - imageUrl: null, - }; -} - -/** "150 g" or "2 servings" */ -export function portionLabel(f: Pick) { - const qty = Math.round(f.servingQty * 10) / 10; - return f.servingUnit === 'serving' ? `${qty} ${qty === 1 ? 'serving' : 'servings'}` : `${qty} ${f.servingUnit}`; -} - export function useRecentFoods() { return useQuery({ queryKey: ['food-recent'], diff --git a/apps/mobile/lib/crashReporter.ts b/apps/mobile/lib/crashReporter.ts new file mode 100644 index 0000000..b7c97f3 --- /dev/null +++ b/apps/mobile/lib/crashReporter.ts @@ -0,0 +1,52 @@ +import { Platform } from 'react-native'; +import Constants from 'expo-constants'; + +const API = process.env.EXPO_PUBLIC_API_URL; +// Don't flood the backend if something throws in a loop +const MAX_PER_SESSION = 10; +let sent = 0; +let currentScreen: string | undefined; + +/** The route the user is on, sent with crash reports. */ +export function setCrashScreen(screen: string) { + currentScreen = screen; +} + +/** + * Sends a crash to the backend's logs (POST /client-errors). Never throws: + * reporting a crash must not cause another. Works signed out, since a crash + * can happen before sign-in. Nothing personal is sent: the error, the screen + * and the app version. + */ +export function reportCrash(error: unknown) { + if (!API || sent >= MAX_PER_SESSION) return; + sent++; + const err = error instanceof Error ? error : new Error(String(error)); + fetch(`${API}/client-errors`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + message: `${err.name}: ${err.message}`.slice(0, 500), + stack: err.stack?.slice(0, 4000), + screen: currentScreen?.slice(0, 200), + platform: Platform.OS === 'ios' || Platform.OS === 'android' ? Platform.OS : 'web', + appVersion: Constants.expoConfig?.version, + }), + }).catch(() => {}); +} + +type GlobalHandler = (error: unknown, isFatal?: boolean) => void; + +/** Reports uncaught JavaScript errors as well, then lets React Native handle them as before. */ +export function installGlobalCrashHandler() { + const g = globalThis as unknown as { + ErrorUtils?: { getGlobalHandler(): GlobalHandler; setGlobalHandler(h: GlobalHandler): void }; + }; + const utils = g.ErrorUtils; + if (!utils) return; + const previous = utils.getGlobalHandler(); + utils.setGlobalHandler((error, isFatal) => { + reportCrash(error); + previous(error, isFatal); + }); +} diff --git a/apps/mobile/lib/queryClient.ts b/apps/mobile/lib/queryClient.ts index 0cf6779..78d2d99 100644 --- a/apps/mobile/lib/queryClient.ts +++ b/apps/mobile/lib/queryClient.ts @@ -1,5 +1,6 @@ import { AppState, Platform } from 'react-native'; -import { focusManager, MutationCache, QueryClient } from '@tanstack/react-query'; +import { focusManager, MutationCache, onlineManager, QueryClient } from '@tanstack/react-query'; +import NetInfo from '@react-native-community/netinfo'; import { showToast } from '@/stores/toastStore'; declare module '@tanstack/react-query' { @@ -16,6 +17,13 @@ export const queryClient = new QueryClient({ queries: { staleTime: 1000 * 60 * 2, // 2 minutes retry: 2, + // Offline, queries pause and keep showing what's cached, then refetch + // on reconnect (the default 'online' mode) + }, + mutations: { + // Saving fails straight away when offline, so a sheet doesn't spin + // until the connection returns; the offline banner explains why + networkMode: 'always', }, }, mutationCache: new MutationCache({ @@ -30,3 +38,13 @@ export const queryClient = new QueryClient({ if (Platform.OS !== 'web') { AppState.addEventListener('change', (status) => focusManager.setFocused(status === 'active')); } + +// React Query follows the browser's online/offline events on web; phones need +// NetInfo. Only the connection itself counts: the reachability probe fetches a +// Google URL, which some networks block, and would then report offline for +// good. null means "not checked yet", which isn't offline. +if (Platform.OS !== 'web') { + onlineManager.setEventListener((setOnline) => + NetInfo.addEventListener((state) => setOnline(state.isConnected !== false)), + ); +} diff --git a/apps/mobile/lib/quickFoods.ts b/apps/mobile/lib/quickFoods.ts new file mode 100644 index 0000000..5235841 --- /dev/null +++ b/apps/mobile/lib/quickFoods.ts @@ -0,0 +1,45 @@ +/** Recent and favourite foods: saved portions, logged again in a tap. */ +import type { NormalizedFood } from '@/hooks/useFoodLog'; + +/** A saved portion: the amounts are for the whole portion, not per 100 g. */ +export interface QuickFood { + name: string; + brand: string | null; + barcode: string | null; + calories: number; + proteinG: number; + carbsG: number; + fatG: number; + servingQty: number; + servingUnit: string; +} + +/** Matches the server's: same name and brand, ignoring case and spacing. */ +export function foodKey(name: string, brand?: string | null) { + const norm = (s: string) => s.trim().toLowerCase().replace(/\s+/g, ' '); + return `${norm(name)}|${norm(brand ?? '')}`; +} + +/** A saved portion in the shape the log sheet takes. */ +export function portionAsFood(f: QuickFood): NormalizedFood { + return { + offId: '', + portion: true, + name: f.name, + brand: f.brand, + barcode: f.barcode, + calories: f.calories, + proteinG: f.proteinG, + carbsG: f.carbsG, + fatG: f.fatG, + servingQty: f.servingQty, + servingUnit: f.servingUnit, + imageUrl: null, + }; +} + +/** "150 g" or "2 servings" */ +export function portionLabel(f: Pick) { + const qty = Math.round(f.servingQty * 10) / 10; + return f.servingUnit === 'serving' ? `${qty} ${qty === 1 ? 'serving' : 'servings'}` : `${qty} ${f.servingUnit}`; +} diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 08d5381..c3a51ba 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -7,13 +7,16 @@ "android": "cross-env NODE_OPTIONS=--no-experimental-require-module expo start --android", "ios": "cross-env NODE_OPTIONS=--no-experimental-require-module expo start --ios", "web": "cross-env NODE_OPTIONS=--no-experimental-require-module expo start --web", - "typecheck": "tsc --noEmit" + "typecheck": "tsc --noEmit", + "test": "jest", + "lint": "expo lint" }, "dependencies": { "@expo-google-fonts/dm-sans": "^0.4.2", "@expo-google-fonts/jetbrains-mono": "^0.4.1", "@expo/vector-icons": "^15.0.3", "@gorhom/bottom-sheet": "^5.2.8", + "@react-native-community/netinfo": "11.4.1", "@supabase/supabase-js": "^2.100.0", "@tanstack/react-query": "^5.95.2", "axios": "^1.13.6", @@ -38,8 +41,6 @@ "react-dom": "19.1.0", "react-native": "0.81.5", "react-native-gesture-handler": "~2.28.0", - "react-native-health": "^1.19.0", - "react-native-health-connect": "^3.5.0", "react-native-reanimated": "~4.1.1", "react-native-safe-area-context": "~5.6.0", "react-native-screens": "~4.16.0", @@ -50,10 +51,24 @@ "zustand": "^5.0.12" }, "devDependencies": { + "@types/jest": "^29.5.14", "@types/react": "~19.1.0", "babel-plugin-module-resolver": "^5.0.3", "babel-preset-expo": "~54.0.12", + "eslint": "^9.39.5", + "eslint-config-expo": "~10.0.0", + "jest": "^29.7.0", + "jest-expo": "~54.0.18", "typescript": "~5.9.2" }, - "private": true + "private": true, + "jest": { + "preset": "jest-expo", + "moduleNameMapper": { + "^@/(.*)$": "/$1" + }, + "testMatch": [ + "/__tests__/**/*.test.ts?(x)" + ] + } } diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 21eda14..ded2797 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -59,26 +59,49 @@ display rounding. when they end; leave and delete. - **Recent and favourite foods** for logging again in a tap. -## Phase 3 — Production readiness - -- **Backend:** drop the old `users.pushToken` column once no server - older than Phase 2 is running (kept so the live API doesn't break), a - real-device check of push alerts, health check, rate limiting, graceful shutdown, environment - validation at boot, structured logging and an exception filter, local JWT - verification instead of a Supabase call per request, missing indexes, - limits on unbounded lists. -- **Mobile:** error boundary and crash reporting, offline handling, - App Store config fixes, accessibility labels throughout. -- **Tests and CI:** service tests for the feed, leaderboard and - challenges; a mobile lint and test setup; GitHub Actions. +## Phase 3 — Production readiness ✅ + +- **Backend:** environment checked at boot, `GET /health` (used by + Railway), sign-in tokens verified locally against Supabase's published + key, rate limiting (300 requests a minute per session), request IDs + and one JSON log line per request, an exception filter that hides + internals, crash reports from the app (`POST /client-errors`), graceful + shutdown, missing indexes and caps on unbounded lists. +- **Mobile:** a recovery screen instead of a blank app when a screen + crashes, offline handling (cached screens, a banner, saves fail fast), + store config fixes (HTTPS-only store builds, no microphone permission, + an iOS privacy manifest, unused HealthKit packages removed) and + accessibility roles, labels and states throughout. +- **Tests and CI:** GitHub Actions runs the backend (migrations, drift + check, format, lint, types, unit and database tests, build) and the + mobile app (types, lint, unit tests) on every pull request. Database + tests cover the feed, leaderboard, privacy, alerts, challenges, weight + and quick foods. + +### After deploying Phase 3 + +- Apply `20261105130000_drop_users_push_token` to Supabase. It removes + the old `users.pushToken` column, which Phase 2 servers still read, so + only apply it once Railway runs this version. + +## Later + +- A real-device check of push alerts, photo picking and the keyboard in + sheets. +- Fuzzy user search (a `pg_trgm` index) once there are many users. +- Commit `package-lock.json` (it's git-ignored today) so CI and Railway + install the same versions. ## Needs the account owner - Google and Apple sign-in: enable the providers in Supabase and use the Apple Developer account. - HealthKit / Health Connect: a development build tested on real devices. -- Push notifications: an EAS project ID (the app needs one to get push - tokens), and an `EXPO_ACCESS_TOKEN` on the server if push security is - turned on. Crash reporting: a Sentry DSN. +- Push notifications: the app already has an EAS project ID; set + `EXPO_ACCESS_TOKEN` on the server if push security is turned on for + the Expo project. Crash reports go to the backend logs; add Sentry + later if you want dashboards and alerting. +- Railway: confirm the health check uses `/health` (set in + `railway.toml`) and optionally set `CORS_ORIGINS` to the web app's URL. - Password reset: add `grit://reset-password` (and the web app's `/reset-password` URL) to Supabase Auth's redirect URLs. diff --git a/packages/backend/.env.example b/packages/backend/.env.example index d1d0254..283cca8 100644 --- a/packages/backend/.env.example +++ b/packages/backend/.env.example @@ -26,3 +26,7 @@ NODE_ENV=development EXPO_ACCESS_TOKEN= # Optional: set to true to skip sending push notifications (e.g. locally) PUSH_DISABLED=false +# Optional: requests a minute allowed per signed-in session (default 300) +RATE_LIMIT_PER_MINUTE= +# Optional: comma-separated web origins allowed by CORS (default: any) +CORS_ORIGINS= diff --git a/packages/backend/package.json b/packages/backend/package.json index c9f6615..e4c1bdd 100644 --- a/packages/backend/package.json +++ b/packages/backend/package.json @@ -13,12 +13,12 @@ "start:debug": "nest start --debug --watch", "start:prod": "node dist/main", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", - "test": "jest", - "test:watch": "jest --watch", - "test:cov": "jest --coverage", - "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", - "test:e2e": "jest --config ./test/jest-e2e.json", - "test:db": "jest --config ./test/jest-db.json --runInBand" + "test": "node ../../node_modules/jest/bin/jest.js", + "test:watch": "node ../../node_modules/jest/bin/jest.js --watch", + "test:cov": "node ../../node_modules/jest/bin/jest.js --coverage", + "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register ../../node_modules/jest/bin/jest.js --runInBand", + "test:e2e": "node ../../node_modules/jest/bin/jest.js --config ./test/jest-e2e.json", + "test:db": "node ../../node_modules/jest/bin/jest.js --config ./test/jest-db.json --runInBand" }, "dependencies": { "@nestjs/axios": "^4.0.1", @@ -27,12 +27,14 @@ "@nestjs/core": "^11.0.1", "@nestjs/platform-express": "^11.0.1", "@nestjs/schedule": "^6.1.3", + "@nestjs/throttler": "^6.7.1", "@prisma/client": "^5.22.0", "@supabase/supabase-js": "^2.100.0", "@upstash/redis": "^1.37.0", "axios": "^1.13.6", "class-transformer": "^0.5.1", "class-validator": "^0.15.1", + "jose": "^5.10.0", "openai": "^7.27.0", "reflect-metadata": "^0.2.2", "rxjs": "^7.8.1" diff --git a/packages/backend/prisma/migrations/20261105120000_add_missing_indexes/migration.sql b/packages/backend/prisma/migrations/20261105120000_add_missing_indexes/migration.sql new file mode 100644 index 0000000..bda4994 --- /dev/null +++ b/packages/backend/prisma/migrations/20261105120000_add_missing_indexes/migration.sql @@ -0,0 +1,12 @@ +-- CreateIndex +CREATE INDEX "challenge_participants_userId_idx" ON "challenge_participants"("userId"); + +-- CreateIndex +CREATE INDEX "challenges_endedAt_endDate_idx" ON "challenges"("endedAt", "endDate"); + +-- CreateIndex +CREATE INDEX "habits_userId_isActive_idx" ON "habits"("userId", "isActive"); + +-- CreateIndex +CREATE INDEX "kudos_userId_idx" ON "kudos"("userId"); + diff --git a/packages/backend/prisma/migrations/20261105130000_drop_users_push_token/migration.sql b/packages/backend/prisma/migrations/20261105130000_drop_users_push_token/migration.sql new file mode 100644 index 0000000..7d67081 --- /dev/null +++ b/packages/backend/prisma/migrations/20261105130000_drop_users_push_token/migration.sql @@ -0,0 +1,5 @@ +-- Push tokens moved to push_devices in Phase 2. Apply this only once every +-- running server is on Phase 3 or later: Phase 2 servers still read the column. +-- AlterTable +ALTER TABLE "users" DROP COLUMN "pushToken"; + diff --git a/packages/backend/prisma/schema.prisma b/packages/backend/prisma/schema.prisma index 4d278ad..6be059e 100644 --- a/packages/backend/prisma/schema.prisma +++ b/packages/backend/prisma/schema.prisma @@ -21,8 +21,6 @@ model User { activityLevel String? gender String? dateOfBirth DateTime? - // Replaced by push_devices; kept until older servers are gone, then dropped - pushToken String? // Goal details from onboarding, editable in Goals & Targets goalWeightKg Float? @@ -160,6 +158,7 @@ model Kudos { user User @relation(fields: [userId], references: [id], onDelete: Cascade) @@unique([activityLogId, userId]) + @@index([userId]) @@map("kudos") } @@ -176,6 +175,7 @@ model Habit { user User @relation(fields: [userId], references: [id], onDelete: Cascade) logs HabitLog[] + @@index([userId, isActive]) @@map("habits") } @@ -218,6 +218,8 @@ model Challenge { participants ChallengeParticipant[] + // The hourly job looks for challenges past their end that haven't finished + @@index([endedAt, endDate]) @@map("challenges") } @@ -233,6 +235,7 @@ model ChallengeParticipant { user User @relation(fields: [userId], references: [id], onDelete: Cascade) @@unique([challengeId, userId]) + @@index([userId]) @@map("challenge_participants") } diff --git a/packages/backend/railway.toml b/packages/backend/railway.toml index d824e10..880f0bd 100644 --- a/packages/backend/railway.toml +++ b/packages/backend/railway.toml @@ -6,3 +6,5 @@ buildCommand = "npm run build" startCommand = "node dist/main" restartPolicyType = "ON_FAILURE" restartPolicyMaxRetries = 3 +healthcheckPath = "/health" +healthcheckTimeout = 60 diff --git a/packages/backend/src/alerts/alerts.service.ts b/packages/backend/src/alerts/alerts.service.ts index 104c77e..adcaff2 100644 --- a/packages/backend/src/alerts/alerts.service.ts +++ b/packages/backend/src/alerts/alerts.service.ts @@ -22,6 +22,7 @@ import { export const STREAK_ALERT_HOUR = 20; // 8pm local export const WEEKLY_ALERT_HOUR = 18; // 6pm local, on Sundays const MIN_STREAK = 2; +const USER_PAGE = 500; /** * Alerts that depend on logged data, sent at a fixed local time. The job runs @@ -59,36 +60,45 @@ export class AlertsService { } } - private usersAtLocalHour( + /** + * Everyone opted in for whom it's `hour` o'clock now, a page at a time so + * a large user base doesn't load into memory at once. + */ + private async *usersAtLocalHour( now: Date, hour: number, pref: 'notifStreak' | 'notifProgress', ) { - return this.prisma.user.findMany({ - where: { - [pref]: true, - OR: offsetRangesAtLocalHour(now, hour).map((r) => ({ - utcOffset: { gte: r.gte, lt: r.lt }, - })), - }, - select: { - id: true, - utcOffset: true, - activeMinutesGoal: true, - notifOffTrackOnly: true, - }, - }); + let cursor: string | undefined; + for (;;) { + const page = await this.prisma.user.findMany({ + where: { + [pref]: true, + OR: offsetRangesAtLocalHour(now, hour).map((r) => ({ + utcOffset: { gte: r.gte, lt: r.lt }, + })), + }, + select: { + id: true, + utcOffset: true, + activeMinutesGoal: true, + notifOffTrackOnly: true, + }, + orderBy: { id: 'asc' }, + take: USER_PAGE, + ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}), + }); + yield* page; + if (page.length < USER_PAGE) return; + cursor = page[page.length - 1].id; + } } /** 8pm: habits done yesterday, not yet today, with a streak worth keeping. */ async sendStreakAlerts(now: Date): Promise { - const users = await this.usersAtLocalHour( - now, - STREAK_ALERT_HOUR, - 'notifStreak', - ); + const users = this.usersAtLocalHour(now, STREAK_ALERT_HOUR, 'notifStreak'); let sent = 0; - for (const user of users) { + for await (const user of users) { const today = localDateOf(now, user.utcOffset); const habits = await this.prisma.habit.findMany({ where: { @@ -136,13 +146,13 @@ export class AlertsService { /** Sunday 6pm: the week so far. With "only when off track", only if behind. */ async sendWeeklyProgress(now: Date): Promise { - const users = await this.usersAtLocalHour( + const users = this.usersAtLocalHour( now, WEEKLY_ALERT_HOUR, 'notifProgress', ); let sent = 0; - for (const user of users) { + for await (const user of users) { const today = localDateOf(now, user.utcOffset); if (new Date(`${today}T00:00:00Z`).getUTCDay() !== 0) continue; // Sundays const monday = weekStart(today); diff --git a/packages/backend/src/app.controller.spec.ts b/packages/backend/src/app.controller.spec.ts deleted file mode 100644 index d22f389..0000000 --- a/packages/backend/src/app.controller.spec.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Test, TestingModule } from '@nestjs/testing'; -import { AppController } from './app.controller'; -import { AppService } from './app.service'; - -describe('AppController', () => { - let appController: AppController; - - beforeEach(async () => { - const app: TestingModule = await Test.createTestingModule({ - controllers: [AppController], - providers: [AppService], - }).compile(); - - appController = app.get(AppController); - }); - - describe('root', () => { - it('should return "Hello World!"', () => { - expect(appController.getHello()).toBe('Hello World!'); - }); - }); -}); diff --git a/packages/backend/src/app.controller.ts b/packages/backend/src/app.controller.ts index cce879e..26da44b 100644 --- a/packages/backend/src/app.controller.ts +++ b/packages/backend/src/app.controller.ts @@ -1,12 +1,90 @@ -import { Controller, Get } from '@nestjs/common'; -import { AppService } from './app.service'; +import { + Body, + Controller, + Get, + HttpCode, + Logger, + Post, + Req, + ServiceUnavailableException, +} from '@nestjs/common'; +import { SkipThrottle, Throttle } from '@nestjs/throttler'; +import { IsIn, IsOptional, IsString, MaxLength } from 'class-validator'; +import { PrismaService } from './prisma/prisma.service'; +import type { TracedRequest } from './observability/request-context'; + +class ClientErrorDto { + @IsString() + @MaxLength(500) + message: string; + + @IsOptional() + @IsString() + @MaxLength(4000) + stack?: string; + + // The screen (route) it happened on + @IsOptional() + @IsString() + @MaxLength(200) + screen?: string; + + @IsIn(['ios', 'android', 'web']) + platform: string; + + @IsOptional() + @IsString() + @MaxLength(40) + appVersion?: string; +} @Controller() export class AppController { - constructor(private readonly appService: AppService) {} + private readonly crashLog = new Logger('ClientCrash'); + private readonly started = Date.now(); + + constructor(private prisma: PrismaService) {} @Get() - getHello(): string { - return this.appService.getHello(); + @SkipThrottle() + root() { + return { name: 'grit-api' }; + } + + /** For the platform's health checks: up, and able to reach the database. */ + @Get('health') + @SkipThrottle() + async health() { + try { + await this.prisma.$queryRaw`SELECT 1`; + } catch { + throw new ServiceUnavailableException({ + status: 'error', + database: 'unreachable', + }); + } + return { + status: 'ok', + database: 'ok', + uptimeSeconds: Math.round((Date.now() - this.started) / 1000), + }; + } + + /** + * Crashes caught by the app's error boundary, written to the logs. No + * sign-in needed: a crash can happen before it. Throttled hard. + */ + @Post('client-errors') + @HttpCode(204) + @Throttle({ default: { limit: 10, ttl: 60_000 } }) + reportClientError(@Body() body: ClientErrorDto, @Req() req: TracedRequest) { + this.crashLog.error({ + requestId: req.requestId, + platform: body.platform, + appVersion: body.appVersion, + screen: body.screen, + message: body.message, + stack: body.stack, + }); } } diff --git a/packages/backend/src/app.module.ts b/packages/backend/src/app.module.ts index 724458a..5b8fe17 100644 --- a/packages/backend/src/app.module.ts +++ b/packages/backend/src/app.module.ts @@ -1,4 +1,6 @@ -import { Module } from '@nestjs/common'; +import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; +import { APP_FILTER, APP_GUARD } from '@nestjs/core'; +import { ThrottlerModule } from '@nestjs/throttler'; import { ConfigModule } from '@nestjs/config'; import { ScheduleModule } from '@nestjs/schedule'; import { PrismaModule } from './prisma/prisma.module'; @@ -15,11 +17,23 @@ import { WorkoutPlanModule } from './workout-plan/workout-plan.module'; import { AlertsModule } from './alerts/alerts.module'; import { ProgressModule } from './progress/progress.module'; import { AppController } from './app.controller'; -import { AppService } from './app.service'; +import { validateEnv } from './config/env'; +import { AllExceptionsFilter } from './observability/all-exceptions.filter'; +import { requestContext } from './observability/request-context'; +import { UserThrottlerGuard } from './observability/throttler.guard'; @Module({ imports: [ - ConfigModule.forRoot({ isGlobal: true }), + ConfigModule.forRoot({ isGlobal: true, validate: validateEnv }), + // Requests a minute per signed-in session (or per IP when signed out): + // well above what a person tapping around the app sends + ThrottlerModule.forRoot([ + { + name: 'default', + ttl: 60_000, + limit: Number(process.env.RATE_LIMIT_PER_MINUTE) || 300, + }, + ]), ScheduleModule.forRoot(), PrismaModule, AuthModule, @@ -36,6 +50,13 @@ import { AppService } from './app.service'; ProgressModule, ], controllers: [AppController], - providers: [AppService], + providers: [ + { provide: APP_GUARD, useClass: UserThrottlerGuard }, + { provide: APP_FILTER, useClass: AllExceptionsFilter }, + ], }) -export class AppModule {} +export class AppModule implements NestModule { + configure(consumer: MiddlewareConsumer) { + consumer.apply(requestContext).forRoutes('*'); + } +} diff --git a/packages/backend/src/app.service.ts b/packages/backend/src/app.service.ts deleted file mode 100644 index 927d7cc..0000000 --- a/packages/backend/src/app.service.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Injectable } from '@nestjs/common'; - -@Injectable() -export class AppService { - getHello(): string { - return 'Hello World!'; - } -} diff --git a/packages/backend/src/auth/auth.guard.ts b/packages/backend/src/auth/auth.guard.ts index 3411a1a..25e8042 100644 --- a/packages/backend/src/auth/auth.guard.ts +++ b/packages/backend/src/auth/auth.guard.ts @@ -4,20 +4,12 @@ import { Injectable, UnauthorizedException, } from '@nestjs/common'; -import { createClient } from '@supabase/supabase-js'; -import { ConfigService } from '@nestjs/config'; import type { AuthenticatedRequest } from '../common/current-user.decorator'; +import { TokenVerifier } from './token-verifier'; @Injectable() export class AuthGuard implements CanActivate { - private supabase; - - constructor(private config: ConfigService) { - this.supabase = createClient( - this.config.getOrThrow('SUPABASE_URL'), - this.config.getOrThrow('SUPABASE_ANON_KEY'), - ); - } + constructor(private verifier: TokenVerifier) {} async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); @@ -27,17 +19,10 @@ export class AuthGuard implements CanActivate { throw new UnauthorizedException('Missing authorization header'); } - const token = authHeader.slice(7); - const { - data: { user }, - error, - } = await this.supabase.auth.getUser(token); - - if (error || !user) { - throw new UnauthorizedException('Invalid or expired token'); - } + const user = await this.verifier.verify(authHeader.slice(7)); + if (!user) throw new UnauthorizedException('Invalid or expired token'); - request.user = { supabaseId: user.id, email: user.email }; + request.user = user; return true; } } diff --git a/packages/backend/src/auth/auth.module.ts b/packages/backend/src/auth/auth.module.ts index e9b6410..6fc0d15 100644 --- a/packages/backend/src/auth/auth.module.ts +++ b/packages/backend/src/auth/auth.module.ts @@ -1,12 +1,15 @@ -import { Module } from '@nestjs/common'; +import { Global, Module } from '@nestjs/common'; import { AuthGuard } from './auth.guard'; import { AuthController } from './auth.controller'; +import { TokenVerifier } from './token-verifier'; import { UsersModule } from '../users/users.module'; +// Global, because every feature module uses @UseGuards(AuthGuard) +@Global() @Module({ imports: [UsersModule], - providers: [AuthGuard], + providers: [AuthGuard, TokenVerifier], controllers: [AuthController], - exports: [AuthGuard], + exports: [AuthGuard, TokenVerifier], }) export class AuthModule {} diff --git a/packages/backend/src/auth/token-verifier.spec.ts b/packages/backend/src/auth/token-verifier.spec.ts new file mode 100644 index 0000000..c525067 --- /dev/null +++ b/packages/backend/src/auth/token-verifier.spec.ts @@ -0,0 +1,108 @@ +import { ConfigService } from '@nestjs/config'; +import { + createLocalJWKSet, + exportJWK, + generateKeyPair, + SignJWT, + type KeyLike, +} from 'jose'; +import { TokenVerifier } from './token-verifier'; + +const URL_ = 'https://proj.supabase.co'; +const ISS = `${URL_}/auth/v1`; + +describe('TokenVerifier', () => { + let privateKey: KeyLike; + let otherKey: KeyLike; + let verifier: TokenVerifier; + let getUser: jest.Mock; + + beforeAll(async () => { + const pair = await generateKeyPair('ES256'); + privateKey = pair.privateKey; + otherKey = (await generateKeyPair('ES256')).privateKey; + const jwk = { + ...(await exportJWK(pair.publicKey)), + kid: 'k1', + alg: 'ES256', + }; + const config = new ConfigService({ + SUPABASE_URL: URL_, + SUPABASE_ANON_KEY: 'anon', + }); + verifier = new TokenVerifier(config); + verifier.keys = createLocalJWKSet({ keys: [jwk] }); + }); + + beforeEach(() => { + getUser = jest.fn(); + verifier.supabase = { auth: { getUser } } as never; + }); + + const sign = ( + claims: Record, + key = privateKey, + opts: { exp?: string; iss?: string; aud?: string } = {}, + ) => + new SignJWT({ role: 'authenticated', email: 'a@b.co', ...claims }) + .setProtectedHeader({ alg: 'ES256', kid: 'k1' }) + .setSubject('user-1') + .setIssuer(opts.iss ?? ISS) + .setAudience(opts.aud ?? 'authenticated') + .setIssuedAt() + .setExpirationTime(opts.exp ?? '1h') + .sign(key); + + it('verifies a valid token locally, without calling Supabase', async () => { + expect(await verifier.verify(await sign({}))).toEqual({ + supabaseId: 'user-1', + email: 'a@b.co', + }); + expect(getUser).not.toHaveBeenCalled(); + }); + + it('rejects expired, forged, wrong-issuer and wrong-audience tokens', async () => { + const past = Math.floor(Date.now() / 1000) - 60; + const expired = await new SignJWT({ role: 'authenticated' }) + .setProtectedHeader({ alg: 'ES256', kid: 'k1' }) + .setSubject('user-1') + .setIssuer(ISS) + .setAudience('authenticated') + .setIssuedAt(past - 3600) + .setExpirationTime(past) + .sign(privateKey); + expect(await verifier.verify(expired)).toBeNull(); + expect(await verifier.verify(await sign({}, otherKey))).toBeNull(); + expect( + await verifier.verify( + await sign({}, privateKey, { iss: 'https://evil.co/auth/v1' }), + ), + ).toBeNull(); + expect( + await verifier.verify(await sign({}, privateKey, { aud: 'anon' })), + ).toBeNull(); + expect(await verifier.verify(await sign({ role: 'anon' }))).toBeNull(); + expect(await verifier.verify('not-a-jwt')).toBeNull(); + expect(getUser).not.toHaveBeenCalled(); + }); + + it('asks Supabase about older HS256 tokens', async () => { + const hs = await new SignJWT({ role: 'authenticated' }) + .setProtectedHeader({ alg: 'HS256' }) + .setSubject('user-2') + .sign(new TextEncoder().encode('secret-secret-secret-secret-secret')); + getUser.mockResolvedValue({ + data: { user: { id: 'user-2', email: 'c@d.co' } }, + error: null, + }); + expect(await verifier.verify(hs)).toEqual({ + supabaseId: 'user-2', + email: 'c@d.co', + }); + getUser.mockResolvedValue({ + data: { user: null }, + error: new Error('bad'), + }); + expect(await verifier.verify(hs)).toBeNull(); + }); +}); diff --git a/packages/backend/src/auth/token-verifier.ts b/packages/backend/src/auth/token-verifier.ts new file mode 100644 index 0000000..dc0ac94 --- /dev/null +++ b/packages/backend/src/auth/token-verifier.ts @@ -0,0 +1,83 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { createClient, type SupabaseClient } from '@supabase/supabase-js'; +import { + createRemoteJWKSet, + decodeProtectedHeader, + jwtVerify, + type JWTVerifyGetKey, +} from 'jose'; +import type { AuthUser } from '../common/current-user.decorator'; + +/** + * Checks Supabase access tokens. Tokens signed with the project's asymmetric + * key (ES256/RS256) are verified here against its published keys, cached, so + * a request doesn't wait on a call to Supabase. Anything else (older HS256 + * projects) is checked by asking Supabase, as before. + * + * Trade-off: a locally verified token stays valid until it expires (an hour) + * even after sign-out. Deleted accounts still fail, because their user row is + * gone. + */ +@Injectable() +export class TokenVerifier { + private readonly logger = new Logger(TokenVerifier.name); + private readonly issuer: string; + // Replaceable in tests + keys: JWTVerifyGetKey; + supabase: Pick; + + constructor(config: ConfigService) { + const url = config.getOrThrow('SUPABASE_URL').replace(/\/+$/, ''); + this.issuer = `${url}/auth/v1`; + this.keys = createRemoteJWKSet( + new URL(`${this.issuer}/.well-known/jwks.json`), + { + cacheMaxAge: 10 * 60_000, + cooldownDuration: 30_000, + }, + ); + this.supabase = createClient( + url, + config.getOrThrow('SUPABASE_ANON_KEY'), + ); + } + + /** The signed-in user, or null if the token isn't valid. */ + async verify(token: string): Promise { + let alg: string | undefined; + try { + alg = decodeProtectedHeader(token).alg; + } catch { + return null; // not a JWT at all + } + + if (alg === 'ES256' || alg === 'RS256') { + try { + const { payload } = await jwtVerify(token, this.keys, { + issuer: this.issuer, + audience: 'authenticated', + algorithms: [alg], + }); + if (typeof payload.sub !== 'string' || payload.role !== 'authenticated') + return null; + return { + supabaseId: payload.sub, + email: typeof payload.email === 'string' ? payload.email : undefined, + }; + } catch (err) { + const code = (err as { code?: string }).code ?? ''; + // A bad or expired token is final; only a key lookup problem falls back + if (!code.startsWith('ERR_JWKS') && code !== 'ERR_JOSE_GENERIC') + return null; + this.logger.warn( + `Key lookup failed (${code}); asking Supabase instead`, + ); + } + } + + const { data, error } = await this.supabase.auth.getUser(token); + if (error || !data.user) return null; + return { supabaseId: data.user.id, email: data.user.email }; + } +} diff --git a/packages/backend/src/challenges/challenges.service.ts b/packages/backend/src/challenges/challenges.service.ts index 25c5635..cd30c81 100644 --- a/packages/backend/src/challenges/challenges.service.ts +++ b/packages/backend/src/challenges/challenges.service.ts @@ -19,6 +19,8 @@ import { } from './challenge-rules'; const MAX_PARTICIPANTS = 8; +// Most recent challenges shown in the app +const MAX_LISTED = 100; const participantUser = { select: { id: true, displayName: true, avatarUrl: true, username: true }, }; @@ -152,6 +154,7 @@ export class ChallengesService { where, include: withParticipants, orderBy: { createdAt: 'desc' }, + take: MAX_LISTED, }); return challenges.map((c) => this.withTotals(c)); } @@ -265,8 +268,11 @@ export class ChallengesService { * challenge finish once. */ async finishEnded(now = new Date()): Promise { + // A batch per run; any left over are picked up an hour later const due = await this.prisma.challenge.findMany({ where: { endDate: { lte: now }, endedAt: null }, + orderBy: { endDate: 'asc' }, + take: 200, }); let finished = 0; for (const c of due) { diff --git a/packages/backend/src/config/env.spec.ts b/packages/backend/src/config/env.spec.ts new file mode 100644 index 0000000..631e639 --- /dev/null +++ b/packages/backend/src/config/env.spec.ts @@ -0,0 +1,43 @@ +import { validateEnv } from './env'; + +const good = { + DATABASE_URL: 'postgresql://u:p@localhost:5432/grit', + SUPABASE_URL: 'https://abc.supabase.co/', + SUPABASE_ANON_KEY: 'key', + AZURE_OPENAI_ENDPOINT: 'https://res.openai.azure.com', + AZURE_OPENAI_API_KEY: 'key', +}; + +describe('validateEnv', () => { + it('accepts a complete environment and trims the Supabase URL', () => { + expect(validateEnv(good).SUPABASE_URL).toBe('https://abc.supabase.co'); + }); + + it('lists every problem at once', () => { + expect(() => + validateEnv({ + ...good, + SUPABASE_ANON_KEY: '', + AZURE_OPENAI_API_KEY: undefined, + PORT: 'abc', + }), + ).toThrow( + /SUPABASE_ANON_KEY is missing[\s\S]*AZURE_OPENAI_API_KEY is missing[\s\S]*PORT must be/, + ); + }); + + it('rejects malformed URLs and connection strings', () => { + expect(() => validateEnv({ ...good, SUPABASE_URL: 'not a url' })).toThrow( + /SUPABASE_URL is not a valid URL/, + ); + expect(() => + validateEnv({ + ...good, + AZURE_OPENAI_ENDPOINT: 'http://res.openai.azure.com', + }), + ).toThrow(/must be an https URL/); + expect(() => validateEnv({ ...good, DATABASE_URL: 'mysql://x' })).toThrow( + /postgres/, + ); + }); +}); diff --git a/packages/backend/src/config/env.ts b/packages/backend/src/config/env.ts new file mode 100644 index 0000000..e0cd8ce --- /dev/null +++ b/packages/backend/src/config/env.ts @@ -0,0 +1,61 @@ +/** + * Checks the environment once at boot, so a missing or malformed setting + * stops the server with one clear message instead of failing on the first + * request that needs it. + */ + +const REQUIRED = [ + 'DATABASE_URL', + 'SUPABASE_URL', + 'SUPABASE_ANON_KEY', + 'AZURE_OPENAI_ENDPOINT', + 'AZURE_OPENAI_API_KEY', +] as const; + +const URLS = ['SUPABASE_URL', 'AZURE_OPENAI_ENDPOINT'] as const; + +export function validateEnv( + env: Record, +): Record { + const problems: string[] = []; + + for (const key of REQUIRED) { + const value = env[key]; + if (typeof value !== 'string' || value.trim() === '') { + problems.push(`${key} is missing`); + } + } + for (const key of URLS) { + const value = env[key]; + if (typeof value !== 'string' || value === '') continue; + try { + const url = new URL(value); + if (url.protocol !== 'https:' && url.hostname !== 'localhost') { + problems.push(`${key} must be an https URL`); + } + } catch { + problems.push(`${key} is not a valid URL`); + } + } + const db = env.DATABASE_URL; + if (typeof db === 'string' && db && !/^postgres(ql)?:\/\//.test(db)) { + problems.push('DATABASE_URL must be a postgres:// connection string'); + } + if (env.PORT !== undefined && env.PORT !== '') { + const port = Number(env.PORT); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + problems.push('PORT must be a number between 1 and 65535'); + } + } + + if (problems.length > 0) { + throw new Error( + `Invalid environment:\n - ${problems.join('\n - ')}\nSee packages/backend/.env.example.`, + ); + } + // Without a trailing slash, so URLs built from it are predictable + return { + ...env, + SUPABASE_URL: String(env.SUPABASE_URL).replace(/\/+$/, ''), + }; +} diff --git a/packages/backend/src/main.ts b/packages/backend/src/main.ts index ace5917..33e7cc3 100644 --- a/packages/backend/src/main.ts +++ b/packages/backend/src/main.ts @@ -1,12 +1,26 @@ import { NestFactory } from '@nestjs/core'; -import { ValidationPipe } from '@nestjs/common'; +import { ConsoleLogger, Logger, ValidationPipe } from '@nestjs/common'; +import type { NestExpressApplication } from '@nestjs/platform-express'; import { AppModule } from './app.module'; async function bootstrap() { - const app = await NestFactory.create(AppModule); + const production = process.env.NODE_ENV === 'production'; + const app = await NestFactory.create(AppModule, { + // One JSON object per line in production, which log tools can search + logger: new ConsoleLogger({ json: production, colors: !production }), + }); + + // Behind Railway's proxy: take the client's IP from X-Forwarded-For, so + // rate limits apply per caller rather than to the proxy + app.set('trust proxy', 1); + // CORS only matters for the web build. CORS_ORIGINS (comma-separated) + // narrows it; unset, any origin is allowed as before. + const origins = process.env.CORS_ORIGINS?.split(',') + .map((o) => o.trim()) + .filter(Boolean); app.enableCors({ - origin: true, // tighten in production + origin: origins?.length ? origins : true, credentials: true, }); @@ -20,7 +34,12 @@ async function bootstrap() { }), ); - await app.listen(process.env.PORT ?? 3000); - console.log(`GRIT backend running on port ${process.env.PORT ?? 3000}`); + // On SIGTERM (a deploy or restart), finish in-flight requests and close the + // database connections before exiting + app.enableShutdownHooks(); + + const port = process.env.PORT ?? 3000; + await app.listen(port); + new Logger('Bootstrap').log(`GRIT backend running on port ${port}`); } void bootstrap(); diff --git a/packages/backend/src/observability/all-exceptions.filter.spec.ts b/packages/backend/src/observability/all-exceptions.filter.spec.ts new file mode 100644 index 0000000..bbbaf79 --- /dev/null +++ b/packages/backend/src/observability/all-exceptions.filter.spec.ts @@ -0,0 +1,83 @@ +import { BadRequestException, NotFoundException } from '@nestjs/common'; +import { Prisma } from '@prisma/client'; +import { AllExceptionsFilter } from './all-exceptions.filter'; + +function run(exception: unknown, headersSent = false) { + const res = { + headersSent, + statusCode: 0, + body: undefined as unknown, + ended: false, + status: (code: number) => { + res.statusCode = code; + return res; + }, + json: (b: unknown) => { + res.body = b; + return res; + }, + end: () => { + res.ended = true; + }, + }; + const req = { requestId: 'req-123', method: 'GET', originalUrl: '/x?y=1' }; + const host = { + switchToHttp: () => ({ getResponse: () => res, getRequest: () => req }), + }; + const filter = new AllExceptionsFilter(); + (filter as unknown as { logger: { error: jest.Mock } }).logger = { + error: jest.fn(), + }; + filter.catch(exception, host as never); + return { + res, + logged: (filter as unknown as { logger: { error: jest.Mock } }).logger + .error, + }; +} + +describe('AllExceptionsFilter', () => { + it('keeps HTTP error bodies and adds the request ID', () => { + const { res, logged } = run( + new BadRequestException(['name must be a string']), + ); + expect(res.statusCode).toBe(400); + expect(res.body).toMatchObject({ + message: ['name must be a string'], + requestId: 'req-123', + }); + expect(logged).not.toHaveBeenCalled(); + expect(run(new NotFoundException('User not found')).res.body).toMatchObject( + { message: 'User not found' }, + ); + }); + + it('maps missing and duplicate records', () => { + const err = (code: string) => + new Prisma.PrismaClientKnownRequestError('x', { + code, + clientVersion: '5', + }); + expect(run(err('P2025')).res.statusCode).toBe(404); + expect(run(err('P2002')).res.statusCode).toBe(409); + }); + + it('hides unexpected errors and logs them', () => { + const { res, logged } = run(new Error('connection refused at 10.0.0.3')); + expect(res.statusCode).toBe(500); + expect(JSON.stringify(res.body)).not.toContain('10.0.0.3'); + expect(logged).toHaveBeenCalledWith( + expect.objectContaining({ + requestId: 'req-123', + path: '/x', + error: 'connection refused at 10.0.0.3', + }), + ); + }); + + it('ends a response that already started streaming', () => { + const { res } = run(new Error('stream broke'), true); + expect(res.ended).toBe(true); + expect(res.body).toBeUndefined(); + }); +}); diff --git a/packages/backend/src/observability/all-exceptions.filter.ts b/packages/backend/src/observability/all-exceptions.filter.ts new file mode 100644 index 0000000..9819991 --- /dev/null +++ b/packages/backend/src/observability/all-exceptions.filter.ts @@ -0,0 +1,89 @@ +import { + ArgumentsHost, + Catch, + ExceptionFilter, + HttpException, + HttpStatus, + Logger, +} from '@nestjs/common'; +import { Prisma } from '@prisma/client'; +import type { Response } from 'express'; +import type { TracedRequest } from './request-context'; + +/** + * The last stop for errors. HTTP errors keep their usual body (the app reads + * `message`); a missing or duplicate record becomes a 404 or 409 instead of a + * 500; anything else is logged with its stack and answered with a generic + * message, so internals never reach the client. Every error body carries the + * request ID. + */ +@Catch() +export class AllExceptionsFilter implements ExceptionFilter { + private readonly logger = new Logger('Exceptions'); + + catch(exception: unknown, host: ArgumentsHost) { + const ctx = host.switchToHttp(); + const res = ctx.getResponse(); + const req = ctx.getRequest(); + const requestId = req.requestId; + + const { status, body } = this.describe(exception); + if (status >= 500) { + this.logger.error({ + requestId, + method: req.method, + path: req.originalUrl?.split('?')[0], + error: + exception instanceof Error ? exception.message : String(exception), + stack: exception instanceof Error ? exception.stack : undefined, + }); + } + + // A streamed reply (the coach) may already have started + if (res.headersSent) { + res.end(); + return; + } + res.status(status).json({ ...body, requestId }); + } + + private describe(exception: unknown): { + status: number; + body: Record; + } { + if (exception instanceof HttpException) { + const response = exception.getResponse(); + const body = + typeof response === 'string' + ? { statusCode: exception.getStatus(), message: response } + : (response as Record); + return { status: exception.getStatus(), body }; + } + if (exception instanceof Prisma.PrismaClientKnownRequestError) { + if (exception.code === 'P2025') { + return { + status: 404, + body: { statusCode: 404, message: 'Not found', error: 'Not Found' }, + }; + } + if (exception.code === 'P2002') { + return { + status: 409, + body: { + statusCode: 409, + message: 'Already exists', + error: 'Conflict', + }, + }; + } + } + return { + status: HttpStatus.INTERNAL_SERVER_ERROR, + body: { + statusCode: 500, + message: 'Something went wrong. Please try again.', + error: 'Internal Server Error', + }, + }; + } +} diff --git a/packages/backend/src/observability/request-context.ts b/packages/backend/src/observability/request-context.ts new file mode 100644 index 0000000..f342a1b --- /dev/null +++ b/packages/backend/src/observability/request-context.ts @@ -0,0 +1,44 @@ +import { Logger } from '@nestjs/common'; +import { randomUUID } from 'crypto'; +import type { NextFunction, Request, Response } from 'express'; +import type { AuthUser } from '../common/current-user.decorator'; + +export type TracedRequest = Request & { requestId?: string; user?: AuthUser }; + +const logger = new Logger('HTTP'); +const SAFE_ID = /^[A-Za-z0-9._-]{8,64}$/; + +/** + * Gives every request an ID (the caller's `x-request-id` if sensible, else a + * new one), returns it in the response header, and logs one line per request + * with its outcome and duration. Error responses carry the same ID, so a + * user's report can be matched to the log line. + */ +export function requestContext( + req: TracedRequest, + res: Response, + next: NextFunction, +) { + const incoming = req.header('x-request-id'); + const id = incoming && SAFE_ID.test(incoming) ? incoming : randomUUID(); + req.requestId = id; + res.setHeader('x-request-id', id); + + const started = process.hrtime.bigint(); + res.on('finish', () => { + const path = req.originalUrl.split('?')[0]; + if (path === '/health' && res.statusCode < 400) return; // probes, every few seconds + const entry = { + requestId: id, + method: req.method, + path, + status: res.statusCode, + ms: Math.round(Number(process.hrtime.bigint() - started) / 1e6), + user: req.user?.supabaseId, + }; + if (res.statusCode >= 500) logger.error(entry); + else if (res.statusCode >= 400) logger.warn(entry); + else logger.log(entry); + }); + next(); +} diff --git a/packages/backend/src/observability/throttler.guard.ts b/packages/backend/src/observability/throttler.guard.ts new file mode 100644 index 0000000..1dba117 --- /dev/null +++ b/packages/backend/src/observability/throttler.guard.ts @@ -0,0 +1,27 @@ +import { Injectable } from '@nestjs/common'; +import { ThrottlerGuard } from '@nestjs/throttler'; +import { createHash } from 'crypto'; +import type { Request } from 'express'; + +/** + * Counts requests per caller: per signed-in session where there is one, so + * people sharing a mobile carrier's IP don't use up each other's allowance, + * and per IP otherwise. A made-up token only gets its own bucket, never + * someone else's. + */ +@Injectable() +export class UserThrottlerGuard extends ThrottlerGuard { + protected getTracker(req: Record): Promise { + const request = req as unknown as Request; + const auth = request.headers?.authorization; + const ip = request.ip ?? 'unknown'; + if (typeof auth === 'string' && auth.startsWith('Bearer ')) { + const session = createHash('sha256') + .update(auth.slice(7)) + .digest('hex') + .slice(0, 24); + return Promise.resolve(`${ip}:${session}`); + } + return Promise.resolve(ip); + } +} diff --git a/packages/backend/src/social/social.db-spec.ts b/packages/backend/src/social/social.db-spec.ts index cdb556f..9332931 100644 --- a/packages/backend/src/social/social.db-spec.ts +++ b/packages/backend/src/social/social.db-spec.ts @@ -244,4 +244,123 @@ describe('SocialService (database)', () => { await social.block(ben.supabaseId, ana.id); expect(await inbox(ben.id)).toHaveLength(0); }); + + it('pages the feed without skipping or repeating items that share a time', async () => { + const viewer = await db.user(); + const author = await db.user({ isPrivate: false }); + await social.follow(viewer.supabaseId, author.id); + const at = new Date(Date.now() - 3_600_000); + const habit = await db.prisma.habit.create({ + data: { userId: author.id, name: 'Read' }, + }); + for (let i = 0; i < 8; i++) { + await db.prisma.activityLog.create({ + data: { + userId: author.id, + activityType: 'yoga', + durationMin: 10, + loggedAt: at, + }, + }); + await db.prisma.foodLog.create({ + data: { + userId: author.id, + name: `Snack ${i}`, + mealType: 'snack', + calories: 100, + loggedAt: at, + }, + }); + } + for (let i = 0; i < 4; i++) { + await db.prisma.habitLog.create({ + data: { + habitId: habit.id, + userId: author.id, + loggedAt: new Date(Date.UTC(2026, 0, 1 + i)), + createdAt: at, + }, + }); + } + // Future-dated rows never show + await db.prisma.foodLog.create({ + data: { + userId: author.id, + name: 'Tomorrow', + mealType: 'snack', + calories: 1, + loggedAt: new Date(Date.now() + 86_400_000), + }, + }); + + const seen: string[] = []; + let cursor: string | undefined; + for (let page = 0; page < 10; page++) { + const items = await social.getFeed(viewer.supabaseId, cursor, 7); + if (items.length === 0) break; + seen.push(...items.map((i) => `${i.type}:${i.id}`)); + cursor = items[items.length - 1].cursor; + } + expect(seen).toHaveLength(20); + expect(new Set(seen).size).toBe(20); + }); + + it('ranks the weekly leaderboard by active minutes, counting only this week so far', async () => { + const me = await db.user(); + const fast = await db.user({ isPrivate: false }); + const slow = await db.user({ isPrivate: false }); + const stranger = await db.user({ isPrivate: false }); + await social.follow(me.supabaseId, fast.id); + await social.follow(me.supabaseId, slow.id); + const now = Date.now(); + await db.prisma.activityLog.createMany({ + data: [ + { + userId: fast.id, + activityType: 'running', + durationMin: 50, + steps: 6000, + loggedAt: new Date(now - 60_000), + }, + { + userId: slow.id, + activityType: 'walking', + durationMin: 20, + loggedAt: new Date(now - 60_000), + }, + { + userId: me.id, + activityType: 'yoga', + durationMin: 30, + loggedAt: new Date(now - 60_000), + }, + // Not counted: future, last month, and someone I don't follow + { + userId: slow.id, + activityType: 'walking', + durationMin: 500, + loggedAt: new Date(now + 3_600_000), + }, + { + userId: slow.id, + activityType: 'walking', + durationMin: 500, + loggedAt: new Date(now - 30 * 86_400_000), + }, + { + userId: stranger.id, + activityType: 'running', + durationMin: 999, + loggedAt: new Date(now - 60_000), + }, + ], + }); + const board = await social.getWeeklyLeaderboard(me.supabaseId, 0); + expect(board.map((e) => [e.user.id, e.activeMinutes, e.isMe])).toEqual([ + [fast.id, 50, false], + [me.id, 30, true], + [slow.id, 20, false], + ]); + expect(board[0].steps).toBe(6000); + }); }); diff --git a/packages/backend/src/social/social.service.ts b/packages/backend/src/social/social.service.ts index c6230fe..699b51e 100644 --- a/packages/backend/src/social/social.service.ts +++ b/packages/backend/src/social/social.service.ts @@ -382,6 +382,7 @@ export class SocialService { where: { blockerId: user.id }, include: { blocked: { select: PUBLIC_USER } }, orderBy: { createdAt: 'desc' }, + take: 500, }); return blocks.map((b) => ({ createdAt: b.createdAt, user: b.blocked })); }