Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(auth): trust only verified Apple emails (#61)

OKNOTOKc1627d68fdd8
diff --git a/server/src/__tests__/oauth-apple-email.test.ts b/server/src/__tests__/oauth-apple-email.test.ts
new file mode 100644
index 0000000..94af27a
--- /dev/null
+++ b/server/src/__tests__/oauth-apple-email.test.ts
@@ -0,0 +1,58 @@
+/**
+ * Regression tests for the Sign in with Apple account-linking boundary.
+ *
+ * Run: node --import tsx --test server/src/__tests__/oauth-apple-email.test.ts
+ */
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { resolveTrustedAppleEmail } from '../apple.js'
+
+test('unlinked Apple identity rejects an email-less token even when the client supplies a victim email', () => {
+ const attackerInput = {
+ linkedEmail: null,
+ tokenEmail: null,
+ tokenEmailVerified: false,
+ // Extra request metadata must never enter the trusted selector.
+ fallbackEmail: '[email protected]',
+ }
+
+ assert.throws(
+ () => resolveTrustedAppleEmail(attackerInput),
+ /verified email not available for unlinked identity/,
+ )
+})
+
+test('unlinked Apple identity rejects an unverified token email', () => {
+ assert.throws(
+ () => resolveTrustedAppleEmail({
+ linkedEmail: null,
+ tokenEmail: '[email protected]',
+ tokenEmailVerified: false,
+ }),
+ /verified email not available for unlinked identity/,
+ )
+})
+
+test('unlinked Apple identity accepts and normalizes a verified token email', () => {
+ assert.equal(resolveTrustedAppleEmail({
+ linkedEmail: null,
+ tokenEmail: ' [email protected] ',
+ tokenEmailVerified: true,
+})
+
+test('linked Apple identity reauthenticates from its stored email without a token email', () => {
+ assert.equal(resolveTrustedAppleEmail({
+ linkedEmail: '[email protected]',
+ tokenEmail: null,
+ tokenEmailVerified: false,
+})
+
+test('linked Apple identity remains authoritative when a later token carries another email', () => {
+ assert.equal(resolveTrustedAppleEmail({
+ linkedEmail: '[email protected]',
+ tokenEmail: '[email protected]',
+ tokenEmailVerified: true,
+})
diff --git a/server/src/api/router.ts b/server/src/api/router.ts
index a629c11..71a7865 100644
--- a/server/src/api/router.ts
+++ b/server/src/api/router.ts
@@ -718,11 +718,10 @@ api.get('/auth/callback/:provider', safe(async (req, res) => {
api.post('/auth/apple/native', safe(async (req, res) => {
const { handleAppleNativeSignIn, WaitlistedError, SuspendedError } = await import('../oauth.js')
const body = (req.body ?? {}) as {
- identityToken?: unknown; email?: unknown; name?: unknown; inviteToken?: unknown
+ identityToken?: unknown; name?: unknown; inviteToken?: unknown
}
const identityToken = typeof body.identityToken === 'string' ? body.identityToken : ''
if (!identityToken) { res.status(400).json({ error: 'identityToken required' }); return }
- const fallbackEmail = typeof body.email === 'string' ? body.email : null
const fallbackName = typeof body.name === 'string' ? body.name : null
const inviteToken = typeof body.inviteToken === 'string' ? body.inviteToken : null
const ip = req.socket.remoteAddress ?? null
@@ -730,7 +729,6 @@ api.post('/auth/apple/native', safe(async (req, res) => {
try {
const r = await handleAppleNativeSignIn({
identityToken,
- fallbackEmail,
fallbackName,
// Only our bundle id is accepted. If we later ship an Android
// app or web SIWA fallback they'll get distinct audiences.
diff --git a/server/src/apple.ts b/server/src/apple.ts
index c21cdab..69c4426 100644
--- a/server/src/apple.ts
+++ b/server/src/apple.ts
@@ -20,10 +20,11 @@
* - `email_verified` is always `"true"` (a string in JWT) on
* successful native flows.
*
- * Crucial Apple-quirk: `email` is only present on the FIRST sign-in
- * with this Apple ID + this app id. Subsequent sign-ins return a JWT
- * with `sub` but no `email`. Callers must remember the linkage by
- * `sub` and not depend on email being there every time.
+ * Apple's standalone credential/user metadata is only returned on the first
+ * authorization, but the signed identity token normally keeps carrying the
+ * email claim on later authorizations. Managed school accounts may have an
+ * empty email claim, so returning users still resolve by their persisted
+ * `sub` linkage rather than depending on email being present every time.
*/
import { createPublicKey, createVerify, type JsonWebKey } from 'node:crypto'
@@ -85,6 +86,29 @@ export interface AppleClaims {
aud: string
}
+/** Select the only email values that are safe to use for account lookup.
+ *
+ * A linked Apple `sub` is already the account identity, so its persisted
+ * email wins even if a later token contains a different value. For an
+ * unlinked `sub`, only an email attested by the signed Apple token may create
+ * or cross-link an account. Client callback fields are deliberately absent
+ * from this boundary: native credential metadata is display data, not proof
+ * of email ownership. */
+export function resolveTrustedAppleEmail(input: {
+ linkedEmail: string | null
+ tokenEmail: string | null
+ tokenEmailVerified: boolean
+}): string {
+ const linkedEmail = (input.linkedEmail ?? '').toLowerCase().trim()
+ if (linkedEmail) return linkedEmail
+
+ const tokenEmail = (input.tokenEmail ?? '').toLowerCase().trim()
+ if (!tokenEmail || !input.tokenEmailVerified) {
+ throw new Error('apple sign-in: verified email not available for unlinked identity')
+ }
+ return tokenEmail
+}
+
/** Verify an Apple identity_token. Throws on any tamper / expiry /
* wrong-audience / wrong-issuer / unknown-signing-key. Returns the
* trusted claims if everything checks out. */
diff --git a/server/src/oauth.ts b/server/src/oauth.ts
index dd25362..1387180 100644
--- a/server/src/oauth.ts
+++ b/server/src/oauth.ts
@@ -623,16 +623,14 @@ export async function handleCallback(args: {
* browser redirect involved (this is a fetch from the native app).
*
* Apple-specific subtleties handled here:
- * - `email` and `name` are only populated by Apple on the user's
- * FIRST sign-in to our app — subsequent sign-ins return a JWT
- * with `sub` only. Clients can pass cached email/name as a
- * fallback for users who reinstalled the app, but the primary
- * identifier is always `sub` via the user_identities lookup. */
+ * - Apple's standalone credential metadata is first-authorization-only;
+ * the signed JWT normally keeps carrying email while name remains
+ * client metadata. Returning users resolve solely through the persisted
+ * `sub` identity; an unlinked user must present a verified email claim in
+ * the signed token. Client-provided names never participate in identity
+ * matching. */
export async function handleAppleNativeSignIn(args: {
identityToken: string
- /** Email passed from the JS layer on FIRST sign-in only, when
- * Apple's native callback populated it. Lowercased before use. */
- fallbackEmail?: string | null
/** Name passed from the JS layer on FIRST sign-in only. Used only
* when creating a brand-new user row. */
fallbackName?: string | null
@@ -645,24 +643,22 @@ export async function handleAppleNativeSignIn(args: {
ip: string | null
userAgent: string | null
}): Promise<{ token: string; userId: string; email: string; displayName: string; companyId: string | null }> {
- const { verifyAppleIdentityToken } = await import('./apple.js')
+ const { resolveTrustedAppleEmail, verifyAppleIdentityToken } = await import('./apple.js')
const claims = await verifyAppleIdentityToken(args.identityToken, args.audiences)
- // Email: from JWT if Apple included it; otherwise the client's
- // cached fallback. Throw if neither — Apple flat-out won't tell us
- // and we need *something* for the user record on first sign-in.
- // (After path A exists, neither email is needed — the linked
- // user_identities row resolves the user by `sub` alone, and we
- // pass the still-required `email` placeholder through to finalize.)
- const linked = await pool.query<{ user_id: string; email_lower: string }>(
- `SELECT user_id, email_lower FROM user_identities
+ // Resolve the stable identity first. Returning users do not need an email
+ // claim; first sign-ins may create/cross-link an account only from Apple's
+ // signed, verified claim — never from request-body metadata.
+ const linked = await pool.query<{ email_lower: string }>(
+ `SELECT email_lower FROM user_identities
WHERE provider = $1 AND provider_id = $2`,
['apple', claims.sub],
)
const knownEmail = linked.rows[0]?.email_lower ?? null
- const email = (claims.email ?? args.fallbackEmail ?? knownEmail ?? '').toLowerCase().trim()
- if (!email) {
- throw new Error('apple sign-in: email not available (first-time sign-ins must include the email Apple returned)')
- }
+ const email = resolveTrustedAppleEmail({
+ linkedEmail: knownEmail,
+ tokenEmail: claims.email,
+ tokenEmailVerified: claims.emailVerified,
+ })
const displayName = (args.fallbackName ?? email.split('@')[0] ?? 'You').trim() || 'You'
let result: CompletionResult
diff --git a/src/api/client.ts b/src/api/client.ts
index b6a3b6a..96f2d8b 100644
--- a/src/api/client.ts
+++ b/src/api/client.ts
@@ -781,12 +781,11 @@ export const api = {
* from the iOS-native ASAuthorization flow. Server verifies the JWT
* against Apple's JWKS, find-or-creates the user, and returns a
* fresh session token. */
- authAppleNative: (input: { identityToken: string; email?: string | null; name?: string | null; inviteToken?: string | null }) =>
+ authAppleNative: (input: { identityToken: string; name?: string | null; inviteToken?: string | null }) =>
http<{ token: string; user: { id: string; email: string; displayName: string }; companyId: string | null }>('/auth/apple/native', {
method: 'POST',
body: JSON.stringify({
identityToken: input.identityToken,
- email: input.email ?? null,
name: input.name ?? null,
inviteToken: input.inviteToken ?? null,
}),
diff --git a/src/components/AuthScreen.tsx b/src/components/AuthScreen.tsx
index 6f0cf7a..419cfbf 100644
--- a/src/components/AuthScreen.tsx
+++ b/src/components/AuthScreen.tsx
@@ -79,8 +79,8 @@ export function AuthScreen() {
async function goApple() {
setBusy('apple'); setErr(null)
try {
- const { identityToken, email, name } = await runAppleSignIn()
- const r = await api.authAppleNative({ identityToken, email, name })
+ const { identityToken, name } = await runAppleSignIn()
+ const r = await api.authAppleNative({ identityToken, name })
useAuth.getState().setSession(r.token, { id: r.user.id, email: r.user.email, name: r.user.displayName }, r.companyId)
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)