Round 19: Fix auth 500/session persistence, script tag warning, module factory error, rate limiting

- Fix auth session persistence: set cookie on both cookies() and NextResponse
- Fix isSecureRequest: check x-forwarded-proto for HTTPS proxy support
- Fix excessive GET /api/auth polling: add useRef guard to prevent duplicate checks
- Increase rate limits: auth POST 30/min, auth GET 120/min
- Fix script tag warning: use ref-based textContent instead of dangerouslySetInnerHTML in chart.tsx
- Fix sanitizeHtml: improve regex patterns for script tag removal
- Fix module factory error: disable SW registration in dev, skip /_next/ caching in sw.js
- Bump SW cache version v2→v3 to force cache invalidation
- Better error handling in auth route with specific error messages
This commit is contained in:
Mustafa Cetin committed 2026-07-29 13:34:33 +00:00
1 parent 760fa70e82
commit 74404708e5
9 files changed
+192 -47

No files matched your search

+51 -11
View File
@@ -7,6 +7,9 @@ import {
createSession,
getSession,
clearSession,
isSecureRequest,
SESSION_COOKIE_NAME,
getSessionCookieOptions,
} from '@/lib/auth';
import { withRateLimit, checkRateLimit, getRateLimitKey, getRateLimitHeaders, createRateLimitResponse } from '@/lib/rate-limit';
@@ -60,9 +63,13 @@ export const POST = withRateLimit(async function POST(request: Request) {
);
}
await createSession(user.id);
const secure = isSecureRequest(request);
await createSession(user.id, secure);
return NextResponse.json({
// Also set cookie on the response object to guarantee the Set-Cookie
// header is included. In some Next.js App Router scenarios, cookies().set()
// alone may not propagate to the NextResponse body.
const response = NextResponse.json({
id: user.id,
email: user.email,
firstName: user.firstName,
@@ -72,6 +79,8 @@ export const POST = withRateLimit(async function POST(request: Request) {
locale: user.locale,
isDemo: user.isDemo,
});
response.cookies.set(SESSION_COOKIE_NAME, user.id, getSessionCookieOptions(secure));
return response;
}
// ── Register ──
@@ -108,9 +117,10 @@ export const POST = withRateLimit(async function POST(request: Request) {
},
});
await createSession(user.id);
const secure = isSecureRequest(request);
await createSession(user.id, secure);
return NextResponse.json(
const response = NextResponse.json(
{
id: user.id,
email: user.email,
@@ -123,28 +133,56 @@ export const POST = withRateLimit(async function POST(request: Request) {
},
{ status: 201 }
);
response.cookies.set(SESSION_COOKIE_NAME, user.id, getSessionCookieOptions(secure));
return response;
}
// ── Logout ──
if (action === 'logout') {
await clearSession();
return NextResponse.json({ message: 'Logged out' });
const response = NextResponse.json({ message: 'Logged out' });
response.cookies.delete(SESSION_COOKIE_NAME);
return response;
}
return NextResponse.json({ error: 'Unknown action' }, { status: 400 });
} catch (error) {
console.error('Auth error:', error);
console.error('Auth POST error:', error);
// Return more specific error info for debugging
const message =
error instanceof Error ? error.message : 'Unknown error';
const isZod = error instanceof z.ZodError;
const isPrisma =
error instanceof Error &&
(error.message.includes('Prisma') || error.constructor.name.includes('Prisma'));
if (isZod) {
return NextResponse.json(
{ error: 'Validation error', details: (error as z.ZodError).issues },
{ status: 400 }
);
}
if (isPrisma) {
return NextResponse.json(
{ error: 'Database error', detail: message },
{ status: 500 }
);
}
return NextResponse.json(
{ error: 'Internal server error' },
{ error: 'Internal server error', detail: message },
{ status: 500 }
);
}
}, 'auth');
export async function GET(request: Request) {
// Apply rate limit for auth check endpoint
// Apply rate limit for auth check endpoint — 120 per minute
const key = getRateLimitKey(request);
const result = checkRateLimit(key, 60, 60 * 1000); // 60 per minute for GET
const result = checkRateLimit(key, 120, 60 * 1000);
if (!result.allowed) {
const rateLimitResponse = createRateLimitResponse(result);
@@ -167,9 +205,11 @@ export async function GET(request: Request) {
}
return response;
} catch (error) {
console.error('Auth me error:', error);
console.error('Auth GET error:', error);
const message =
error instanceof Error ? error.message : 'Unknown error';
return NextResponse.json(
{ error: 'Internal server error' },
{ error: 'Internal server error', detail: message },
{ status: 500 }
);
}
+6 -1
View File
@@ -1,6 +1,6 @@
'use client';
import React, { useEffect } from 'react';
import React, { useEffect, useRef } from 'react';
import { useAppStore } from '@/lib/store';
import { fetchCurrentUser } from '@/lib/api';
import AuthView from '@/components/auth-view';
@@ -10,8 +10,13 @@ export default function Home() {
const currentUser = useAppStore((s) => s.currentUser);
const isLoadingAuth = useAppStore((s) => s.isLoadingAuth);
const setCurrentUser = useAppStore((s) => s.setCurrentUser);
const hasCheckedRef = useRef(false);
useEffect(() => {
// Prevent duplicate auth checks: only run once per component lifecycle
if (hasCheckedRef.current) return;
hasCheckedRef.current = true;
async function checkAuth() {
try {
const user = await fetchCurrentUser();
+3
View File
@@ -179,6 +179,9 @@ export function useServiceWorker() {
useEffect(() => {
if (typeof window === 'undefined') return;
if (!('serviceWorker' in navigator)) return;
// Skip service worker registration during development to avoid stale
// Turbopack chunk caching ("module factory is not available" errors)
if (process.env.NODE_ENV === 'development') return;
async function registerSW() {
try {
+9 -11
View File
@@ -78,12 +78,9 @@ const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
return null
}
return (
<style
dangerouslySetInnerHTML={{
__html: Object.entries(THEMES)
.map(
([theme, prefix]) => `
const cssText = Object.entries(THEMES)
.map(
([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
@@ -95,11 +92,12 @@ ${colorConfig
.join("\n")}
}
`
)
.join("\n"),
}}
/>
)
)
.join("\n")
// Use ref to set textContent instead of dangerouslySetInnerHTML to avoid
// React 19 "Encountered a script tag" warning for style elements
return <style ref={(el) => { if (el) el.textContent = cssText }} />
}
const ChartTooltip = RechartsPrimitive.Tooltip
+30 -10
View File
@@ -3,8 +3,33 @@ import { cookies } from 'next/headers';
import { Prisma } from '@prisma/client';
import { db } from '@/lib/db';
const SESSION_COOKIE_NAME = 'ct_session';
const SESSION_COOKIE_MAX_AGE = 60 * 60 * 24 * 7; // 7 days
export const SESSION_COOKIE_NAME = 'ct_session';
export const SESSION_COOKIE_MAX_AGE = 60 * 60 * 24 * 7; // 7 days
/**
* Determine whether the Secure flag should be set on cookies.
* Returns true when:
* - NODE_ENV is production, OR
* - the request came through an HTTPS proxy (x-forwarded-proto: https)
*/
export function isSecureRequest(request: Request): boolean {
if (process.env.NODE_ENV === 'production') return true;
const forwarded = request.headers.get('x-forwarded-proto');
return forwarded === 'https';
}
/**
* Returns the cookie options object for the session cookie.
*/
export function getSessionCookieOptions(secure: boolean) {
return {
httpOnly: true,
secure,
sameSite: 'lax' as const,
maxAge: SESSION_COOKIE_MAX_AGE,
path: '/',
};
}
export async function hashPassword(password: string): Promise<string> {
const salt = await bcrypt.genSalt(10);
@@ -18,15 +43,10 @@ export async function verifyPassword(
return bcrypt.compare(password, hash);
}
export async function createSession(userId: string): Promise<void> {
export async function createSession(userId: string, secure?: boolean): Promise<void> {
const cookieStore = await cookies();
cookieStore.set(SESSION_COOKIE_NAME, userId, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: SESSION_COOKIE_MAX_AGE,
path: '/',
});
const cookieSecure = secure ?? (process.env.NODE_ENV === 'production');
cookieStore.set(SESSION_COOKIE_NAME, userId, getSessionCookieOptions(cookieSecure));
}
const sessionUserSelect = Prisma.validator<Prisma.UserSelect>()({
+5 -2
View File
@@ -23,8 +23,11 @@ setInterval(() => {
// ─── Preset Limits ────────────────────────────────────────────────────
export const RATE_LIMITS = {
// Auth endpoints: 20 requests per minute (allows retries & multiple tabs)
auth: { limit: 20, windowMs: 60 * 1000 },
// Auth POST endpoints: 30 requests per minute (allows retries & multiple tabs)
auth: { limit: 30, windowMs: 60 * 1000 },
// Auth GET endpoint: 120 requests per minute (high frequency, low cost)
authGet: { limit: 120, windowMs: 60 * 1000 },
// Data read endpoints: 60 requests per minute (generous)
dataRead: { limit: 60, windowMs: 60 * 1000 },
+15 -5
View File
@@ -13,15 +13,25 @@ export function cn(...inputs: ClassValue[]) {
export function sanitizeHtml(html: string): string {
if (!html) return '';
return html
// Remove <script> tags and their content
.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
// Remove <script> tags and their content (handles multi-line, attributes, and unclosed tags)
.replace(/<script\b[\s\S]*?<\/script\s*>/gi, '')
// Remove unclosed <script> tags (no closing tag)
.replace(/<script\b[^>]*>[\s\S]*$/gi, '')
// Remove self-closing <script /> tags
.replace(/<script\b[^>]*\/>/gi, '')
// Remove on* event handler attributes (onclick, onload, onerror, etc.)
.replace(/\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '')
// Remove javascript: URLs
.replace(/href\s*=\s*(?:"javascript:[^"]*"|'javascript:[^']*')/gi, 'href="#"')
// Remove <iframe> tags
.replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi, '')
.replace(/<iframe\b[\s\S]*?<\/iframe\s*>/gi, '')
// Remove <object> and <embed> tags
.replace(/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi, '')
.replace(/<embed\b[^>]*>/gi, '');
.replace(/<object\b[\s\S]*?<\/object\s*>/gi, '')
.replace(/<embed\b[^>]*>/gi, '')
// Remove <noscript> tags (may contain script-like content)
.replace(/<noscript\b[\s\S]*?<\/noscript\s*>/gi, '')
// Remove <link> tags (could load external scripts)
.replace(/<link\b[^>]*>/gi, '')
// Remove <meta> tags with http-equiv="refresh" (could redirect)
.replace(/<meta\b[^>]*http-equiv\s*=\s*["']?refresh["']?[^>]*>/gi, '');
}