This commit is contained in:
shafi54 2026-10-25 21:35:38 +05:30
parent 9d1ba3d0f9
commit d6685f156d
15 changed files with 460 additions and 82 deletions

View file

@ -154,7 +154,7 @@ Use these names in the cases below so the expected values stay consistent.
| APP-03 | edge | auth settled, signed out | still redirects home; auth walls are per-page |
| APP-04 | edge | auth layout loading | spinner, no stack |
| APP-05 | happy | auth layout loaded | auth stack renders |
| APP-06 | edge | drawer layout loading | pink loading spinner |
| APP-06 | edge | drawer layout loading | brand loading spinner (visible on white) |
| APP-07 | happy | drawer layout loaded | five tabs: Home, Offers, center 1 Hr Delivery, Stores, Me |
| APP-08 | edge | `hideTabsNav` has one true key | tab bar style is `display: none` |
| APP-09 | edge | all hide keys false | tab bar visible |
@ -1498,6 +1498,8 @@ Covered by HOME-81..98, plus:
| REGION-29 | edge | live resolution differs from cache | region/bound switch to the live answer |
| REGION-30 | edge | live resolution succeeds | persisted to StorageServiceCasual |
| REGION-31 | edge | live resolution null, region adopted from cache | region cleared for the chooser |
| REGION-32 | edge | persisted region/bound in SecureStore | hydrates before the launch decision; no “Finding your region” spinner |
| REGION-33 | edge | setRegion / clearRegion | selection persisted / removed from SecureStore |
| LOCSTORE-01 | happy | start once | one permission/fix; second start no-op |
| LOCSTORE-02 | error | denied | status denied, coords null |
| LOCSTORE-03 | edge | services off | status services-off |
@ -1513,9 +1515,9 @@ Covered by HOME-81..98, plus:
| ID | Type | Case and setup | Assertion |
| --- | --- | --- | --- |
| AUTH-01 | edge | no token/userId | signed out, not loading |
| AUTH-02 | edge | token+userId | authenticated, loading until getSelfData |
| AUTH-02 | edge | token+userId | authenticated and not loading (no block on getSelfData) |
| AUTH-03 | happy | selfData | user/userDetails populated |
| AUTH-04 | error | getSelfData fails | signed out; `deleteAuthToken` not called (current) |
| AUTH-04 | error | getSelfData UNAUTHORIZED | full logout; token removed |
| AUTH-05 | happy | loginWithToken | token/userId saved; authenticated; redirect handler |
| AUTH-06 | error | save token fails | loading false; throws |
| AUTH-07 | happy | login | login mutation, token save, refetch |
@ -1529,6 +1531,8 @@ Covered by HOME-81..98, plus:
| AUTH-15 | edge | redirect older than 24h | replace `/` |
| AUTH-16 | edge | no redirect state | `router.back()` |
| AUTH-17 | edge | corrupt redirect JSON | replace `/` |
| AUTH-18 | error | getSelfData fails (offline/5xx) | trusted session kept; token kept |
| AUTH-19 | edge | FORCE_LOGOUT_EVENT (401 from any endpoint) | session cleared; token removed |
| ROUTE-01 | edge | useAuthenticatedRoute loading | no redirect |
| ROUTE-02 | edge | authenticated | no redirect |
| ROUTE-03 | edge | unauthenticated | stores target/query/timestamp; push login |
@ -1542,6 +1546,7 @@ Covered by HOME-81..98, plus:
| TRPC-04 | edge | headers | bearer token when present |
| TRPC-05 | edge | timeout | aborts request |
| TRPC-06 | edge | upstream abort | forwarded |
| TRPC-07 | edge | 401 tRPC envelope (`error.data.code`) | emits force-logout |
| HIDE-01 | edge | focus with key | hideTabsNav key true |
| HIDE-02 | edge | default key | `default` |
| HIDE-03 | edge | blur | false |

View file

