138 lines
4.3 KiB
TypeScript
138 lines
4.3 KiB
TypeScript
/**
|
|
* 401 -> force-logout wiring (src/trpc-client.ts + the app shell).
|
|
*
|
|
* trpc-client emits FORCE_LOGOUT_EVENT when a response is a 401 whose error
|
|
* message is "UNAUTHORIZED". The missing half is a subscriber: nothing in
|
|
* user-ui listens for that event, so a signed-in session survives a 401.
|
|
*
|
|
* The last test pins that gap — it asserts the session is NOT cleared and will
|
|
* fail once a listener is wired up. See tests/KNOWN-GAPS.md.
|
|
*/
|
|
|
|
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
|
jest.unmock('@/src/contexts/AuthContext')
|
|
|
|
import React from 'react'
|
|
import { Text } from 'react-native'
|
|
import { DeviceEventEmitter } from 'react-native'
|
|
import { screen, waitFor } from '@testing-library/react-native'
|
|
import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs'
|
|
import { StorageService } from 'common-ui/src/services/StorageService'
|
|
|
|
import { AuthProvider, useAuth } from '@/src/contexts/AuthContext'
|
|
import { trpcClient } from '@/src/trpc-client'
|
|
import { getAuthToken } from '@/hooks/useJWT'
|
|
import { resetStorage, setupApiMocks } from '../mocks/api'
|
|
import { renderWithProviders } from '../helpers/render'
|
|
|
|
const USER = {
|
|
id: 5,
|
|
name: 'Test User',
|
|
email: 'test@example.com',
|
|
mobile: '9876543210',
|
|
profileImage: '',
|
|
createdAt: '',
|
|
}
|
|
|
|
const jwtFor = (payload: Record<string, unknown>) => {
|
|
const enc = (obj: unknown) =>
|
|
Buffer.from(JSON.stringify(obj)).toString('base64url')
|
|
return `${enc({ alg: 'HS256', typ: 'JWT' })}.${enc(payload)}.sig`
|
|
}
|
|
|
|
const Probe = () => {
|
|
const auth = useAuth()
|
|
return (
|
|
<Text testID="state">
|
|
{`${auth.isAuthenticated}|${auth.isLoading}|${auth.user?.id ?? 'none'}`}
|
|
</Text>
|
|
)
|
|
}
|
|
|
|
/** A tRPC response shaped like the batch error envelope the client inspects. */
|
|
const responseWith = (status: number, message: string) => {
|
|
const body = [{ error: { message } }]
|
|
return {
|
|
ok: status < 400,
|
|
status,
|
|
statusText: 'status',
|
|
headers: new Map(),
|
|
url: '',
|
|
json: async () => body,
|
|
text: async () => JSON.stringify(body),
|
|
clone: () => ({ json: async () => body }),
|
|
}
|
|
}
|
|
|
|
/** Fire a query through the real client and wait for it to settle. */
|
|
const callAndSettle = async (status: number, message: string) => {
|
|
;(global as unknown as { fetch: unknown }).fetch = jest.fn(async () =>
|
|
responseWith(status, message)
|
|
)
|
|
|
|
let settled = false
|
|
const promise = trpcClient.common.healthCheck
|
|
.query()
|
|
.catch(() => undefined)
|
|
.then(() => {
|
|
settled = true
|
|
})
|
|
|
|
await waitFor(() => expect(settled).toBe(true))
|
|
await promise
|
|
}
|
|
|
|
describe('401 force-logout', () => {
|
|
beforeEach(async () => {
|
|
await resetStorage()
|
|
await StorageService.clearAll(['authToken', 'userId'])
|
|
})
|
|
|
|
it('emits FORCE_LOGOUT_EVENT for a 401 UNAUTHORIZED', async () => {
|
|
const emit = jest.spyOn(DeviceEventEmitter, 'emit')
|
|
|
|
await callAndSettle(401, 'UNAUTHORIZED')
|
|
|
|
expect(emit).toHaveBeenCalledWith(FORCE_LOGOUT_EVENT)
|
|
})
|
|
|
|
it('does not emit for a 401 with another message', async () => {
|
|
const emit = jest.spyOn(DeviceEventEmitter, 'emit')
|
|
|
|
await callAndSettle(401, 'TOKEN_EXPIRED')
|
|
|
|
expect(emit).not.toHaveBeenCalledWith(FORCE_LOGOUT_EVENT)
|
|
})
|
|
|
|
/**
|
|
* KNOWN GAP: the event is emitted but no component subscribes, so an
|
|
* authenticated session is left in place after the server has rejected its
|
|
* token. The next screen the user opens will fail again instead of being
|
|
* sent to login.
|
|
*
|
|
* This pins the gap: it asserts the session survives. It must be rewritten
|
|
* to assert the redirect once a FORCE_LOGOUT_EVENT listener exists.
|
|
*/
|
|
it('leaves the signed-in session untouched (no subscriber for the event)', async () => {
|
|
await StorageService.setItem('authToken', jwtFor({ id: USER.id }))
|
|
await StorageService.setItem('userId', String(USER.id))
|
|
|
|
setupApiMocks({
|
|
procedures: { 'user.user.getSelfData': { data: { user: USER } } },
|
|
})
|
|
renderWithProviders(
|
|
<AuthProvider>
|
|
<Probe />
|
|
</AuthProvider>,
|
|
{ centralStores: false }
|
|
)
|
|
|
|
await waitFor(() => expect(screen.getByTestId('state')).toHaveTextContent('true|false|5'))
|
|
|
|
await callAndSettle(401, 'UNAUTHORIZED')
|
|
|
|
// Nothing listens for FORCE_LOGOUT_EVENT: the session is not torn down.
|
|
await waitFor(() => expect(screen.getByTestId('state')).toHaveTextContent('true|false|5'))
|
|
expect(await getAuthToken()).not.toBeNull()
|
|
})
|
|
})
|