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: 6 additions & 0 deletions app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`,
Expand Down Expand Up @@ -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',
Expand Down
14 changes: 14 additions & 0 deletions docs/deploy.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
16 changes: 16 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

114 changes: 113 additions & 1 deletion src/api/auth-endpoints.test.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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<string, unknown>;
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<Partial<AuthApiError>>({ code: 'INVALID_ID_TOKEN' }));
});
});
46 changes: 46 additions & 0 deletions src/api/auth-endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<AppleNonce> {
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<SessionUser> {
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();
}
125 changes: 125 additions & 0 deletions src/features/auth/apple-sign-in-button.test.tsx
Original file line number Diff line number Diff line change
@@ -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<typeof import('react-native')>('react-native');
return {
AppleAuthenticationButton: (props: { onPress: () => void }) => (
<View testID="apple-button" onTouchEnd={props.onPress} />
),
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(<AppleSignInButton {...props} />);
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();
});
});
Loading
Loading