@ -27,7 +27,7 @@ export default function Layout() {
if (isLoading) {
return (
<View style={tw`flex-1 justify-center items-center bg-white`}>
<ActivityIndicator size="large" color={theme.colors.pink2} />
<ActivityIndicator size="large" color={theme.colors.brand500} />
</View>
);
}

View file

@ -1,15 +1,28 @@
import React, { createContext, useContext, useState, useEffect } from 'react';
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { getAuthToken, saveAuthToken, deleteAuthToken, saveUserId, getUserId } from '../../hooks/useJWT';
import { getCurrentUserId } from '@/utils/getCurrentUserId';
import { useRegister } from '@/src/api-hooks/auth.api';
import { AuthState, AuthContextType, LoginCredentials, RegisterData, User, UserDetails } from '@/src/types/auth';
import { trpc } from '@/src/trpc-client';
import { StorageServiceCasual } from 'common-ui';
import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs';
import { useQueryClient } from '@tanstack/react-query';
import { useRouter } from 'expo-router';
import { DeviceEventEmitter } from 'react-native';
import constants from '@/src/constants';
import type { AuthRedirectOptions, ReactParentComponent } from '@packages/shared';
/**
* Only a credential rejection proves the stored token is dead. Offline, a
* timeout or a 5xx must never sign the user out: the stored credentials are
* trusted until the backend actually says no.
*/
const isCredentialError = (error: unknown): boolean => {
const trpcError = error as { data?: { code?: string }; shape?: { data?: { code?: string } } } | null;
const code = trpcError?.data?.code ?? trpcError?.shape?.data?.code;
return code === 'UNAUTHORIZED' || code === 'FORBIDDEN';
};
export interface RedirectState extends AuthRedirectOptions {
targetUrl: string;
queryParams: Record<string, any>;
@ -33,6 +46,23 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
const loginMutation = trpc.user.auth.login.useMutation();
const registerMutation = useRegister();
// Drop the session everywhere: stored token, cached queries and state.
const clearSession = useCallback(async (): Promise<void> => {
try {
await deleteAuthToken();
} catch {
// Still clear local state even if deleting the token fails.
}
queryClient.clear();
setAuthState({
user: null,
userDetails: null,
isAuthenticated: false,
isLoading: false,
token: null,
});
}, [queryClient]);
// Initialize auth state on app startup
useEffect(() => {
const initializeAuth = async () => {
@ -41,7 +71,8 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
const userId = await getCurrentUserId();
if (token && userId) {
// Use existing token, only fetch user data
// Trust the stored credentials: render the app now and let the
// background getSelfData read confirm (or reject) them.
setAuthState({
user: {
id: userId,
@ -53,7 +84,7 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
},
userDetails: null,
isAuthenticated: true,
isLoading: true, // Keep loading while fetching user data
isLoading: false,
token,
});
} else {
@ -102,18 +133,22 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
userDetails: user,
isLoading: false,
}));
} else if (selfDataError && authState.isAuthenticated) {
// If token is invalid, clear auth state
// deleteAuthToken();
setAuthState({
user: null,
userDetails: null,
isAuthenticated: false,
isLoading: false,
token: null,
});
} else if (selfDataError && authState.isAuthenticated && isCredentialError(selfDataError)) {
// The backend rejected the stored token: drop the session.
void clearSession();
}
}, [selfData, selfDataError, authState.isAuthenticated]);
// Any other failure (offline, timeout, 5xx) keeps the trusted session; the
// screen that needs the data shows its own error/retry.
}, [selfData, selfDataError, authState.isAuthenticated, clearSession]);
// src/trpc-client.ts emits this whenever the API answers 401 UNAUTHORIZED, so
// a revoked token is dropped even when the failing call is not getSelfData.
useEffect(() => {
const subscription = DeviceEventEmitter.addListener(FORCE_LOGOUT_EVENT, () => {
void clearSession();
});
return () => subscription.remove();
}, [clearSession]);
// Helper function to handle redirect after successful login
const handlePostLoginRedirect = async () => {
@ -257,29 +292,8 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
}
};
const logout = async (): Promise<void> => {
try {
await deleteAuthToken();
queryClient.clear();
setAuthState({
user: null,
userDetails: null,
isAuthenticated: false,
isLoading: false,
token: null,
});
} catch (error) {
// Still clear local state even if deleteJWT fails
queryClient.clear();
setAuthState({
user: null,
userDetails: null,
isAuthenticated: false,
isLoading: false,
token: null,
});
}
};
// Manual logout and forced logout (rejected credentials) are the same thing.
const logout = clearSession;
const updateUser = (userData: Partial<User>): void => {
setAuthState(prev => ({

View file

@ -67,7 +67,7 @@ export interface UseRegionResult {
bound: RegionBoundSummary | null
/** Monotonic marker bumped on every region change; use it to ignore stale responses. */
regionGeneration: number
/** Always true: the region store is in-memory (not persisted). */
/** True once the persisted region/bound has been read (or found empty). */
hydrated: boolean
/** Latest device coordinates, if the launch fix succeeded. */
coords: { latitude: number; longitude: number } | null
@ -107,15 +107,22 @@ export function useRegion(): UseRegionResult {
const regionGeneration = useRegionStore((state) => state.regionGeneration)
const setRegion = useRegionStore((state) => state.setRegion)
const clearRegion = useRegionStore((state) => state.clearRegion)
// The persisted selection hydrates asynchronously (SecureStore). Until it has
// been read the gate keeps its neutral spinner, so a warm launch paints with
// the previous region instead of "Finding your region".
const hydrated = useRegionStore((state) => state.hydrated)
const hydrate = useRegionStore((state) => state.hydrate)
const coords = useLocationStore((state) => state.coords)
const locationStatus = useLocationStore((state) => state.status)
const startTracking = useLocationStore((state) => state.start)
const refreshTracking = useLocationStore((state) => state.refresh)
// The region store is in-memory (not persisted), so there is nothing to
// hydrate before we can decide.
const hydrated = true
// Every consumer calls this; the store makes it single-flight.
useEffect(() => {
void hydrate()
}, [hydrate])
// True once the launch location check has a definitive outcome.
const [startupResolved, setStartupResolved] = useState(false)
@ -267,13 +274,20 @@ export function useRegion(): UseRegionResult {
const boundId = storedBoundId ?? activeBoundId
// Take the single launch fix — even when a region is already saved, so a
// device that has moved to another region is detected on startup.
// Take the single launch fix immediately — even when a region is already
// saved, so a device that has moved to another region is detected on startup.
// It runs in parallel with the SecureStore read.
useEffect(() => {
startTracking()
}, [startTracking])
// The launch baseline is the region the app opened with. It is recorded only
// after hydration, so a restored selection counts as launch state (and may be
// switched by the decision) rather than as a manual pick.
useEffect(() => {
if (!hydrated) return
if (startupLaunchRegionId === undefined) startupLaunchRegionId = regionId
startTracking()
}, [hydrated, regionId, startTracking])
}, [hydrated, regionId])
// Stable, rounded input so GPS jitter doesn't churn the query key.
const lat = coords ? Math.round(coords.latitude * 1e5) / 1e5 : 0

View file

@ -32,6 +32,18 @@ export interface CachedLocationResolution {
result: ResolvedRegion | null
}
/**
* The browsing region + bound selected at the end of the last session. Hydrated
* before the first paint so startup can render the app and read the regional
* CDN files immediately; the launch decision still re-resolves the location and
* corrects (or clears) this selection when the device/address says otherwise.
*/
export interface CachedRegionSelection {
regionId: number
region: RegionSummary
boundId: number | null
}
/**
* Small, user-scoped snapshots of the responses that decide where the app
* starts:
@ -45,11 +57,13 @@ export interface CachedLocationResolution {
// SecureStore only accepts alphanumeric, ".", "-" and "_" in keys.
export const REGION_LIST_CACHE_KEY = 'region_cache.list_regions.v1'
export const LOCATION_RESOLUTION_CACHE_KEY = 'region_cache.location_resolution.v1'
export const REGION_SELECTION_CACHE_KEY = 'region_cache.selection.v1'
export const userAddressesCacheKey = (userId: number) =>
`region_cache.user_addresses.v1.${userId}`
let lastWrittenRegions: string | null = null
let lastWrittenResolution: string | null = null
let lastWrittenSelection: string | null = null
const lastWrittenAddresses = new Map<number, string>()
function parseJson(raw: string | null): unknown {
@ -150,3 +164,33 @@ export async function writeCachedLocationResolution(
const stored = await StorageServiceCasual.setItem(LOCATION_RESOLUTION_CACHE_KEY, serialized)
if (stored) lastWrittenResolution = serialized
}
function isCachedRegionSelection(value: unknown): value is CachedRegionSelection {
if (value == null || typeof value !== 'object') return false
const candidate = value as Partial<CachedRegionSelection>
if (typeof candidate.regionId !== 'number') return false
const region = candidate.region as Partial<RegionSummary> | undefined
if (region == null || typeof region !== 'object') return false
if (region.id !== candidate.regionId || typeof region.name !== 'string') return false
if (candidate.boundId !== null && !isFiniteNumber(candidate.boundId)) return false
return true
}
export async function readCachedRegionSelection(): Promise<CachedRegionSelection | null> {
const parsed = parseJson(await StorageServiceCasual.getItem(REGION_SELECTION_CACHE_KEY))
return isCachedRegionSelection(parsed) ? parsed : null
}
export async function writeCachedRegionSelection(
selection: CachedRegionSelection
): Promise<void> {
const serialized = JSON.stringify(selection)
if (serialized === lastWrittenSelection) return
const stored = await StorageServiceCasual.setItem(REGION_SELECTION_CACHE_KEY, serialized)
if (stored) lastWrittenSelection = serialized
}
export async function clearCachedRegionSelection(): Promise<void> {
lastWrittenSelection = null
await StorageServiceCasual.removeItem(REGION_SELECTION_CACHE_KEY)
}

View file

@ -1,14 +1,19 @@
import { create } from 'zustand'
import type { RegionSummary } from '@packages/shared'
import {
clearCachedRegionSelection,
readCachedRegionSelection,
writeCachedRegionSelection,
} from '@/src/lib/region-cache'
// Browsing region — the region the user is currently shopping in.
//
// Deliberately NOT persisted: at each launch the region is re-derived from the
// device location, or from the user's default / chosen address. A persisted
// region would let the app show a stale region (e.g. the last one) whenever the
// location is unavailable, instead of asking the user to grant location or add
// an address. `regionGeneration` is a monotonic marker bumped on every change so
// stale regional responses can be ignored.
// The selection (region + bound) is persisted so a launch can render the app
// and start the regional CDN reads without waiting for the device fix, auth or
// the network. It is NOT trusted blindly: `useRegion` still resolves the launch
// location / default address and switches (or clears) the region when the live
// answer differs. `regionGeneration` is a monotonic marker bumped on every real
// change so stale regional responses can be ignored.
interface RegionStore {
selectedRegionId: number | null
selectedRegion: RegionSummary | null
@ -19,16 +24,50 @@ interface RegionStore {
*/
selectedBoundId: number | null
regionGeneration: number
/** True once the persisted selection has been read (or found empty). */
hydrated: boolean
/**
* Read the persisted selection once. Idempotent and safe to call from every
* consumer; `hydrated` flips even when there is nothing stored.
*/
hydrate: () => Promise<void>
setRegion: (region: RegionSummary, boundId?: number | null) => void
clearRegion: () => void
}
export const useRegionStore = create<RegionStore>((set) => ({
// Single-flight: useRegion is consumed by several components and they all call
// hydrate() on mount.
let hydration: Promise<void> | null = null
export const useRegionStore = create<RegionStore>((set, get) => ({
selectedRegionId: null,
selectedRegion: null,
selectedBoundId: null,
regionGeneration: 0,
setRegion: (region, boundId = null) =>
hydrated: false,
hydrate: () => {
if (hydration) return hydration
hydration = (async () => {
try {
const cached = await readCachedRegionSelection()
// A region chosen while the read was in flight wins.
if (cached && get().selectedRegionId == null) {
set({
selectedRegionId: cached.regionId,
selectedRegion: cached.region,
selectedBoundId: cached.boundId,
})
}
} finally {
set({ hydrated: true })
}
})()
return hydration
},
setRegion: (region, boundId = null) => {
let changed = false
set((state) => {
// No-op when nothing actually changed: keeps regionGeneration stable
// and prevents effect loops that re-apply the same region.
@ -40,14 +79,21 @@ export const useRegionStore = create<RegionStore>((set) => ({
) {
return state
}
changed = true
return {
selectedRegionId: region.id,
selectedRegion: region,
selectedBoundId: boundId,
regionGeneration: state.regionGeneration + 1,
}
}),
clearRegion: () =>
})
if (changed) {
void writeCachedRegionSelection({ regionId: region.id, region, boundId })
}
},
clearRegion: () => {
let changed = false
set((state) => {
if (
state.selectedRegionId == null &&
@ -56,11 +102,16 @@ export const useRegionStore = create<RegionStore>((set) => ({
) {
return state
}
changed = true
return {
selectedRegionId: null,
selectedRegion: null,
selectedBoundId: null,
regionGeneration: state.regionGeneration + 1,
}
}),
})
if (changed) {
void clearCachedRegionSelection()
}
},
}))

View file

@ -40,11 +40,11 @@ export const trpcClient = createTRPCProxyClient<AppRouter>({
const data = await response
.clone()
.json()
.catch(() => ({}));
let code = "";
if (data[0]?.error || data?.error) {
code = data[0]?.error?.message || data?.error?.message;
}
.catch(() => null);
const entry = Array.isArray(data) ? data[0] : data;
// tRPC puts the code on error.data.code; a plain handler may only send
// a message. Accept both so a revoked token always forces a logout.
const code = entry?.error?.data?.code ?? entry?.error?.message;
if (code === "UNAUTHORIZED") {
DeviceEventEmitter.emit(FORCE_LOGOUT_EVENT);
}

View file

@ -92,12 +92,12 @@ describe('app entry + route layouts (APP-01..APP-24)', () => {
expect(view.UNSAFE_getByType(Stack)).toBeTruthy()
})
it('APP-06: drawer layout while loading shows the pink spinner', () => {
it('APP-06: drawer layout while loading shows the brand spinner', () => {
authState({ isLoading: true })
const view = renderWithProviders(<DrawerLayout />, { auth: false })
const spinner = view.UNSAFE_getByType(ActivityIndicator)
expect(spinner.props.color).toBe(theme.colors.pink2)
expect(spinner.props.color).toBe(theme.colors.brand500)
})
it('APP-07: loaded drawer layout declares the five tabs', () => {

View file

@ -47,6 +47,10 @@ export function resetStores() {
selectedRegion: null,
selectedBoundId: null,
regionGeneration: 0,
// Most cases exercise the launch decision with an empty store; they do not
// test the SecureStore hydration, so start settled (the persistence tests
// flip this back to false).
hydrated: true,
})
useSlotStore.setState({ slotId: undefined, storeId: undefined })
useFlashNavigationStore.setState({ shouldNavigateToCart: false })

View file

@ -8,9 +8,10 @@
* is recorded rather than navigated.
*/
import * as React from 'react'
import { Text } from 'react-native'
import { Text, DeviceEventEmitter } from 'react-native'
import { act, waitFor } from '@testing-library/react-native'
import { StorageService } from 'common-ui'
import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs'
import { useAuth } from '@/src/contexts/AuthContext'
import { getAuthToken, getUserId } from '@/hooks/useJWT'
import constants from '@/src/constants'
@ -61,12 +62,12 @@ describe('AuthContext', () => {
expect(ctx.user).toBeNull()
})
it('AUTH-02: is authenticated but still loading while getSelfData is pending', async () => {
it('AUTH-02: trusts the stored token and does not block on getSelfData', async () => {
setProcedure('user.user.getSelfData', { mode: 'pending' })
renderWithProviders(<AuthProbe />, { auth: 'in' })
await waitFor(() => expect(ctx.isAuthenticated).toBe(true))
expect(ctx.isLoading).toBe(true)
expect(ctx.isLoading).toBe(false)
expect(ctx.token).toBe(TEST_JWT)
})
@ -79,20 +80,20 @@ describe('AuthContext', () => {
expect(ctx.userDetails).toEqual(AUTH_USER_FULL)
})
it('AUTH-04: signs out when getSelfData fails but keeps the stored token', async () => {
it('AUTH-04: logs out when the backend rejects the stored token', async () => {
setProcedure('user.user.getSelfData', {
mode: 'error',
error: new Error('unauthorized'),
errorCode: 'UNAUTHORIZED',
})
renderWithProviders(<AuthProbe />, { auth: 'in' })
// `isAuthenticated` starts false, so wait for the bootstrap + self read to
// settle (the signed-in state is too short-lived for a poll to catch), then
// assert the failure signed the user out.
await waitFor(() => expect(ctx.isLoading).toBe(false))
// The token is present until the rejection lands, so this waits for the
// effect instead of racing the initial signed-out render.
await waitFor(() => expect(__snapshot().authToken).toBeUndefined())
expect(ctx.isAuthenticated).toBe(false)
// Current behaviour: deleteAuthToken() is commented out.
expect(__snapshot().authToken).toBe(TEST_JWT)
expect(ctx.isLoading).toBe(false)
expect(ctx.user).toBeNull()
})
it('AUTH-05: loginWithToken stores token/userId and runs the redirect handler', async () => {
@ -284,4 +285,32 @@ describe('AuthContext', () => {
await waitFor(() => expect(router.replace).toHaveBeenCalledWith('/'))
})
it('AUTH-18: a non-credential getSelfData failure keeps the trusted session', async () => {
// Offline / timeout / 5xx must not wipe the credentials.
setProcedure('user.user.getSelfData', {
mode: 'error',
error: new Error('network down'),
errorCode: 'INTERNAL_SERVER_ERROR',
})
renderWithProviders(<AuthProbe />, { auth: 'in' })
await waitFor(() => expect(ctx.isLoading).toBe(false))
expect(ctx.isAuthenticated).toBe(true)
expect(ctx.user).not.toBeNull()
expect(__snapshot().authToken).toBe(TEST_JWT)
})
it('AUTH-19: a force-logout event (401 from any endpoint) clears the session', async () => {
renderWithProviders(<AuthProbe />, { auth: 'in' })
await waitFor(() => expect(ctx.isAuthenticated).toBe(true))
act(() => {
DeviceEventEmitter.emit(FORCE_LOGOUT_EVENT)
})
await waitFor(() => expect(__snapshot().authToken).toBeUndefined())
expect(ctx.isAuthenticated).toBe(false)
expect(ctx.token).toBeNull()
})
})

View file

@ -256,6 +256,21 @@ describe('trpc client link', () => {
await pending
})
it('TRPC-07: emits force-logout on a 401 tRPC envelope (error.data.code)', async () => {
const emitSpy = jest.spyOn(DeviceEventEmitter, 'emit')
;(global as any).fetch = jest.fn(async () =>
makeResponse(401, [
{ error: { message: 'Unauthorized', data: { code: 'UNAUTHORIZED', httpStatus: 401 } } },
])
)
await realTrpcClient.common.healthCheck.query().catch(() => undefined)
await flush()
expect(emitSpy).toHaveBeenCalledWith(FORCE_LOGOUT_EVENT)
emitSpy.mockRestore()
})
})
/* -------------------------------------------------------------------------- */

View file

@ -827,6 +827,55 @@ describe('useRegion', () => {
}
})
})
it('REGION-32: a persisted region/bound is hydrated before the launch decision', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1 } = ctx.fixtures
ctx.auth.__setAuthState({ isAuthenticated: false, isLoading: false })
ctx.locationMock.__configure({ permission: 'denied' })
// Opt out of the reset helper's settled store: this case starts cold and
// must be hydrated from SecureStore.
ctx.regionStore.setState({ hydrated: false })
ctx.secure.__set(
ctx.regionCache.REGION_SELECTION_CACHE_KEY,
JSON.stringify({ regionId: REGION_1.id, region: REGION_1, boundId: 7 })
)
const { result, view } = ctx.renderRegion()
// Before the read lands the gate keeps its neutral state; the labelled
// "Finding your region" spinner is not used because the store reports
// itself as not hydrated yet.
expect(result.current.hydrated).toBe(false)
await ctx.testUtils.flush(4)
expect(result.current.hydrated).toBe(true)
expect(result.current.regionId).toBe(REGION_1.id)
expect(result.current.boundId).toBe(7)
expect(result.current.isResolvingRegion).toBe(false)
view.unmount()
})
})
it('REGION-33: setRegion persists the selection and clearRegion removes it', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1 } = ctx.fixtures
ctx.regionStore.getState().setRegion(REGION_1, 7)
await ctx.testUtils.flush(2)
const stored = ctx.secure.__snapshot()[ctx.regionCache.REGION_SELECTION_CACHE_KEY]
expect(JSON.parse(stored as string)).toMatchObject({ regionId: REGION_1.id, boundId: 7 })
ctx.regionStore.getState().clearRegion()
await ctx.testUtils.flush(2)
expect(
ctx.secure.__snapshot()[ctx.regionCache.REGION_SELECTION_CACHE_KEY]
).toBeUndefined()
})
})
})

View file

@ -1,8 +1,20 @@
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react'
import { trpc } from './trpc-client'
import { trpc, setUnauthorizedHandler } from './trpc-client'
import { useNavigate } from '@tanstack/react-router'
import type { User as SharedUser, AuthStateCore } from '@packages/shared'
/**
* Only a credential rejection proves the stored token is dead. Offline, a
* timeout or a 5xx must never sign the user out.
*/
const isCredentialError = (error: unknown): boolean => {
const trpcError = error as
| { data?: { code?: string }; shape?: { data?: { code?: string } } }
| null
const code = trpcError?.data?.code ?? trpcError?.shape?.data?.code
return code === 'UNAUTHORIZED' || code === 'FORBIDDEN'
}
// Auth user — serialized view of the shared User (optional name, no createdAt)
type User = Pick<SharedUser, 'id' | 'email'> &
Partial<Omit<SharedUser, 'id' | 'email' | 'createdAt' | 'mobile'>> & {
@ -41,10 +53,12 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
const storedToken = localStorage.getItem('auth_token')
const storedUserId = localStorage.getItem('user_id')
if (storedToken && storedUserId) {
// Trust the stored credentials: render now, let getSelfData confirm them.
setState((prev) => ({
...prev,
token: storedToken,
isAuthenticated: true,
isLoading: false,
}))
} else {
setState((prev) => ({ ...prev, isLoading: false }))
@ -52,7 +66,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
}, [])
// Fetch user data when token is available
const { data: selfData } = trpc.user.user.getSelfData.useQuery(undefined, {
const { data: selfData, error: selfDataError } = trpc.user.user.getSelfData.useQuery(undefined, {
enabled: !!state.token && state.isAuthenticated,
retry: 1,
})
@ -65,10 +79,8 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
userDetails: selfData.data.user,
isLoading: false,
}))
} else if (selfData === undefined && state.token) {
// Token might be invalid
}
}, [selfData, state.token])
}, [selfData])
const login = useCallback((token: string, user: User) => {
localStorage.setItem('auth_token', token)
@ -103,6 +115,19 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
navigate({ to: '/login' })
}, [navigate])
// A rejected token drops the session; any other failure keeps it.
useEffect(() => {
if (selfDataError && state.isAuthenticated && isCredentialError(selfDataError)) {
logout()
}
}, [selfDataError, state.isAuthenticated, logout])
// Any endpoint that answers 401 UNAUTHORIZED drops the session.
useEffect(() => {
setUnauthorizedHandler(logout)
return () => setUnauthorizedHandler(null)
}, [logout])
const updateUser = useCallback((user: User) => {
setState((prev) => ({ ...prev, user }))
}, [])

