# Email Normalization

> **See also:** [AUTH_EMAIL_NORMALIZATION.md](./AUTH_EMAIL_NORMALIZATION.md)
> for the full treatment, including OAuth identity recovery when an admin has
> edited a user's email. This file is the short form covering the `+tag` /
> lowercasing rule only.

## The Problem

Gmail and many email providers treat `user+tag@domain.com` as equivalent to `user@domain.com`. The `+tag` portion is ignored for delivery but can be used for filtering.

This causes issues with OAuth:

- User registers with `timothy+test@aimclear.com`
- Google OAuth returns `timothy@aimclear.com` (canonical form)
- Stripe session has `timothy+test@aimclear.com`
- Email mismatch prevents OAuth account linking

## The Solution

All email addresses are normalized before database lookups or user creation by removing the `+tag` portion and lowercasing.

**Implementation:** `lib/email-utils.ts`

**Applied in:**

1. `lib/auth.ts` - OAuth signIn callback
2. `lib/auth.ts` - JWT callback
3. `lib/stripe-webhook-handlers.ts` - Stripe webhook handler

## Examples

| Input                       | Normalized             |
| --------------------------- | ---------------------- |
| `timothy+test@aimclear.com` | `timothy@aimclear.com` |
| `User+Signup@Gmail.com`     | `user@gmail.com`       |
| `JOHN@Example.COM`          | `john@example.com`     |

## Key Points

- No duplicate accounts for the same email with different tags
- OAuth works correctly regardless of which email variant is used
- Always normalize before any email comparison or lookup
