Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions apps/mobile-app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,10 @@ port in development mode, and runs `contract/app.contract.test.ts`: sign-up,
get-session, sign-out, wrong password, sign-in, `GET`/`PATCH /users/me`
(including validation and the 403 for another user), `GET /users/me/sessions`,
session restore on a cold launch, and `DELETE /users/me`. The app's real modules run in Node; only the
native modules are stubbed (`contract/stubs/`). Server output goes to
`.contract/server.log`.
native modules are stubbed (`contract/stubs/`), and fetch is sent over
`node:http` as the native app sends it (`contract/nativeFetch.ts`): Node's own
fetch adds browser Fetch Metadata (`Sec-Fetch-Mode`), which the server's API
gate answers with 404. Server output goes to `.contract/server.log`.

It needs Go and Docker. Overrides:

Expand Down
34 changes: 29 additions & 5 deletions apps/mobile-app/contract/app.contract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,11 +106,35 @@ describe('mobile app against the Go server', () => {
})

it('restores the session on the next launch from the keychain', async () => {
const relaunched = await launchApp()
// The splash screen waits on this atom: it is filled from the keychain
// cache before any request, then confirmed by get-session.
expect(relaunched.authClient.$store.atoms.session.get().data?.user.email).toBe(email)
const { data } = await relaunched.authClient.getSession()
// The splash screen waits on this atom. expoClient fills it from the
// keychain cache as the first get-session starts (better-auth 1.7: in that
// request's init, before it is sent), then get-session confirms it. Hold
// the auth client's requests back to prove the cached session is there
// without the network. The client keeps the fetch it was created with.
const sendFetch = globalThis.fetch
let release = () => {}
const held = new Promise<void>(resolve => (release = resolve))
let sent = 0
globalThis.fetch = async (input, init) => {
await held
sent++
return sendFetch(input, init)
}
let relaunched: Awaited<ReturnType<typeof launchApp>>
try {
relaunched = await launchApp()
} finally {
globalThis.fetch = sendFetch
}
const pending = relaunched.authClient.getSession()
try {
await vi.waitFor(() => expect(relaunched.authClient.$store.atoms.session.get().data?.user.email).toBe(email))
expect(sent).toBe(0)
} finally {
release()
}
const { data } = await pending
expect(sent).toBe(1)
expect(data?.user.name).toBe('Ada Lovelace')
expect((await relaunched.getCurrentUser()).data?.user.email).toBe(email)
app = relaunched
Expand Down
4 changes: 3 additions & 1 deletion apps/mobile-app/contract/globalSetup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import path from 'node:path'

import type { TestProject } from 'vitest/node'

import { nativeFetch } from './nativeFetch'

/**
* Starts the real Go server for the contract tests:
*
Expand Down Expand Up @@ -128,7 +130,7 @@ export default async function setup(project: TestProject) {
await waitFor('the Go server /healthz', 30_000, async () => {
if (exited) throw new Error('contract setup: server exited, see .contract/server.log')
try {
return (await fetch(`${apiUrl}/healthz`)).ok
return (await nativeFetch(`${apiUrl}/healthz`)).ok
} catch {
return false
}
Expand Down
69 changes: 69 additions & 0 deletions apps/mobile-app/contract/nativeFetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import http from 'node:http'
import https from 'node:https'

/**
* fetch as the native app sends it. React Native's fetch (NSURLSession on
* iOS, OkHttp on Android) sends only the headers the caller set. Node's fetch
* (undici) adds the browser's Fetch Metadata (`Sec-Fetch-Mode: cors`), which
* the Go server's API gate (apps/web/internal/server/middleware.go, apiOnly)
* rightly treats as a browser and answers with 404. This sends the request
* over node:http instead, so the contract test exercises the API as the app
* reaches it.
*
* It covers what the app's clients use: method, headers, a buffered body,
* an AbortSignal and `redirect` (follow by default, or manual).
*/
const maxRedirects = 20
const redirectStatuses = new Set([301, 302, 303, 307, 308])
const nullBodyStatuses = new Set([101, 204, 205, 304])

export async function nativeFetch(input: string | URL | Request, init?: RequestInit): Promise<Response> {
const request = new Request(input, init)
const body = request.body ? Buffer.from(await request.arrayBuffer()) : undefined
let url = new URL(request.url)
let method = request.method
let payload = body
for (let hops = 0; ; hops++) {
const response = await send(url, method, request.headers, payload, request.signal)
const location = response.headers.get('location')
if (request.redirect === 'manual' || !redirectStatuses.has(response.status) || !location) return response
if (request.redirect === 'error') throw new TypeError(`fetch: redirect to ${location}`)
if (hops >= maxRedirects) throw new TypeError('fetch: too many redirects')
url = new URL(location, url)
// As fetch does: a 303, or a 301/302 after POST, becomes a bodiless GET.
if (response.status === 303 || ((response.status === 301 || response.status === 302) && method === 'POST')) {
method = 'GET'
payload = undefined
}
}
}

function send(url: URL, method: string, headers: Headers, body: Buffer | undefined, signal: AbortSignal): Promise<Response> {
const outgoing: Record<string, string> = {}
headers.forEach((value, name) => (outgoing[name] = value))
if (body) outgoing['content-length'] = String(body.length)
const transport = url.protocol === 'https:' ? https : http
return new Promise((resolve, reject) => {
const req = transport.request(url, { method, headers: outgoing, signal }, res => {
const chunks: Buffer[] = []
res.on('data', (chunk: Buffer) => chunks.push(chunk))
res.on('error', reject)
res.on('end', () => {
const responseHeaders = new Headers()
for (let index = 0; index < res.rawHeaders.length; index += 2) {
responseHeaders.append(res.rawHeaders[index], res.rawHeaders[index + 1])
}
const status = res.statusCode ?? 0
const response = new Response(nullBodyStatuses.has(status) ? null : Buffer.concat(chunks), {
status,
statusText: res.statusMessage,
headers: responseHeaders,
})
Object.defineProperty(response, 'url', { value: url.toString() })
resolve(response)
})
})
req.on('error', reject)
req.end(body)
})
}
6 changes: 6 additions & 0 deletions apps/mobile-app/contract/setup.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { inject } from 'vitest'

import { nativeFetch } from './nativeFetch'

// The app's clients call the global fetch: send it as the native app does,
// without the Fetch Metadata Node's fetch adds (see nativeFetch.ts).
globalThis.fetch = nativeFetch

// src/lib/config/env.ts reads this when the app modules are imported.
process.env.EXPO_PUBLIC_API_URL = inject('apiUrl')
Loading