View file

@ -9,11 +9,40 @@ export const BASE_API_URL =
export const trpc = createTRPCReact<AppRouter>()
type UnauthorizedHandler = () => void
let unauthorizedHandler: UnauthorizedHandler | null = null
/** Registered by the auth provider; called when the API answers 401 UNAUTHORIZED. */
export function setUnauthorizedHandler(handler: UnauthorizedHandler | null) {
unauthorizedHandler = handler
}
/**
* Mirrors the user app's FORCE_LOGOUT_EVENT: a token the backend rejects must
* drop the session, even when the failing call was not getSelfData.
*/
async function fetchWithCredentialCheck(input: RequestInfo | URL, init?: RequestInit) {
const response = await fetch(input, init)
if (response.status === 401) {
const data = await response
.clone()
.json()
.catch(() => null)
const entry = Array.isArray(data) ? data[0] : data
// tRPC puts the code on error.data.code; a plain handler may only send a message.
const code = entry?.error?.data?.code ?? entry?.error?.message
if (code === 'UNAUTHORIZED') unauthorizedHandler?.()
}
return response
}
export function getTrpcClient() {
return createTRPCClient<AppRouter>({
links: [
httpBatchLink({
url: `${BASE_API_URL}/api/trpc`,
fetch: fetchWithCredentialCheck,
headers: async () => {
try {
const token = localStorage.getItem('auth_token')

View file

@ -10235,3 +10235,102 @@ Re-validated the fixed file two ways:
removed, 2026-02-10 00:00 is kept, old coupon_usage/complaints/user_incidents rows survive with
NULL order refs, FK check clean.
2. Pre-0006 local dump copy: orders 2548 -> 2438 (-110), no orphan rows, FK check clean.
[2026-10-25 20:55 IST] Persisted the browsing region + bound so startup can render (and read the
regional CDN files) before the device fix / auth / network settle. essentialConsts was already
persisted per bound in `useGetEssentialConsts`; with the bound known at hydration its snapshot and
cache URLs are now available immediately.
--- apps/user-ui/src/lib/region-cache.ts
Added REGION_SELECTION_CACHE_KEY ('region_cache.selection.v1'), CachedRegionSelection,
readCachedRegionSelection / writeCachedRegionSelection (dedup) / clearCachedRegionSelection, with
validation that the stored region matches its id and the bound is number|null.
--- apps/user-ui/src/store/regionStore.ts
+ hydrated: boolean, hydrate(): Promise<void>
+ hydration is single-flight; skips if a region was chosen while the read was in flight
+ setRegion() writes the selection, clearRegion() removes it
Changed the header comment: the selection is persisted now, but still reconciled against the live
location/default address at launch (not trusted blindly).
--- apps/user-ui/src/hooks/useRegion.ts
hydrated now comes from the store (was hardcoded true) and every consumer calls hydrate() once.
The launch baseline (startupLaunchRegionId) is set after hydration, so the restored selection is
treated as launch state, not as a manual pick, and reconciliation still runs.
--- apps/user-ui/tests/helpers/reset.ts
Reset keeps hydrated: true so existing cases behave as before (they do not test hydration).
--- apps/user-ui/tests/lib/use-region.test.tsx
REGION-32 persisted selection hydrates before the launch decision (no spinner).
REGION-33 setRegion persists / clearRegion removes the stored selection.
--- apps/user-ui/JEST-TEST-CASES.md
Rows REGION-32/33.
The GPS launch fix now starts in parallel with the SecureStore read (only the launch baseline
waits for hydration), and essentialConsts keeps its existing per-bound SecureStore snapshot:
with the bound hydrated, `useGetEssentialConsts` serves that snapshot as placeholder data, so
`essentialUrls` are available without the network and products/availability/stores/slots start
fetching as soon as the screens mount (the wrappers above the region gate already mount the hook,
so the read starts before the gate opens).
Typecheck: `apps/user-ui` project clean.
[2026-10-25 21:14 IST] Fixed the invisible drawer auth spinner. `theme.colors.pink2` is '#fff0f6'
on `bg-white`, so the (drawer) auth gate rendered as a plain white screen with no visible
indicator whenever the drawer mounted while auth was still validating (deep link / restored
route). Use brand500 (always visible, matches LocationTestWrapper).
--- apps/user-ui/app/(drawer)/_layout.tsx
- <ActivityIndicator size="large" color={theme.colors.pink2} />
+ <ActivityIndicator size="large" color={theme.colors.brand500} />
--- apps/user-ui/tests/app/layouts.test.tsx
- it('APP-06: drawer layout while loading shows the pink spinner', () => {
+ it('APP-06: drawer layout while loading shows the brand spinner', () => {
- expect(spinner.props.color).toBe(theme.colors.pink2)
+ expect(spinner.props.color).toBe(theme.colors.brand500)
--- apps/user-ui/JEST-TEST-CASES.md
-| APP-06 | edge | drawer layout loading | pink loading spinner |
+| APP-06 | edge | drawer layout loading | brand loading spinner (visible on white) |
No web-ui counterpart change: apps/web-ui gates auth via ProtectedRoute, which already renders a
border-brand-500 spinner (visible), so there is no invisible-spinner equivalent to mirror.
[2026-10-25 21:38 IST] Startup no longer blocks on getSelfData. Stored token+userId are trusted
immediately (isLoading false), the app renders, and the background selfData read confirms them.
Only a backend rejection (UNAUTHORIZED/FORBIDDEN) clears the session; offline/timeout/5xx keeps the
trusted session. user-ui also subscribes to FORCE_LOGOUT_EVENT (the 401 handler in trpc-client
already emitted it, but nothing listened, so a revoked token only surfaced on the next selfData
read). The 401 handler now also checks error.data.code, which is where tRPC actually puts
UNAUTHORIZED.
--- apps/user-ui/src/contexts/AuthContext.tsx
import useCallback; DeviceEventEmitter; FORCE_LOGOUT_EVENT
+ isCredentialError(error): data.code UNAUTHORIZED/FORBIDDEN
+ clearSession(): deleteAuthToken (best effort) + queryClient.clear() + reset state; logout = clearSession
initializeAuth: token+userId -> isLoading:false (was true; comment "keep loading while fetching user")
selfData effect: success -> user/userDetails; credential error -> clearSession(); other errors -> keep
the session (no logout on network failure)
+ useEffect FORCE_LOGOUT_EVENT -> clearSession()
--- apps/user-ui/src/trpc-client.ts
401 handler: read error.data.code (tRPC envelope) with the old error.message as fallback
--- apps/user-ui/tests/lib/auth.test.tsx
AUTH-02: authenticated and NOT loading while getSelfData is pending
AUTH-04: UNAUTHORIZED selfData -> full logout (token removed)
+ AUTH-18 non-auth selfData failure keeps the trusted session
+ AUTH-19 FORCE_LOGOUT_EVENT clears the session
--- apps/user-ui/tests/lib/route-network.test.tsx
+ TRPC-07 401 with a tRPC envelope (error.data.code = UNAUTHORIZED) emits force-logout
--- apps/user-ui/JEST-TEST-CASES.md
AUTH-02/04 rows updated; AUTH-18/19 added; TRPC-07 added.
--- apps/web-ui/src/lib/auth-context.tsx
Mirror: stored token -> isLoading:false; selfData error with UNAUTHORIZED -> logout (/login).
--- apps/web-ui/src/lib/trpc-client.ts
Mirror of the RN event: setUnauthorizedHandler() invoked when the API answers 401 UNAUTHORIZED.