Skip to content

Commit 4e491c6

Browse files
GRACENOBLEclaude
andcommitted
fix(web): address CodeRabbit review findings on auth layer
Security: - Verify Firebase ID tokens with firebase-admin verifyIdToken() instead of decoding the JWT payload without signature verification; add lib/firebase-admin.ts with singleton Admin app init - Sign out of Firebase client alongside NextAuth in useSignOut hook to prevent stale Firebase auth state after logout Correctness: - Preserve query string in callbackUrl (proxy.ts) so users are returned to their original URL with params after login - Restore sidebar open/close state from cookie in DashboardLayout by reading the sidebar_state cookie server-side and passing as defaultOpen - Fix NavAuth test mock shape: use user instead of session to match the UseSessionReturn type - Handle popup-dismissed Firebase errors silently in GoogleSignInButton; disable button while sign-in is in flight Quality: - Switch to z.email() (Zod v4.4.3+) from deprecated z.string().email() - Update docs/auth.md to accurately describe the Firebase idToken flow - Fix stale middleware.ts reference in docs/_index.md to proxy.ts - Add FIREBASE_PROJECT_ID and FIREBASE_SERVICE_ACCOUNT_JSON to web/.env.example Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 1b7ee56 commit 4e491c6

13 files changed

Lines changed: 1129 additions & 46 deletions

File tree

‎web/.env.example‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@ NEXT_PUBLIC_SENTRY_DSN=
44
# NextAuth.js — required for session management
55
AUTH_SECRET= # openssl rand -base64 32
66

7+
# Firebase Admin SDK — server-side token verification
8+
# Set FIREBASE_SERVICE_ACCOUNT_JSON to the full service account JSON (single line, no newlines).
9+
# If omitted, set FIREBASE_PROJECT_ID and rely on Application Default Credentials (GCP only).
10+
FIREBASE_PROJECT_ID= # same as NEXT_PUBLIC_FIREBASE_PROJECT_ID, server-side only
11+
FIREBASE_SERVICE_ACCOUNT_JSON= # {"type":"service_account","project_id":"..."}
12+
713
# Firebase — client-side config (copy from Firebase Console > Project settings)
814
NEXT_PUBLIC_FIREBASE_API_KEY=
915
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=

‎web/app/(dashboard)/layout.tsx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
1+
import { cookies } from 'next/headers'
12
import { SidebarInset, SidebarProvider, SidebarTrigger } from '@/components/ui/sidebar'
23
import { AppSidebar } from '@/components/layout/AppSidebar'
34

