Co-authored-by: dev_agent <dev_agent@cubecraftlabs.com>
This commit was merged in pull request #58.
This commit is contained in:
+83
-13
@@ -1,15 +1,18 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { errorResponse, fakeLocation, jsonResponse, ME, request, stubFetch } from '../test/fetchStub.ts'
|
||||
import { ApiError, createApiClient, CSRF_HEADER } from './index.ts'
|
||||
import { ApiError, createApiClient, createVerifiedSession, CSRF_HEADER, VERIFIED_SESSION_KEY } from './index.ts'
|
||||
import { cacheFallbackHeader } from '../sw/routes.ts'
|
||||
import { createNetworkStatus } from '../pwa/networkStatus.ts'
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('apiFetch', () => {
|
||||
it('sends same-origin JSON and the cached CSRF token on non-GET requests only', async () => {
|
||||
const fetchMock = stubFetch(jsonResponse(200, ME), jsonResponse(200, { ok: 1 }), jsonResponse(200, { ok: 2 }))
|
||||
const api = createApiClient(fakeLocation())
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
await api.loadMe()
|
||||
|
||||
await expect(api.apiFetch('/api/v1/settings/household')).resolves.toEqual({ ok: 1 })
|
||||
@@ -29,7 +32,7 @@ describe('apiFetch', () => {
|
||||
|
||||
it('refuses a non-GET request before /me has loaded', async () => {
|
||||
const fetchMock = stubFetch()
|
||||
const api = createApiClient(fakeLocation())
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
await expect(api.apiFetch('/api/v1/jobs', { method: 'POST', body: {} })).rejects.toThrow(/no CSRF token/)
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -47,7 +50,7 @@ describe('apiFetch', () => {
|
||||
'api/v1/me',
|
||||
])('refuses %s without sending it or the CSRF token', async (path) => {
|
||||
const fetchMock = stubFetch(jsonResponse(200, ME))
|
||||
const api = createApiClient(fakeLocation())
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
await api.loadMe()
|
||||
|
||||
await expect(api.apiFetch(path, { method: 'POST', body: {} })).rejects.toThrow(
|
||||
@@ -60,7 +63,7 @@ describe('apiFetch', () => {
|
||||
|
||||
it('rejects with a typed ApiError from the error body', async () => {
|
||||
stubFetch(errorResponse(503, 'unavailable', true))
|
||||
const api = createApiClient(fakeLocation())
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
const error = await api.apiFetch('/api/v1/jobs/j1').catch((e: unknown) => e)
|
||||
expect(error).toBeInstanceOf(ApiError)
|
||||
expect(error).toMatchObject({ status: 503, code: 'unavailable', message: 'unavailable message', retryable: true })
|
||||
@@ -68,14 +71,14 @@ describe('apiFetch', () => {
|
||||
|
||||
it('rejects a response without the API error body', async () => {
|
||||
stubFetch(new Response('<html>bad gateway</html>', { status: 502 }))
|
||||
const api = createApiClient(fakeLocation())
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
await expect(api.apiFetch('/api/v1/jobs/j1')).rejects.toThrow('GET /api/v1/jobs/j1: 502 response is not JSON')
|
||||
})
|
||||
|
||||
it('on 401 navigates to sign-in with the current path and search to return to', async () => {
|
||||
stubFetch(errorResponse(401, 'unauthenticated'))
|
||||
const location = fakeLocation('/plan/shopping', '?week=2026-10-05')
|
||||
const api = createApiClient(location)
|
||||
const api = createApiClient(location, createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
|
||||
await expect(api.apiFetch('/api/v1/settings/household')).rejects.toMatchObject({ status: 401 })
|
||||
expect(location.assign).toHaveBeenCalledExactlyOnceWith(
|
||||
@@ -90,7 +93,7 @@ describe('apiFetch', () => {
|
||||
jsonResponse(200, { ...ME, csrfToken: 'token-2' }),
|
||||
jsonResponse(201, { id: 'j1' }),
|
||||
)
|
||||
const api = createApiClient(fakeLocation())
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
await api.loadMe()
|
||||
|
||||
await expect(api.apiFetch('/api/v1/jobs', { method: 'POST', body: { kind: 'noop' } })).resolves.toEqual({
|
||||
@@ -111,7 +114,7 @@ describe('apiFetch', () => {
|
||||
jsonResponse(200, { ...ME, csrfToken: 'token-2' }),
|
||||
errorResponse(403, 'csrf'),
|
||||
)
|
||||
const api = createApiClient(fakeLocation())
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
await api.loadMe()
|
||||
|
||||
await expect(api.apiFetch('/api/v1/jobs', { method: 'POST', body: {} })).rejects.toMatchObject({
|
||||
@@ -124,7 +127,7 @@ describe('apiFetch', () => {
|
||||
|
||||
it('marks any other 403 as not in this household and notifies subscribers', async () => {
|
||||
const fetchMock = stubFetch(errorResponse(403, 'forbidden'))
|
||||
const api = createApiClient(fakeLocation())
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
const listener = vi.fn()
|
||||
api.subscribe(listener)
|
||||
|
||||
@@ -136,14 +139,14 @@ describe('apiFetch', () => {
|
||||
|
||||
it('does not take a 403 without the API error body as not in this household', async () => {
|
||||
stubFetch(new Response('<html>denied by proxy</html>', { status: 403 }))
|
||||
const api = createApiClient(fakeLocation())
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
await expect(api.apiFetch('/api/v1/me')).rejects.toThrow('GET /api/v1/me: 403 response is not JSON')
|
||||
expect(api.forbidden()).toBe(false)
|
||||
})
|
||||
|
||||
it('does not refresh /me for a csrf 403 on a GET, which carries no token', async () => {
|
||||
const fetchMock = stubFetch(errorResponse(403, 'csrf'))
|
||||
const api = createApiClient(fakeLocation())
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
await expect(api.loadMe()).rejects.toMatchObject({ status: 403, code: 'csrf' })
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
@@ -152,7 +155,74 @@ describe('apiFetch', () => {
|
||||
describe('loadMe', () => {
|
||||
it('rejects a /me response without a CSRF token', async () => {
|
||||
stubFetch(jsonResponse(200, { ...ME, csrfToken: '' }))
|
||||
const api = createApiClient(fakeLocation())
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
await expect(api.loadMe()).rejects.toThrow('response is not a member with a CSRF token')
|
||||
})
|
||||
})
|
||||
|
||||
describe('verified session', () => {
|
||||
it('is remembered when /me answers with a member', async () => {
|
||||
stubFetch(jsonResponse(200, ME))
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
expect(api.session.verified()).toBe(false)
|
||||
await api.loadMe()
|
||||
expect(api.session.verified()).toBe(true)
|
||||
expect(localStorage.getItem(VERIFIED_SESSION_KEY)).toBe('1')
|
||||
})
|
||||
|
||||
it('stores nothing from the /me response', async () => {
|
||||
stubFetch(jsonResponse(200, ME))
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
await api.loadMe()
|
||||
expect(Object.keys(localStorage)).toEqual([VERIFIED_SESSION_KEY])
|
||||
expect(JSON.stringify({ ...localStorage })).not.toContain(ME.csrfToken)
|
||||
})
|
||||
|
||||
it('is not remembered for a /me response that is not a member', async () => {
|
||||
stubFetch(jsonResponse(200, { ...ME, csrfToken: '' }))
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
await expect(api.loadMe()).rejects.toThrow()
|
||||
expect(api.session.verified()).toBe(false)
|
||||
})
|
||||
|
||||
it('is forgotten on a 401', async () => {
|
||||
stubFetch(jsonResponse(200, ME), errorResponse(401, 'unauthenticated'))
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
await api.loadMe()
|
||||
await expect(api.apiFetch('/api/v1/plans')).rejects.toMatchObject({ status: 401 })
|
||||
expect(api.session.verified()).toBe(false)
|
||||
})
|
||||
|
||||
it('is forgotten when the account is not in this household', async () => {
|
||||
stubFetch(jsonResponse(200, ME), errorResponse(403, 'forbidden'))
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
await api.loadMe()
|
||||
await expect(api.apiFetch('/api/v1/plans')).rejects.toMatchObject({ status: 403 })
|
||||
expect(api.session.verified()).toBe(false)
|
||||
})
|
||||
|
||||
it('is kept when a request fails with a network error', async () => {
|
||||
stubFetch(jsonResponse(200, ME))
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
await api.loadMe()
|
||||
vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockRejectedValue(new TypeError('Failed to fetch')))
|
||||
await expect(api.loadMe()).rejects.toThrow(TypeError)
|
||||
expect(api.session.verified()).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('network status', () => {
|
||||
it('counts a response the service worker answered from its cache as offline', async () => {
|
||||
vi.spyOn(navigator, 'onLine', 'get').mockReturnValue(true)
|
||||
const cached = jsonResponse(200, { id: '01J9ZR' })
|
||||
cached.headers.set(cacheFallbackHeader, '1')
|
||||
stubFetch(cached, jsonResponse(200, { id: '01J9ZR' }))
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
|
||||
await expect(api.apiFetch('/api/v1/recipes/01J9ZR')).resolves.toEqual({ id: '01J9ZR' })
|
||||
expect(api.network.offline()).toBe(true)
|
||||
|
||||
await expect(api.apiFetch('/api/v1/recipes/01J9ZR')).resolves.toEqual({ id: '01J9ZR' })
|
||||
expect(api.network.offline()).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
+44
-8
@@ -1,4 +1,7 @@
|
||||
import type { NetworkStatus } from '../pwa/networkStatus.ts'
|
||||
import { cacheFallbackHeader } from '../sw/routes.ts'
|
||||
import { ApiError, isRecord, parseApiError } from './errors.ts'
|
||||
import type { VerifiedSession } from './verifiedSession.ts'
|
||||
|
||||
// CSRF_HEADER carries the session's CSRF token on every non-GET request.
|
||||
export const CSRF_HEADER = 'X-MealQuest-CSRF'
|
||||
@@ -36,7 +39,7 @@ export type ApiLocation = Pick<Location, 'origin' | 'pathname' | 'search' | 'ass
|
||||
|
||||
export type ApiRequest = {
|
||||
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
|
||||
// Sent as JSON.
|
||||
// Sent as JSON. A GET must not have one.
|
||||
body?: unknown
|
||||
}
|
||||
|
||||
@@ -51,11 +54,18 @@ export type ApiClient = {
|
||||
// account is not in this household; subscribe is notified when it changes.
|
||||
forbidden(): boolean
|
||||
subscribe(listener: () => void): () => void
|
||||
// network learns of every request that failed with a network error or was
|
||||
// answered from the service worker's cache, and of every request the
|
||||
// server answered.
|
||||
network: NetworkStatus
|
||||
// session remembers, on this device, whether /me last answered with a
|
||||
// member; offline, AuthBootstrap opens the saved pages only if it did.
|
||||
session: VerifiedSession
|
||||
}
|
||||
|
||||
// createApiClient builds the app's API client. location is window.location in
|
||||
// the app: a 401 sends it to /auth/login with the current path to return to.
|
||||
export function createApiClient(location: ApiLocation): ApiClient {
|
||||
export function createApiClient(location: ApiLocation, network: NetworkStatus, session: VerifiedSession): ApiClient {
|
||||
let csrfToken: string | null = null
|
||||
let refreshing: Promise<Me> | null = null
|
||||
let forbidden = false
|
||||
@@ -70,12 +80,28 @@ export function createApiClient(location: ApiLocation): ApiClient {
|
||||
}
|
||||
headers[CSRF_HEADER] = csrfToken
|
||||
}
|
||||
return fetch(path, {
|
||||
method,
|
||||
headers,
|
||||
credentials: 'same-origin',
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
})
|
||||
// Serialize before fetching so a body that cannot be sent is its own error
|
||||
// and never counts as a network failure.
|
||||
let json: string | undefined
|
||||
try {
|
||||
json = body === undefined ? undefined : JSON.stringify(body)
|
||||
} catch (error) {
|
||||
throw new Error(`${method} ${path}: request body is not serializable as JSON`, { cause: error })
|
||||
}
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(path, { method, headers, credentials: 'same-origin', body: json })
|
||||
} catch (error) {
|
||||
// fetch rejects with a TypeError when the network fails; an abort is a
|
||||
// DOMException and says nothing about the network.
|
||||
if (error instanceof TypeError) network.requestFailed()
|
||||
throw error
|
||||
}
|
||||
// The service worker marks a response it answered from its cache because
|
||||
// the server could not be reached in time.
|
||||
if (response.headers.has(cacheFallbackHeader)) network.requestFailed()
|
||||
else network.requestSucceeded()
|
||||
return response
|
||||
}
|
||||
|
||||
// refreshMe shares one in-flight /me request between every request that
|
||||
@@ -90,6 +116,11 @@ export function createApiClient(location: ApiLocation): ApiClient {
|
||||
async function apiFetch<T>(path: string, request: ApiRequest = {}): Promise<T> {
|
||||
const method = request.method ?? 'GET'
|
||||
const url = apiURL(location.origin, method, path)
|
||||
// fetch refuses a GET with a body by rejecting with a TypeError, the same
|
||||
// error as a network failure, so refuse it here before anything is sent.
|
||||
if (method === 'GET' && request.body !== undefined) {
|
||||
throw new Error(`GET ${path}: a GET request cannot carry a body`)
|
||||
}
|
||||
let response = await send(method, url, request.body)
|
||||
if (response.status === 403) {
|
||||
const error = await parseForbidden(method, path, response)
|
||||
@@ -113,12 +144,14 @@ export function createApiClient(location: ApiLocation): ApiClient {
|
||||
|
||||
function markForbidden() {
|
||||
if (forbidden) return
|
||||
session.forget()
|
||||
forbidden = true
|
||||
listeners.forEach((listener) => listener())
|
||||
}
|
||||
|
||||
async function decode<T>(method: string, path: string, response: Response): Promise<T> {
|
||||
if (response.status === 401) {
|
||||
session.forget()
|
||||
location.assign(`/auth/login?return=${encodeURIComponent(location.pathname + location.search)}`)
|
||||
}
|
||||
if (!response.ok) throw await parseApiError(method, path, response)
|
||||
@@ -140,6 +173,7 @@ export function createApiClient(location: ApiLocation): ApiClient {
|
||||
throw new Error(`GET ${ME_PATH}: response is not a member with a CSRF token`)
|
||||
}
|
||||
csrfToken = me.csrfToken
|
||||
session.remember()
|
||||
return me as Me
|
||||
}
|
||||
|
||||
@@ -151,5 +185,7 @@ export function createApiClient(location: ApiLocation): ApiClient {
|
||||
listeners.add(listener)
|
||||
return () => listeners.delete(listener)
|
||||
},
|
||||
network,
|
||||
session,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,4 +2,5 @@ export { ApiProvider, useApi } from './ApiContext.tsx'
|
||||
export { createApiClient, CSRF_HEADER, ME_PATH, type ApiClient, type ApiLocation, type ApiRequest, type Me } from './client.ts'
|
||||
export { ApiError } from './errors.ts'
|
||||
export { createQueryClient, shouldRetry } from './queryClient.ts'
|
||||
export { createVerifiedSession, VERIFIED_SESSION_KEY, type VerifiedSession } from './verifiedSession.ts'
|
||||
export { useJob, type Job, type JobState, type JobStatus } from './useJob.ts'
|
||||
|
||||
@@ -2,7 +2,8 @@ import { act, renderHook } from '@testing-library/react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { errorResponse, fakeLocation, jsonResponse, request, stubFetch } from '../test/fetchStub.ts'
|
||||
import { ApiProvider, createApiClient, useJob } from './index.ts'
|
||||
import { ApiProvider, createApiClient, createVerifiedSession, useJob } from './index.ts'
|
||||
import { createNetworkStatus } from '../pwa/networkStatus.ts'
|
||||
|
||||
type Draft = { dinners: string[] }
|
||||
|
||||
@@ -11,7 +12,7 @@ function job(status: string, result: Draft | null, error: string | null = null)
|
||||
}
|
||||
|
||||
function renderJob(jobId: string | null) {
|
||||
const api = createApiClient(fakeLocation())
|
||||
const api = createApiClient(fakeLocation(), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
const wrapper = ({ children }: { children: ReactNode }) => <ApiProvider client={api}>{children}</ApiProvider>
|
||||
return renderHook(({ id }) => useJob<Draft>(id), { wrapper, initialProps: { id: jobId } })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
// VERIFIED_SESSION_KEY is the localStorage key marking that GET /api/v1/me
|
||||
// last answered with a household member on this device. It holds only "1" —
|
||||
// never the /me response, its CSRF token or anything from /auth.
|
||||
export const VERIFIED_SESSION_KEY = 'mealquest.verified-session'
|
||||
|
||||
export type VerifiedSession = {
|
||||
// verified reports whether /me last answered with a member on this device.
|
||||
verified(): boolean
|
||||
// remember records a /me that answered with a member.
|
||||
remember(): void
|
||||
// forget records that the server refused the session (401) or the account
|
||||
// (not in this household).
|
||||
forget(): void
|
||||
}
|
||||
|
||||
// createVerifiedSession keeps the marker in storage (window.localStorage in
|
||||
// the app). A storage failure is thrown to the caller.
|
||||
export function createVerifiedSession(storage: Storage): VerifiedSession {
|
||||
return {
|
||||
verified: () => storage.getItem(VERIFIED_SESSION_KEY) === '1',
|
||||
remember: () => storage.setItem(VERIFIED_SESSION_KEY, '1'),
|
||||
forget: () => storage.removeItem(VERIFIED_SESSION_KEY),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user