feat(auth): add production-grade Firebase Authentication setup with secure session cookies, CSRF defense, and UI modal

This commit is contained in:
2026-11-13 11:21:34 +05:30
parent a9c092ba03
commit 0fe0457136
14 changed files with 4154 additions and 20 deletions
+84
View File
@@ -0,0 +1,84 @@
import { describe, it, expect, vi } from 'vitest';
import { isFirebaseClientConfigured } from '@/lib/firebase/config';
import { isFirebaseAdminConfigured } from '@/lib/firebase/admin';
import { POST as sessionPost, DELETE as sessionDelete, GET as sessionGet } from '@/app/api/auth/session/route';
import { NextRequest } from 'next/server';
describe('Firebase Authentication Architecture & Security Guards', () => {
it('correctly evaluates client configuration state', () => {
// In unconfigured state (empty env vars)
const configured = isFirebaseClientConfigured();
expect(typeof configured).toBe('boolean');
});
it('correctly evaluates admin configuration state', () => {
const adminConfigured = isFirebaseAdminConfigured();
expect(typeof adminConfigured).toBe('boolean');
});
it('rejects POST /api/auth/session requests with mismatched or forged origin (CSRF defense)', async () => {
const fakeReq = new NextRequest('http://localhost:3000/api/auth/session', {
method: 'POST',
headers: {
host: 'localhost:3000',
origin: 'https://malicious-attacker.com',
'content-type': 'application/json',
},
body: JSON.stringify({ idToken: 'fake-token' }),
});
const res = await sessionPost(fakeReq);
expect(res.status).toBe(403);
const data = await res.json();
expect(data.error).toContain('CSRF');
});
it('rejects POST /api/auth/session requests with missing idToken', async () => {
const req = new NextRequest('http://localhost:3000/api/auth/session', {
method: 'POST',
headers: {
host: 'localhost:3000',
origin: 'http://localhost:3000',
'content-type': 'application/json',
},
body: JSON.stringify({}),
});
const res = await sessionPost(req);
expect(res.status).toBe(400);
const data = await res.json();
expect(data.error).toBe('Valid idToken required');
});
it('accepts valid origin on DELETE /api/auth/session and clears cookie', async () => {
const req = new NextRequest('http://localhost:3000/api/auth/session', {
method: 'DELETE',
headers: {
host: 'localhost:3000',
origin: 'http://localhost:3000',
},
});
const res = await sessionDelete(req);
expect(res.status).toBe(200);
const data = await res.json();
expect(data.success).toBe(true);
const setCookie = res.headers.get('set-cookie');
expect(setCookie).toContain('__session=;');
});
it('returns unauthenticated on GET /api/auth/session when no session cookie is provided', async () => {
const req = new NextRequest('http://localhost:3000/api/auth/session', {
method: 'GET',
headers: {
host: 'localhost:3000',
},
});
const res = await sessionGet(req);
expect(res.status).toBe(200);
const data = await res.json();
expect(data.authenticated).toBe(false);
expect(data.user).toBeNull();
});
});