4-
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
5+
export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
6+
const cookieStore = await cookies()
7+
const sidebarOpen = cookieStore.get('sidebar_state')?.value !== 'false'
8+
59
return (
6-
<SidebarProvider className="flex flex-1">
10+
<SidebarProvider defaultOpen={sidebarOpen} className="flex flex-1">
711
<AppSidebar />
812
<SidebarInset className="flex flex-col">
913
<header className="flex h-12 shrink-0 items-center border-b px-4">

‎web/auth.ts‎

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import NextAuth from "next-auth"
22
import Credentials from "next-auth/providers/credentials"
33
import { z } from "zod"
4+
import { verifyFirebaseToken } from "@/lib/firebase-admin"
45

56
export const { handlers, auth, signIn, signOut } = NextAuth({
67
providers: [
@@ -10,21 +11,15 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
1011
const parsed = z.object({ idToken: z.string().min(1) }).safeParse(credentials)
1112
if (!parsed.success) return null
1213

13-
const parts = parsed.data.idToken.split(".")
14-
if (parts.length !== 3) return null
15-
1614
try {
17-
const payload = JSON.parse(
18-
Buffer.from(parts[1], "base64url").toString("utf-8"),
19-
) as { sub?: string; email?: string; name?: string; picture?: string }
20-
21-
if (!payload.sub) return null
15+
const decoded = await verifyFirebaseToken(parsed.data.idToken)
16+
if (!decoded.sub) return null
2217

2318
return {
24-
id: payload.sub,
25-
email: payload.email ?? null,
26-
name: payload.name ?? null,
27-
image: payload.picture ?? null,
19+
id: decoded.sub,
20+
email: decoded.email ?? null,
21+
name: decoded.name ?? null,
22+
image: decoded.picture ?? null,
2823
}
2924
} catch {
3025
return null

‎web/components/layout/__tests__/NavAuth.test.tsx‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,19 +19,19 @@ const mockUseSession = vi.mocked(useSession)
1919

2020
describe('NavAuth', () => {
2121
it('shows a loading skeleton while session is loading', () => {
22-
mockUseSession.mockReturnValue({ isLoading: true, isAuthenticated: false, session: null })
22+
mockUseSession.mockReturnValue({ isLoading: true, isAuthenticated: false, user: null })
2323
const { container } = render(<NavAuth />)
2424
expect(container.querySelector('.animate-pulse')).toBeInTheDocument()
2525
})
2626

2727
it('renders UserMenu when authenticated', () => {
28-
mockUseSession.mockReturnValue({ isLoading: false, isAuthenticated: true, session: { user: { email: 'a@b.com' }, expires: '2099' } })
28+
mockUseSession.mockReturnValue({ isLoading: false, isAuthenticated: true, user: { email: 'a@b.com' } })
2929
render(<NavAuth />)
3030
expect(screen.getByTestId('user-menu')).toBeInTheDocument()
3131
})
3232

3333
it('renders a sign-in link when unauthenticated', () => {
34-
mockUseSession.mockReturnValue({ isLoading: false, isAuthenticated: false, session: null })
34+
mockUseSession.mockReturnValue({ isLoading: false, isAuthenticated: false, user: null })
3535
render(<NavAuth />)
3636
expect(screen.getByRole('link', { name: /sign in/i })).toBeInTheDocument()
3737
})

‎web/docs/_index.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,4 @@ The `docs` agent reads this index first to locate the right file.
1515
| WebSocket hook (useWebSocket, reconnect, auth) | [websocket.md](websocket.md) | `lib/useWebSocket.ts`, `lib/useWebSocket.test.ts` |
1616
| Firebase Cloud Messaging — permission, token, service worker, useFCM hook | [fcm.md](fcm.md) | `lib/fcm.ts`, `lib/useFCM.ts`, `public/firebase-messaging-sw.js`, `lib/fcm.test.ts` |
1717
| Object storage (Cloudflare R2) — presign utility, uploadToR2, useUpload hook | [storage.md](storage.md) | `lib/storage.ts`, `lib/useUpload.ts` |
18-
| Authentication (NextAuth v5) — providers, session, middleware, forms, hooks | [auth.md](auth.md) | `auth.ts`, `middleware.ts`, `features/auth/` |
18+
| Authentication (NextAuth v5) — providers, session, proxy, forms, hooks | [auth.md](auth.md) | `auth.ts`, `proxy.ts`, `features/auth/` |

‎web/docs/auth.md‎

Lines changed: 80 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ topic: auth
33
last_verified: 2026-06-24
44
sources:
55
- auth.ts
6+
- lib/firebase.ts
7+
- lib/firebase-admin.ts
68
- app/api/auth/[...nextauth]/route.ts
79
- proxy.ts
810
- server/trpc.ts
@@ -23,14 +25,23 @@ sources:
2325

2426
# Authentication
2527

26-
NextAuth v5 (`next-auth@beta`) with Google OAuth and Credentials providers.
28+
Firebase-first auth with NextAuth v5 (Auth.js) for session management.
29+
30+
**Flow overview:**
31+
1. Client signs in with Firebase Auth (Google popup or email/password).
32+
2. Client retrieves a Firebase ID token (`user.getIdToken()`).
33+
3. Client calls NextAuth's Credentials provider with `{ idToken }`.
34+
4. `auth.ts` verifies the token with Firebase Admin SDK (`verifyIdToken`), extracts claims, and returns a NextAuth user.
35+
5. NextAuth issues a JWT session cookie.
2736

2837
## Packages
2938

3039
```json
3140
"next-auth": "beta",
41+
"firebase": "^12.x",
42+
"firebase-admin": "^14.x",
3243
"react-hook-form": "^7.x",
33-
"@hookform/resolvers": "^3.x"
44+
"@hookform/resolvers": "^5.x"
3445
```
3546

3647
## Config (`auth.ts`)
@@ -42,15 +53,18 @@ export const { handlers, auth, signIn, signOut } = NextAuth({ ... })
4253
```
4354

4455
- **`handlers`** — `{ GET, POST }` for the route handler.
45-
- **`auth()`** — async function; call in Server Components, Server Actions, and middleware to read the session.
56+
- **`auth()`** — async function; call in Server Components, Server Actions, and proxy to read the session.
4657
- **`signIn(provider, options)`** — trigger sign-in from server context.
4758
- **`signOut(options)`** — trigger sign-out from server context.
4859

49-
### Providers
60+
### Provider
5061

51-
**Google** — reads `AUTH_GOOGLE_ID` / `AUTH_GOOGLE_SECRET` from env.
62+
Single **Credentials** provider that accepts `{ idToken: string }`.
5263

53-
**Credentials** — validates email + password with Zod, then proxies a `POST` to `${NEXT_PUBLIC_API_URL}/auth/login`. Returns `{ id, email, name }` on success or `null` on failure.
64+
`authorize()`:
65+
1. Validates `idToken` is a non-empty string with Zod.
66+
2. Calls `verifyFirebaseToken(idToken)` (Firebase Admin SDK) — verifies signature, expiry, audience, and issuer.
67+
3. Returns `{ id, email, name, image }` from the decoded claims, or `null` on any failure.
5468

5569
### Session strategy
5670

@@ -64,6 +78,24 @@ session: { strategy: 'jwt' }
6478
pages: { signIn: '/login' }
6579
```
6680

81+
## Firebase Admin SDK (`lib/firebase-admin.ts`)
82+
83+
Initialises the Admin app once (singleton) and exports `verifyFirebaseToken`:
84+
85+
```ts
86+
export async function verifyFirebaseToken(idToken: string) {
87+
return getAuth(getAdminApp()).verifyIdToken(idToken)
88+
}
89+
```
90+
91+
Initialization precedence:
92+
1. `FIREBASE_SERVICE_ACCOUNT_JSON` (full service account JSON string) — works everywhere.
93+
2. `FIREBASE_PROJECT_ID` alone — works on GCP with Application Default Credentials.
94+
95+
## Firebase Client SDK (`lib/firebase.ts`)
96+
97+
Exports `getFirebaseAuth()` for use in client components. Initialises the Firebase app once using `NEXT_PUBLIC_FIREBASE_*` env vars.
98+
6799
## Route handler (`app/api/auth/[...nextauth]/route.ts`)
68100

69101
```ts
@@ -83,17 +115,17 @@ import { auth } from "@/auth"
83115
export default auth((req: NextAuthRequest) => {
84116
if (!req.auth) {
85117
const loginUrl = new URL("/login", req.url)
86-
loginUrl.searchParams.set("callbackUrl", req.nextUrl.pathname)
118+
loginUrl.searchParams.set("callbackUrl", req.nextUrl.pathname + req.nextUrl.search)
87119
return NextResponse.redirect(loginUrl)
88120
}
89121
})
90122

91123
export const config = {
92-
matcher: ["/dashboard/:path*"],
124+
matcher: ["/dashboard/:path*", "/settings/:path*"],
93125
}
94126
```
95127

96-
Unauthenticated requests to `/dashboard/*` are redirected to `/login?callbackUrl=<original-path>`.
128+
Unauthenticated requests to `/dashboard/*` or `/settings/*` are redirected to `/login?callbackUrl=<original-path-and-query>`.
97129

98130
### Additional guard in Server Components
99131

@@ -138,6 +170,7 @@ export function Providers({ children }: { children: React.ReactNode }) {
138170
return (
139171
<SessionProvider>
140172
<TRPCProvider>{children}</TRPCProvider>
173+
<Toaster richColors position="top-right" />
141174
</SessionProvider>
142175
)
143176
}
@@ -165,25 +198,42 @@ export interface AuthSession {
165198

166199
Zod v4 schemas:
167200

168-
- **`loginSchema`** — `{ email: string, password: string }` (password min 1).
169-
- **`registerSchema`** — `{ name: string (min 2), email: string, password: string (min 8), confirmPassword: string }` with `.refine` for password match.
201+
- **`loginSchema`** — `{ email: z.email(), password: string (min 1) }`.
202+
- **`registerSchema`** — `{ name: string (min 2), email: z.email(), password: string (min 8), confirmPassword: string }` with `.refine` for password match.
170203
- Exports inferred types `LoginFormValues` and `RegisterFormValues`.
171204

205+
Used with `standardSchemaResolver` from `@hookform/resolvers/standard-schema` (required for Zod v4).
206+
172207
## Auth components (`features/auth/components/`)
173208

174-
All are `'use client'` components.
209+
All are `'use client'` components. Errors are surfaced via Sonner toasts, not inline error state.
175210

176211
### `LoginForm`
177212

178-
`react-hook-form` with `standardSchemaResolver(loginSchema)` from `@hookform/resolvers/standard-schema`. Calls `signIn('credentials', { redirect: false })` from `next-auth/react` on submit, then pushes to `/dashboard` on success. Displays an inline error string on failure.
213+
`react-hook-form` with `standardSchemaResolver(loginSchema)`. On submit:
214+
1. `signInWithEmailAndPassword(getFirebaseAuth(), email, password)` via Firebase.
215+
2. Retrieves ID token from the credential.
216+
3. `signIn('credentials', { idToken, redirect: false })` via NextAuth.
217+
4. Pushes to `/dashboard` on success; shows `toast.error` on failure.
179218

180219
### `RegisterForm`
181220

182-
Same form setup with `registerSchema`. On submit: POSTs to `${NEXT_PUBLIC_API_URL}/auth/register`, then calls `signIn('credentials', { redirect: false })` to sign in immediately after registration. Pushes to `/dashboard` on success.
221+
Same form setup with `registerSchema`. On submit:
222+
1. `createUserWithEmailAndPassword(getFirebaseAuth(), email, password)`.
223+
2. `updateProfile(user, { displayName: name })`.
224+
3. Retrieves ID token.
225+
4. `signIn('credentials', { idToken, redirect: false })`.
226+
5. Pushes to `/dashboard` on success.
227+
Handles `auth/email-already-in-use` with a specific toast message.
183228

184229
### `GoogleSignInButton`
185230

186-
Calls `signIn('google', { callbackUrl: '/dashboard' })` on click. Renders a `Button` with the Google SVG logo inline.
231+
On click:
232+
1. `signInWithPopup(getFirebaseAuth(), new GoogleAuthProvider())`.
233+
2. Retrieves ID token.
234+
3. `signIn('credentials', { idToken, redirect: false })`.
235+
4. Pushes to `/dashboard` on success.
236+
Popup-dismissed errors (`auth/popup-closed-by-user`, `auth/cancelled-popup-request`) are silently ignored. Button is disabled while in-flight.
187237

188238
### `UserMenu`
189239

@@ -201,10 +251,14 @@ Wraps `useSession` from `next-auth/react`. Returns `UseSessionReturn`:
201251

202252
### `useSignOut`
203253

204-
Wraps `signOut` from `next-auth/react` with `{ redirect: false }`, then calls `router.push('/login')`.
254+
Signs out of both NextAuth and Firebase in parallel, then navigates to `/login`:
205255

206256
```ts
207-
const { signOut } = useSignOut()
257+
await Promise.all([
258+
nextAuthSignOut({ redirect: false }),
259+
firebaseSignOut(getFirebaseAuth()),
260+
])
261+
router.push('/login')
208262
```
209263

210264
## Pages
@@ -214,6 +268,7 @@ const { signOut } = useSignOut()
214268
| `/login` | `app/(auth)/login/page.tsx` | Server Component |
215269
| `/register` | `app/(auth)/register/page.tsx` | Server Component |
216270
| `/dashboard` | `app/(dashboard)/dashboard/page.tsx` | Server Component |
271+
| `/settings` | `app/(dashboard)/settings/page.tsx` | Server Component |
217272

218273
Login and Register pages are layout-less Server Components that render a centered `Card` containing `GoogleSignInButton`, a divider, the form, and a link to the other page.
219274

@@ -222,9 +277,14 @@ Login and Register pages are layout-less Server Components that render a centere
222277
| Variable | Description |
223278
|---|---|
224279
| `AUTH_SECRET` | Secret used to sign JWTs. Generate with `openssl rand -base64 32`. |
225-
| `AUTH_GOOGLE_ID` | Google OAuth client ID. |
226-
| `AUTH_GOOGLE_SECRET` | Google OAuth client secret. |
227-
| `NEXT_PUBLIC_API_URL` | Go backend base URL (e.g. `http://localhost:8080`). Used by Credentials provider and RegisterForm. |
280+
| `FIREBASE_PROJECT_ID` | Firebase project ID (server-side). Used when `FIREBASE_SERVICE_ACCOUNT_JSON` is absent and ADC is available (GCP). |
281+
| `FIREBASE_SERVICE_ACCOUNT_JSON` | Full service account JSON as a single-line string. Required outside GCP for `verifyIdToken`. |
282+
| `NEXT_PUBLIC_FIREBASE_API_KEY` | Firebase web API key. |
283+
| `NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN` | Firebase auth domain. |
284+
| `NEXT_PUBLIC_FIREBASE_PROJECT_ID` | Firebase project ID (client-side). |
285+
| `NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET` | Firebase storage bucket. |
286+
| `NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID` | Firebase messaging sender ID. |
287+
| `NEXT_PUBLIC_FIREBASE_APP_ID` | Firebase app ID. |
228288

229289
## Testing
230290

‎web/features/auth/components/GoogleSignInButton.tsx‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,45 @@
11
'use client'
22

3+
import { useState } from 'react'
34
import { GoogleAuthProvider, signInWithPopup } from 'firebase/auth'
45
import { signIn } from 'next-auth/react'
56
import { useRouter } from 'next/navigation'
67
import { toast } from 'sonner'
78
import { Button } from '@/components/ui/button'
89
import { getFirebaseAuth } from '@/lib/firebase'
910

11+
const POPUP_DISMISSED = new Set(['auth/popup-closed-by-user', 'auth/cancelled-popup-request'])
12+
1013
export function GoogleSignInButton() {
1114
const router = useRouter()
15+
const [isPending, setIsPending] = useState(false)
1216

1317
async function handleClick() {
18+
setIsPending(true)
1419
try {
1520
const result = await signInWithPopup(getFirebaseAuth(), new GoogleAuthProvider())
1621
const idToken = await result.user.getIdToken()
1722
const res = await signIn('credentials', { idToken, redirect: false })
1823
if (res?.ok) router.push('/dashboard')
1924
else toast.error('Sign-in failed. Please try again.')
20-
} catch {
21-
toast.error('Sign-in failed. Please try again.')
25+
} catch (err) {
26+
const code = (err as { code?: string }).code
27+
if (!code || !POPUP_DISMISSED.has(code)) {
28+
toast.error('Sign-in failed. Please try again.')
29+
}
30+
} finally {
31+
setIsPending(false)
2232
}
2333
}
2434

2535
return (
26-
<Button type="button" variant="outline" className="w-full" onClick={handleClick}>
36+
<Button
37+
type="button"
38+
variant="outline"
39+
className="w-full"
40+
onClick={handleClick}
41+
disabled={isPending}
42+
>
2743
<svg
2844
className="mr-2 h-4 w-4"
2945
aria-hidden="true"
@@ -47,7 +63,7 @@ export function GoogleSignInButton() {
4763
fill="#EA4335"
4864
/>
4965
</svg>
50-
Continue with Google
66+
{isPending ? 'Signing in…' : 'Continue with Google'}
5167
</Button>
5268
)
5369
}

‎web/features/auth/hooks/useSignOut.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
11
'use client'
22

33
import { signOut as nextAuthSignOut } from 'next-auth/react'
4+
import { signOut as firebaseSignOut } from 'firebase/auth'
45
import { useRouter } from 'next/navigation'
6+
import { getFirebaseAuth } from '@/lib/firebase'
57

68
export function useSignOut() {
79
const router = useRouter()
810

911
const signOut = async () => {
10-
await nextAuthSignOut({ redirect: false })
12+
await Promise.all([
13+
nextAuthSignOut({ redirect: false }),
14+
firebaseSignOut(getFirebaseAuth()),
15+
])
1116
router.push('/login')
1217
}
1318

‎web/features/auth/validation.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
import { z } from 'zod'
22

33
export const loginSchema = z.object({
4-
email: z.string().email('Please enter a valid email address'),
4+
email: z.email('Please enter a valid email address'),
55
password: z.string().min(1, 'Password is required'),
66
})
77

88
export const registerSchema = z
99
.object({
1010
name: z.string().min(2, 'Name must be at least 2 characters'),
11-
email: z.string().email('Please enter a valid email address'),
11+
email: z.email('Please enter a valid email address'),
1212
password: z.string().min(8, 'Password must be at least 8 characters'),
1313
confirmPassword: z.string(),
1414
})

0 commit comments

Comments
 (0)