Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .claude/settings.local.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@
"Bash(vercel:*)",
"WebFetch(domain:console.groq.com)",
"Bash(ls:*)",
"Bash(sed:*)"
"Bash(sed:*)",
"Bash(echo $CLERK_JWT_ISSUER_DOMAIN)",
"Bash(curl:*)"
],
"deny": []
}
Expand Down
35 changes: 28 additions & 7 deletions convex/rateLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ interface RateLimitEntry {
resetTime: number;
}

// Simple in-memory rate limiting (for production, use Redis or similar)
// Simple in-memory rate limiting with bounded size (for production, use Redis or similar)
const MAX_RATE_LIMIT_ENTRIES = 10000; // Prevent unbounded growth
const rateLimitStore = new Map<string, RateLimitEntry>();

/**
Expand All @@ -38,6 +39,11 @@ export async function checkRateLimit(
throw new Error("Authentication required for rate limiting");
}

// More aggressive cleanup to prevent memory leaks
if (Math.random() < 0.05 || rateLimitStore.size > MAX_RATE_LIMIT_ENTRIES) {
cleanupExpiredRateLimits();
}

const config = RATE_LIMITS[operation];
const key = `${identity.subject}:${operation}`;
const now = Date.now();
Expand Down Expand Up @@ -95,20 +101,35 @@ export async function enforceRateLimit(
}

/**
* Clean up expired rate limit entries (should be called periodically)
* Clean up expired rate limit entries (called during rate limit checks)
*/
export function cleanupExpiredRateLimits(): void {
function cleanupExpiredRateLimits(): void {
const now = Date.now();
const keysToDelete: string[] = [];

for (const [key, entry] of rateLimitStore.entries()) {
if (now > entry.resetTime) {
rateLimitStore.delete(key);
keysToDelete.push(key);
}
}

// Delete expired entries
for (const key of keysToDelete) {
rateLimitStore.delete(key);
}

// If still too many entries, delete oldest ones (LRU-style)
if (rateLimitStore.size > MAX_RATE_LIMIT_ENTRIES) {
const entries = Array.from(rateLimitStore.entries());
entries.sort((a, b) => a[1].resetTime - b[1].resetTime);

const numToDelete = rateLimitStore.size - MAX_RATE_LIMIT_ENTRIES;
for (let i = 0; i < numToDelete; i++) {
rateLimitStore.delete(entries[i][0]);
}
}
}

// Clean up expired entries every 5 minutes
setInterval(cleanupExpiredRateLimits, 5 * 60 * 1000);

/**
* Get current rate limit status for a user and operation
*/
Expand Down
14 changes: 10 additions & 4 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,18 @@ import PrivacyPolicy from "./pages/PrivacyPolicy";
import Chat from "./pages/Chat";
import AuthGuard from "./components/AuthGuard";
import UserSync from "./components/UserSync";
import { AuthWrapper } from "./components/AuthWrapper";
import { AuthErrorBoundary } from "./components/AuthErrorBoundary";
import E2BDemo from "./pages/E2BDemo";

const queryClient = new QueryClient();

const App = () => (
<ConvexProviderWithClerk client={convex} useAuth={useAuth}>
<UserSync>
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<AuthErrorBoundary>
<UserSync>
<AuthWrapper>
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
<TooltipProvider>
<div className="min-h-screen bg-background">
Expand Down Expand Up @@ -56,8 +60,10 @@ const App = () => (
</div>
</TooltipProvider>
</QueryClientProvider>
</trpc.Provider>
</UserSync>
</trpc.Provider>
</AuthWrapper>
</UserSync>
</AuthErrorBoundary>
</ConvexProviderWithClerk>
);

Expand Down
73 changes: 73 additions & 0 deletions src/components/AuthErrorBoundary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import React, { Component, ErrorInfo, ReactNode } from 'react';

interface Props {
children: ReactNode;
fallback?: ReactNode;
}

interface State {
hasError: boolean;
error?: Error;
}

export class AuthErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false };
}

static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}

componentDidCatch(error: Error, errorInfo: ErrorInfo) {
// Log error without exposing sensitive auth details
console.error('Authentication error caught by boundary:', {
message: error.message,
stack: error.stack,
componentStack: errorInfo.componentStack
});
}

render() {
if (this.state.hasError) {
return this.props.fallback || (
<div className="flex items-center justify-center min-h-screen bg-gray-50">
<div className="text-center">
<div className="mb-4">
<div className="inline-flex items-center justify-center w-16 h-16 bg-red-100 rounded-full">
<svg
className="w-8 h-8 text-red-600"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"
/>
</svg>
</div>
</div>
<h2 className="text-xl font-semibold text-gray-900 mb-2">
Authentication Error
</h2>
<p className="text-gray-600 mb-4">
There was a problem with authentication. Please refresh the page to try again.
</p>
<button
onClick={() => window.location.reload()}
className="inline-flex items-center px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
>
Refresh Page
</button>
</div>
</div>
);
}

return this.props.children;
}
}
84 changes: 84 additions & 0 deletions src/components/AuthProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import React, { createContext, useContext, useEffect, useState, useCallback } from 'react';
import { useAuth as useClerkAuth, useUser } from '@clerk/clerk-react';
import type { UserResource } from '@clerk/types';
import { useAuthToken } from '@/lib/auth-token';

