From 21734bff80e2b6e59433e6a6761db38ba15ecd01 Mon Sep 17 00:00:00 2001 From: Real Codesiman Date: Fri, 13 Nov 2026 14:24:02 +0700 Subject: [PATCH] feat(auth): add native sign in with apple Required by App Store guideline 4.8 since the app offers other social logins. Uses the id_token grant on /api/auth/mobile/token with a hashed nonce. --- app.config.ts | 6 + docs/deploy.md | 14 ++ package.json | 1 + pnpm-lock.yaml | 16 +++ src/api/auth-endpoints.test.ts | 114 +++++++++++++++- src/api/auth-endpoints.ts | 46 +++++++ .../auth/apple-sign-in-button.test.tsx | 125 ++++++++++++++++++ src/features/auth/apple-sign-in-button.tsx | 123 +++++++++++++++++ src/features/auth/social-buttons.tsx | 38 ++++-- 9 files changed, 471 insertions(+), 12 deletions(-) create mode 100644 src/features/auth/apple-sign-in-button.test.tsx create mode 100644 src/features/auth/apple-sign-in-button.tsx diff --git a/app.config.ts b/app.config.ts index 7e58516..8844447 100644 --- a/app.config.ts +++ b/app.config.ts @@ -178,6 +178,10 @@ const config: ExpoConfig = { // Only OS-provided TLS/Keychain + random UUIDs — no custom crypto, so export-compliance exempt. // Skips the App Store Connect "App Encryption Documentation" prompt on every upload. infoPlist: { ITSAppUsesNonExemptEncryption: false }, + // Adds the `com.apple.developer.applesignin` entitlement (native Sign in with Apple, required + // by App Store guideline 4.8 because the app offers other social logins). EAS syncs the + // capability to the App ID on the next build. + usesAppleSignIn: true, }, android: { package: `${brand.android.package}${envConfig.idSuffix}`, @@ -213,6 +217,8 @@ const config: ExpoConfig = { ], 'expo-image', 'expo-web-browser', + // Native Sign in with Apple button/credential API (pairs with `ios.usesAppleSignIn`). + 'expo-apple-authentication', 'expo-secure-store', [ 'expo-image-picker', diff --git a/docs/deploy.md b/docs/deploy.md index fe5654e..6f5054d 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -108,6 +108,20 @@ offers to save credentials to your EAS project), or set them as environment vari (`EXPO_APPLE_ID`, etc. — see `eas submit --help` for the full list) before running non-interactively in CI. +## Apple Sign In + +The iOS app offers native Sign in with Apple (App Store guideline 4.8, since Google/Facebook login +exist). It is a native `id_token` grant on `POST /api/auth/mobile/token` — no browser redirect and no +`.p8` key on the app side. + +- The capability comes from `ios.usesAppleSignIn` in `app.config.ts`; EAS syncs it to the App ID on + the next build. It is a native change, so a new dev client / binary is required (OTA is not enough). +- The backend's `APPLE_APP_BUNDLE_IDS` must list every bundle ID that should sign in: each + `.dev` / `.preview` variant (see `idSuffix` in `app.config.ts`) and the production ID. +- White-label brands (`brands/*/brand.json`) each have their own bundle ID, so each needs its own + entry in `APPLE_APP_BUNDLE_IDS` and the capability on its App ID. +- Test on a real device signed into an Apple ID; the Simulator is unreliable for Sign in with Apple. + ## Version bumping `eas.json`'s `"appVersionSource": "remote"` means EAS tracks the build number remotely — you don't diff --git a/package.json b/package.json index f831c39..c4848df 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "@tanstack/react-query": "^5.105.3", "dayjs": "^1.11.23", "expo": "~58.0.25", + "expo-apple-authentication": "~58.0.2", "expo-camera": "~58.0.14", "expo-constants": "~58.0.16", "expo-crypto": "~58.0.8", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 539cb28..c871d4b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -190,6 +190,9 @@ importers: expo: specifier: ~58.0.25 version: 58.0.25(@babel/core@7.29.7(supports-color@10.2.2))(@expo/metro-runtime@58.0.17)(expo-router@58.0.31)(react-dom@19.2.3(react@19.3.0))(react-native-web@0.21.2(react-dom@19.2.3(react@19.3.0))(react@19.3.0))(react-native-worklets@0.13.0(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(react-native@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2))(react@19.3.0)(supports-color@10.2.2))(react-native@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2))(react@19.3.0)(supports-color@10.2.2)(typescript@6.0.3) + expo-apple-authentication: + specifier: ~58.0.2 + version: 58.0.3(expo@58.0.25)(react-native@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2))(react@19.3.0) expo-camera: specifier: ~58.0.14 version: 58.0.14(@types/emscripten@1.41.5)(expo@58.0.25)(react-native-web@0.21.2(react-dom@19.2.3(react@19.3.0))(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2))(react@19.3.0) @@ -3058,6 +3061,13 @@ packages: resolution: {integrity: sha512-0LNuMvs8/5mRYhnCR4k+lGV7fqPMs6Bnksda4S3zsCUmdxBpAn4zU4NNzXdq1pMKe/H4W5t/zVIDSJ/H3e0vDA==} engines: {node: ^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0} + expo-apple-authentication@58.0.3: + resolution: {integrity: sha512-w7WFqHs6A89dAlKzv92dQV7JmoFouVso0NzmqfcKqaTbjJJcf/4+DDEa/oIMbUWxJDdWCz1Kx08/08FyVpr/+A==} + peerDependencies: + expo: '*' + react: '*' + react-native: '*' + expo-application@58.1.2: resolution: {integrity: sha512-WYFdNHGaxe/j69oYREhK0cKsKYszuIuz399WXYCP+M1grfO+FCWB/RbuMgaXJsLWlzqhNjA/zLgfJ+33FwrQvw==} peerDependencies: @@ -9034,6 +9044,12 @@ snapshots: jest-mock: 30.5.2 jest-util: 30.5.1 + expo-apple-authentication@58.0.3(expo@58.0.25)(react-native@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2))(react@19.3.0): + dependencies: + expo: 58.0.25(@babel/core@7.29.7(supports-color@10.2.2))(@expo/metro-runtime@58.0.17)(expo-router@58.0.31)(react-dom@19.2.3(react@19.3.0))(react-native-web@0.21.2(react-dom@19.2.3(react@19.3.0))(react@19.3.0))(react-native-worklets@0.13.0(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(react-native@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2))(react@19.3.0)(supports-color@10.2.2))(react-native@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2))(react@19.3.0)(supports-color@10.2.2)(typescript@6.0.3) + react: 19.3.0 + react-native: 0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2) + expo-application@58.1.2(expo@58.0.25): dependencies: expo: 58.0.25(@babel/core@7.29.7(supports-color@10.2.2))(@expo/metro-runtime@58.0.17)(expo-router@58.0.31)(react-dom@19.2.3(react@19.3.0))(react-native-web@0.21.2(react-dom@19.2.3(react@19.3.0))(react@19.3.0))(react-native-worklets@0.13.0(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(react-native@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2))(react@19.3.0)(supports-color@10.2.2))(react-native@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2))(react@19.3.0)(supports-color@10.2.2)(typescript@6.0.3) diff --git a/src/api/auth-endpoints.test.ts b/src/api/auth-endpoints.test.ts index 81efeea..10bde91 100644 --- a/src/api/auth-endpoints.test.ts +++ b/src/api/auth-endpoints.test.ts @@ -1,7 +1,14 @@ import * as Crypto from 'expo-crypto'; import * as SecureStore from 'expo-secure-store'; -import { refreshAccessToken, requestPasswordReset, startSocialSignIn } from '@/api/auth-endpoints'; +import { + AuthApiError, + createAppleNonce, + refreshAccessToken, + requestPasswordReset, + signInWithAppleIdToken, + startSocialSignIn, +} from '@/api/auth-endpoints'; import { getMobileDeviceId } from '@/api/auth-device'; import { setAuthTokens } from '@/api/auth-token'; @@ -147,3 +154,108 @@ describe('requestPasswordReset', () => { }); }); }); + +describe('createAppleNonce', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('returns a dashless raw nonce and its SHA-256 hex digest', async () => { + jest + .mocked(Crypto.randomUUID) + .mockReturnValueOnce('aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa') + .mockReturnValueOnce('bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'); + jest.mocked(Crypto.digestStringAsync).mockResolvedValue('deadbeef'); + + const nonce = await createAppleNonce(); + + expect(nonce.raw).toBe('aaaaaaaaaaaa4aaa8aaaaaaaaaaaaaaabbbbbbbbbbbb4bbb8bbbbbbbbbbbbbbb'); + expect(nonce.hashed).toBe('deadbeef'); + expect(Crypto.digestStringAsync).toHaveBeenCalledWith('SHA-256', nonce.raw); + }); +}); + +describe('signInWithAppleIdToken', () => { + const tokens = { + accessToken: 'access', + expiresAt: Date.now() + 10 * 60_000, + refreshToken: 'refresh', + }; + const me = { id: 'u1', email: 'a@b.test', name: 'Ada Lovelace', mustChangePassword: false }; + + function mockSuccessfulFetch() { + const fetchMock = jest + .fn() + .mockResolvedValueOnce(new Response(JSON.stringify(tokens), { status: 200 })) + .mockResolvedValueOnce(new Response(JSON.stringify(me), { status: 200 })); + global.fetch = fetchMock; + return fetchMock; + } + + beforeEach(() => { + jest.clearAllMocks(); + jest.mocked(getMobileDeviceId).mockResolvedValue('device-1'); + jest.mocked(SecureStore.setItemAsync).mockResolvedValue(); + jest.mocked(SecureStore.getItemAsync).mockResolvedValue(JSON.stringify(tokens)); + }); + + it('posts the id_token grant with the raw nonce and device id', async () => { + const fetchMock = mockSuccessfulFetch(); + + await signInWithAppleIdToken({ + idToken: 'id-token', + nonce: 'raw-nonce', + firstName: 'Ada', + lastName: 'Lovelace', + }); + + const [url, init] = fetchMock.mock.calls[0]!; + expect(url).toBe('https://api.example.test/api/auth/mobile/token'); + expect(JSON.parse(init.body as string)).toEqual({ + deviceId: 'device-1', + grantType: 'id_token', + idToken: 'id-token', + nonce: 'raw-nonce', + provider: 'apple', + user: { name: { firstName: 'Ada', lastName: 'Lovelace' } }, + }); + }); + + it('omits user when Apple sent no name', async () => { + const fetchMock = mockSuccessfulFetch(); + + await signInWithAppleIdToken({ + idToken: 'id-token', + nonce: 'raw-nonce', + firstName: null, + lastName: '', + }); + + const body = JSON.parse(fetchMock.mock.calls[0]![1].body as string) as Record; + expect(body).not.toHaveProperty('user'); + }); + + it('stores the tokens and returns the current user', async () => { + mockSuccessfulFetch(); + + const user = await signInWithAppleIdToken({ idToken: 'id-token', nonce: 'raw-nonce' }); + + expect(user).toEqual(me); + expect(SecureStore.setItemAsync).toHaveBeenCalledWith( + 'test-brand.authTokens', + expect.stringContaining('access'), + ); + }); + + it('surfaces the backend error code', async () => { + global.fetch = jest.fn().mockResolvedValue( + new Response(JSON.stringify({ message: 'Bad token', code: 'INVALID_ID_TOKEN' }), { + status: 401, + }), + ); + + await expect( + signInWithAppleIdToken({ idToken: 'id-token', nonce: 'raw-nonce' }), + ).rejects.toEqual(expect.objectContaining>({ code: 'INVALID_ID_TOKEN' })); + }); +}); diff --git a/src/api/auth-endpoints.ts b/src/api/auth-endpoints.ts index f61150d..5f5f06b 100644 --- a/src/api/auth-endpoints.ts +++ b/src/api/auth-endpoints.ts @@ -252,3 +252,49 @@ export async function exchangeSocialCode(code: string, codeVerifier: string): Pr await setAuthTokens((await response.json()) as MobileTokenResponse); return getCurrentUser(); } + +export interface AppleNonce { + /** Sent to the backend, which hashes it and compares with the token's `nonce` claim. */ + raw: string; + /** Lowercase SHA-256 hex of `raw`; this is what Apple embeds in the identity token. */ + hashed: string; +} + +/** Generates the replay-protection nonce pair for native Sign in with Apple (expo-crypto only — + * `crypto.subtle` doesn't exist on Hermes). */ +export async function createAppleNonce(): Promise { + const raw = `${Crypto.randomUUID()}${Crypto.randomUUID()}`.replaceAll('-', ''); + const hashed = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, raw); + return { raw, hashed }; +} + +export interface AppleIdTokenInput { + idToken: string; + /** The RAW nonce (the hashed form went to Apple). */ + nonce: string; + /** Apple only returns the name on the very first authorization, so forward it in that call. */ + firstName?: string | null; + lastName?: string | null; +} + +export async function signInWithAppleIdToken(input: AppleIdTokenInput): Promise { + const firstName = input.firstName?.trim() ?? ''; + const lastName = input.lastName?.trim() ?? ''; + const hasName = firstName !== '' || lastName !== ''; + + const response = await fetch(`${AUTH_BASE_URL}/mobile/token`, { + method: 'POST', + headers: AUTH_POST_HEADERS, + body: JSON.stringify({ + deviceId: await getMobileDeviceId(), + grantType: 'id_token', + idToken: input.idToken, + nonce: input.nonce, + provider: 'apple', + ...(hasName ? { user: { name: { firstName, lastName } } } : {}), + }), + }); + await throwIfError(response); + await setAuthTokens((await response.json()) as MobileTokenResponse); + return getCurrentUser(); +} diff --git a/src/features/auth/apple-sign-in-button.test.tsx b/src/features/auth/apple-sign-in-button.test.tsx new file mode 100644 index 0000000..3a098ee --- /dev/null +++ b/src/features/auth/apple-sign-in-button.test.tsx @@ -0,0 +1,125 @@ +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react-native'; +import * as AppleAuthentication from 'expo-apple-authentication'; +import { Platform } from 'react-native'; + +import { createAppleNonce, signInWithAppleIdToken } from '@/api/auth-endpoints'; +import { initI18n } from '@/i18n'; + +import { AppleSignInButton } from './apple-sign-in-button'; + +jest.mock('expo-apple-authentication', () => { + const { View } = jest.requireActual('react-native'); + return { + AppleAuthenticationButton: (props: { onPress: () => void }) => ( + + ), + AppleAuthenticationButtonStyle: { BLACK: 2, WHITE: 0 }, + AppleAuthenticationButtonType: { CONTINUE: 1 }, + AppleAuthenticationScope: { FULL_NAME: 0, EMAIL: 1 }, + isAvailableAsync: jest.fn(), + signInAsync: jest.fn(), + }; +}); +jest.mock('@/api/auth-endpoints', () => ({ + AuthApiError: class AuthApiError extends Error {}, + createAppleNonce: jest.fn(), + signInWithAppleIdToken: jest.fn(), +})); + +const user = { id: 'u1', email: 'a@b.test', name: 'Ada', mustChangePassword: false }; + +async function setup() { + const props = { + disabled: false, + onBusyChange: jest.fn(), + onSignedIn: jest.fn(), + onError: jest.fn(), + }; + await render(); + return { props }; +} + +async function press() { + await act(async () => { + fireEvent(await screen.findByTestId('apple-button'), 'touchEnd'); + }); +} + +beforeAll(() => { + initI18n(); +}); + +beforeEach(() => { + jest.clearAllMocks(); + Platform.OS = 'ios'; + jest.mocked(AppleAuthentication.isAvailableAsync).mockResolvedValue(true); + jest.mocked(createAppleNonce).mockResolvedValue({ raw: 'raw', hashed: 'hashed' }); +}); + +describe('AppleSignInButton', () => { + it('renders nothing when Sign in with Apple is unavailable', async () => { + jest.mocked(AppleAuthentication.isAvailableAsync).mockResolvedValue(false); + await setup(); + await waitFor(() => expect(AppleAuthentication.isAvailableAsync).toHaveBeenCalled()); + + expect(screen.queryByTestId('apple-button')).toBeNull(); + }); + + it('renders nothing on Android', async () => { + Platform.OS = 'android'; + await setup(); + + expect(screen.queryByTestId('apple-button')).toBeNull(); + expect(AppleAuthentication.isAvailableAsync).not.toHaveBeenCalled(); + }); + + it('shows no error when the user cancels', async () => { + jest + .mocked(AppleAuthentication.signInAsync) + .mockRejectedValue(Object.assign(new Error('canceled'), { code: 'ERR_REQUEST_CANCELED' })); + const { props } = await setup(); + + await press(); + + expect(props.onError).toHaveBeenCalledTimes(1); + expect(props.onError).toHaveBeenCalledWith(null); + expect(props.onSignedIn).not.toHaveBeenCalled(); + expect(props.onBusyChange).toHaveBeenLastCalledWith(false); + }); + + it('sends the hashed nonce to Apple and the raw nonce to the API', async () => { + jest.mocked(AppleAuthentication.signInAsync).mockResolvedValue({ + identityToken: 'id-token', + fullName: { givenName: 'Ada', familyName: 'Lovelace' }, + } as AppleAuthentication.AppleAuthenticationCredential); + jest.mocked(signInWithAppleIdToken).mockResolvedValue(user); + const { props } = await setup(); + + await press(); + + expect(AppleAuthentication.signInAsync).toHaveBeenCalledWith( + expect.objectContaining({ nonce: 'hashed' }), + ); + expect(signInWithAppleIdToken).toHaveBeenCalledWith({ + idToken: 'id-token', + nonce: 'raw', + firstName: 'Ada', + lastName: 'Lovelace', + }); + expect(props.onSignedIn).toHaveBeenCalledWith(user); + }); + + it('reports an error when Apple returns no identity token', async () => { + jest.mocked(AppleAuthentication.signInAsync).mockResolvedValue({ + identityToken: null, + fullName: null, + } as AppleAuthentication.AppleAuthenticationCredential); + const { props } = await setup(); + + await press(); + + expect(signInWithAppleIdToken).not.toHaveBeenCalled(); + expect(props.onError).toHaveBeenLastCalledWith(expect.any(String)); + expect(props.onSignedIn).not.toHaveBeenCalled(); + }); +}); diff --git a/src/features/auth/apple-sign-in-button.tsx b/src/features/auth/apple-sign-in-button.tsx new file mode 100644 index 0000000..83be11e --- /dev/null +++ b/src/features/auth/apple-sign-in-button.tsx @@ -0,0 +1,123 @@ +import * as AppleAuthentication from 'expo-apple-authentication'; +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Platform, StyleSheet } from 'react-native'; + +import { + AuthApiError, + createAppleNonce, + signInWithAppleIdToken, + type SessionUser, +} from '@/api/auth-endpoints'; +import { radiusTokens } from '@/theme/tokens'; +import { useResolvedScheme } from '@/theme/use-theme'; + +const BUTTON_HEIGHT = 56; +const CANCELED_CODE = 'ERR_REQUEST_CANCELED'; + +interface AppleSignInButtonProps { + /** True while any provider's sign-in is running, so a second one can't start. */ + disabled: boolean; + onBusyChange: (busy: boolean) => void; + onSignedIn: (user: SessionUser) => void; + /** Called with a message on failure, or `null` when a new attempt starts. */ + onError: (message: string | null) => void; +} + +function isCanceled(error: unknown): boolean { + return ( + typeof error === 'object' && + error !== null && + (error as { code?: unknown }).code === CANCELED_CODE + ); +} + +/** Native Sign in with Apple (iOS only). Apple receives the SHA-256 of a nonce and the backend the + * raw value, so a stolen identity token can't be replayed. */ +export function AppleSignInButton({ + disabled, + onBusyChange, + onSignedIn, + onError, +}: AppleSignInButtonProps) { + const { t } = useTranslation(); + const scheme = useResolvedScheme(); + const [isAvailable, setIsAvailable] = useState(false); + + useEffect(() => { + if (Platform.OS !== 'ios') return; + let isActive = true; + AppleAuthentication.isAvailableAsync() + .then((available) => { + if (isActive) setIsAvailable(available); + }) + .catch(() => { + if (isActive) setIsAvailable(false); + }); + return () => { + isActive = false; + }; + }, []); + + if (Platform.OS !== 'ios' || !isAvailable) return null; + + const handlePress = async () => { + if (disabled) return; + onError(null); + onBusyChange(true); + try { + const nonce = await createAppleNonce(); + const credential = await AppleAuthentication.signInAsync({ + requestedScopes: [ + AppleAuthentication.AppleAuthenticationScope.FULL_NAME, + AppleAuthentication.AppleAuthenticationScope.EMAIL, + ], + nonce: nonce.hashed, + }); + + if (!credential.identityToken) { + onError(t('auth.socialSignInFailed')); + return; + } + + const user = await signInWithAppleIdToken({ + idToken: credential.identityToken, + nonce: nonce.raw, + firstName: credential.fullName?.givenName, + lastName: credential.fullName?.familyName, + }); + onSignedIn(user); + } catch (error) { + // Backing out of the Apple sheet isn't an error. + if (isCanceled(error)) return; + if (__DEV__) console.warn('[apple-sign-in] failed', error); + onError(error instanceof AuthApiError ? error.message : t('auth.socialSignInFailed')); + } finally { + onBusyChange(false); + } + }; + + return ( + + ); +} + +const styles = StyleSheet.create({ + button: { + height: BUTTON_HEIGHT, + width: '100%', + }, + disabled: { + opacity: 0.5, + }, +}); diff --git a/src/features/auth/social-buttons.tsx b/src/features/auth/social-buttons.tsx index 207120d..670dae2 100644 --- a/src/features/auth/social-buttons.tsx +++ b/src/features/auth/social-buttons.tsx @@ -4,14 +4,21 @@ import { useState } from 'react'; import { useTranslation } from 'react-i18next'; import { StyleSheet, View } from 'react-native'; -import { exchangeSocialCode, SOCIAL_CALLBACK_URL, startSocialSignIn } from '@/api/auth-endpoints'; +import { + exchangeSocialCode, + SOCIAL_CALLBACK_URL, + startSocialSignIn, + type SessionUser, +} from '@/api/auth-endpoints'; import { BrandIcon, GoogleLogo } from '@/components/ui/brand-icons'; import { Button } from '@/components/ui/button'; import { ErrorBanner } from '@/components/ui/error-banner'; import { consumePendingDeepLink } from '@/lib/pending-deep-link'; import { useAuthStore } from '@/stores/use-auth-store'; -type Provider = 'google' | 'facebook'; +import { AppleSignInButton } from './apple-sign-in-button'; + +type Provider = 'google' | 'facebook' | 'apple'; /** * Social sign-in uses the browser only for the provider interaction. The @@ -24,7 +31,16 @@ export function SocialButtons() { const [error, setError] = useState(null); const [loadingProvider, setLoadingProvider] = useState(null); - const handleSignIn = async (provider: Provider) => { + const completeSignIn = (user: SessionUser) => { + setSignedIn(user); + const pendingDeepLink = user.mustChangePassword ? null : consumePendingDeepLink(); + // A captured deep link is an arbitrary runtime string, not a route this app's typed-routes + // manifest can know statically — `Href` (rather than `as never`) is expo-router's own type + // for exactly this "any valid path string" case. + router.replace((pendingDeepLink ?? '/') as Href); + }; + + const handleSignIn = async (provider: 'google' | 'facebook') => { setError(null); setLoadingProvider(provider); try { @@ -44,14 +60,7 @@ export function SocialButtons() { return; } - const user = await exchangeSocialCode(code, start.codeVerifier); - - setSignedIn(user); - const pendingDeepLink = user.mustChangePassword ? null : consumePendingDeepLink(); - // A captured deep link is an arbitrary runtime string, not a route this app's typed-routes - // manifest can know statically — `Href` (rather than `as never`) is expo-router's own type - // for exactly this "any valid path string" case. - router.replace((pendingDeepLink ?? '/') as Href); + completeSignIn(await exchangeSocialCode(code, start.codeVerifier)); } catch (err) { setError(err instanceof Error ? err.message : t('errors.unknown')); } finally { @@ -62,6 +71,13 @@ export function SocialButtons() { return ( {error ? : null} + {/* Apple first: guideline 4.8 wants it at least as prominent as the other providers. */} + setLoadingProvider(busy ? 'apple' : null)} + onSignedIn={completeSignIn} + onError={setError} + />