interface AuthContextType {
isAuthenticated: boolean;
isLoading: boolean;
user: UserResource | null | undefined;
token: string | null;
refreshAuth: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const { isSignedIn, isLoaded } = useClerkAuth();
const { user } = useUser();
const { getValidToken, clearStoredToken } = useAuthToken();
const [token, setToken] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);

const refreshAuth = useCallback(async () => {
try {
if (isSignedIn && isLoaded) {
const newToken = await getValidToken();
setToken(newToken);
} else {
setToken(null);
clearStoredToken();
}
} catch (error) {
console.error('Failed to refresh auth token');
setToken(null);
clearStoredToken();
}
}, [isSignedIn, isLoaded, getValidToken, clearStoredToken]);

// Main auth effect - handles initial load and auth state changes
useEffect(() => {
const handleAuth = async () => {
if (!isLoaded) {
// Still loading Clerk, keep loading state
return;
}

setIsLoading(true);
await refreshAuth();
setIsLoading(false);
};

handleAuth();
}, [isSignedIn, isLoaded, user?.id, refreshAuth]);

// Periodic token refresh to prevent expiration
useEffect(() => {
if (isSignedIn && isLoaded) {
const interval = setInterval(refreshAuth, 4 * 60 * 1000); // Every 4 minutes
return () => clearInterval(interval);
}
}, [isSignedIn, isLoaded, refreshAuth]);

const value: AuthContextType = {
isAuthenticated: isLoaded && isSignedIn && !!token,
isLoading: isLoading || !isLoaded,
user,
token,
refreshAuth,
};

return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
);
};

export const useAuthContext = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuthContext must be used within an AuthProvider');
}
return context;
};
47 changes: 47 additions & 0 deletions src/components/AuthWrapper.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import React, { useEffect } from 'react';
import { useConvexAuth } from 'convex/react';
import { useAuth as useClerkAuth } from '@clerk/clerk-react';
import { useAuthToken } from '@/lib/auth-token';

interface AuthWrapperProps {
children: React.ReactNode;
}

export const AuthWrapper: React.FC<AuthWrapperProps> = ({ children }) => {
const convexAuth = useConvexAuth();
const clerkAuth = useClerkAuth();
const { getValidToken, clearStoredToken } = useAuthToken();

useEffect(() => {
// Handle authentication recovery on page load/refresh
const handleAuthRecovery = async () => {
// If Convex shows not authenticated but Clerk is signed in
if (!convexAuth.isAuthenticated && !convexAuth.isLoading && clerkAuth.isSignedIn && clerkAuth.isLoaded) {
try {
// Get a fresh token to sync with Convex
const freshToken = await getValidToken();
if (freshToken) {
// Let Convex naturally re-authenticate without forcing reload
console.log('Auth token refreshed for Convex sync');
}
} catch (error) {
console.error('Auth recovery failed');
clearStoredToken();
}
}
};

// Run recovery after initial auth check
const timeout = setTimeout(handleAuthRecovery, 1000);
return () => clearTimeout(timeout);
}, [convexAuth.isAuthenticated, convexAuth.isLoading, clerkAuth.isSignedIn, clerkAuth.isLoaded, getValidToken, clearStoredToken]);

// Handle sign out cleanup
useEffect(() => {
if (!clerkAuth.isSignedIn && clerkAuth.isLoaded) {
clearStoredToken();
}
}, [clerkAuth.isSignedIn, clerkAuth.isLoaded, clearStoredToken]);

return <>{children}</>;
};
3 changes: 2 additions & 1 deletion src/components/UserSync.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { useEffect } from 'react';
import { useConvexAuth } from 'convex/react';
import { useUser } from '@clerk/clerk-react';
import { useUser, useAuth as useClerkAuth } from '@clerk/clerk-react';
import { useMutation } from 'convex/react';
import { api } from '../../convex/_generated/api';

export default function UserSync({ children }: { children: React.ReactNode }) {
const { isAuthenticated, isLoading } = useConvexAuth();
const { user: clerkUser } = useUser();
const { isSignedIn } = useClerkAuth();
const upsertUser = useMutation(api.users.upsertUser);

useEffect(() => {
Expand Down
42 changes: 42 additions & 0 deletions src/lib/auth-provider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { useAuth as useClerkAuth } from '@clerk/clerk-react';
import { useConvexAuth } from 'convex/react';
import { useAuthToken } from './auth-token';

// Enhanced auth hook that combines Clerk and Convex auth with secure token management
export const useAuthWithTokens = () => {
const clerkAuth = useClerkAuth();
const convexAuth = useConvexAuth();
const { getValidToken, clearStoredToken } = useAuthToken();

// Enhanced getToken that uses secure memory-based storage
const getTokenSecure = async () => {
try {
// Get token using the secure token manager
if (clerkAuth.isSignedIn && clerkAuth.isLoaded) {
return await getValidToken();
}

return null;
} catch (error) {
console.error('Error getting auth token');
clearStoredToken();
return null;
}
};

// Clear tokens on sign out
const signOut = async () => {
clearStoredToken();
if (clerkAuth.signOut) {
await clerkAuth.signOut();
}
};

return {
...clerkAuth,
...convexAuth,
getToken: getTokenSecure,
signOut,
isFullyAuthenticated: convexAuth.isAuthenticated && clerkAuth.isSignedIn,
};
};
Loading