mirror of
https://github.com/bitbaum/botsmann.git
synced 2026-12-04 11:38:13 +01:00
* refactor(rate-limit): one limiter from limitkit, keyed on the proxy's hop Two hand-rolled limiters lived side by side — lib/rate-limit.ts and lib/middleware/rate-limit.ts — each with its own window maths, its own header names and its own idea of who the caller is. Both are gone; the decision now comes from limitkit (fleet/SHARED.md), and what stays here is the one table of app budgets in lib/rate-limit.ts. A route names a bucket; it does not get to invent a number. The reason this matters beyond tidiness: both copies keyed the limit on the FIRST hop of X-Forwarded-For. That hop is written by the client, so any caller could mint a fresh budget per request by adding a header — the limiter looked like it worked and enforced nothing. limitkit counts from the right, i.e. the hop our own proxy wrote. A test now pins it: a forged first hop must not mint a fresh bucket. Also removed the Supabase check_rate_limit RPC path, which failed OPEN on every error — the limiter switched itself off whenever the database hiccupped. And 429s now carry Retry-After and X-RateLimit-* headers plus a retryAfter field, which is what the auth forms count down. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * refactor(icons): each icon body written once Icons.tsx repeated the same 24-box outline SVG wrapper for every icon — a 121-line self-clone. One `Outline` frame and one `icon(paths, ...)` builder replace it; an icon is now its path data and nothing else. Every export and every path string is byte-identical to before, so the rendered output does not move. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * refactor(create): one QuickCreateFlow behind /create and /personal The two pages held the same three-step flow twice — 192 cloned lines of state machine, header, progress indicator and step switch. They differ only in the copy around the template picker, so that is what the pages now pass in: /personal supplies its title block and its link out to the professionals, /create supplies neither. Both renders are unchanged, including that /personal's intro and outro only appear on the picker step. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * refactor(auth): one shell, one field, one submit button for the auth screens signup, signin, forgot-password and verify-email each carried their own copy of the page frame, the error line, the labelled input and the submit button — six clone pairs with signup in every one. They now share AuthShell / AuthAlert / AuthField / AuthSubmitButton, and the per-form error-plus-countdown state lives once in useAuthError. One real fix falls out of it: isRateLimitError compared the error code against 'RATE_LIMITED', but the API has always sent 'RATE_LIMIT'. The rate-limit countdown therefore never showed. It does now. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * chore(lint): console.info is not logging, and every disable says why `no-console` allowed `info`, so debug lines shipped as operator output: the blog route narrated every render to the server log at info level. Those lines now go through lib/logger (the single logger) at the level they actually are, and the allowance is gone — warn and error only. The 21 remaining console.log calls are all in scripts/test-db-connection.ts, where printing to the terminal is the point. The eslint-disable count drops 16 -> 13. Comments.tsx no longer needs one (useSyncExternalStore is the supported way to ask "are we on the client"), and lib/supabase.ts no longer needs its `any` — the SSG mock casts once at the return instead. The 13 that remain each name their reason: external avatar URLs that next/image would need a host allowlist for, and effects that seed state from an external store. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
386 lines
11 KiB
TypeScript
386 lines
11 KiB
TypeScript
'use client';
|
|
|
|
import { createContext, useContext, useEffect, useState, useCallback, type ReactNode } from 'react';
|
|
import type { User, Session } from '@supabase/supabase-js';
|
|
import { createClientComponentClient, isSupabaseConfigured } from '@/lib/supabase';
|
|
import { ROUTES } from '@/lib/routes';
|
|
import { useRateLimitCountdown } from '@/lib/hooks/useRateLimitCountdown';
|
|
import type { UserProfile } from '@/lib/schemas/auth';
|
|
|
|
// Lazy-loaded client - only created when Supabase is configured and first used
|
|
let _supabaseClient: ReturnType<typeof createClientComponentClient> | null = null;
|
|
|
|
function getSupabaseClient() {
|
|
if (!_supabaseClient && isSupabaseConfigured()) {
|
|
_supabaseClient = createClientComponentClient();
|
|
}
|
|
return _supabaseClient;
|
|
}
|
|
|
|
/**
|
|
* Auth error with optional code for specific handling (e.g., rate limiting)
|
|
*/
|
|
export interface AuthError extends Error {
|
|
code?: string;
|
|
retryAfter?: number;
|
|
}
|
|
|
|
/**
|
|
* Create an AuthError from an API response
|
|
*/
|
|
function createAuthError(message: string, code?: string, retryAfter?: number): AuthError {
|
|
const error = new Error(message) as AuthError;
|
|
error.code = code;
|
|
error.retryAfter = retryAfter;
|
|
return error;
|
|
}
|
|
|
|
interface AuthContextType {
|
|
user: User | null;
|
|
session: Session | null;
|
|
loading: boolean;
|
|
isEmailVerified: boolean;
|
|
displayName: string | null;
|
|
avatarUrl: string | null;
|
|
signIn: (email: string, password: string) => Promise<{ error: AuthError | null }>;
|
|
signUp: (email: string, password: string) => Promise<{ error: AuthError | null }>;
|
|
signOut: () => Promise<void>;
|
|
resetPassword: (email: string) => Promise<{ error: AuthError | null }>;
|
|
updatePassword: (newPassword: string) => Promise<{ error: AuthError | null }>;
|
|
resendVerificationEmail: () => Promise<{ error: AuthError | null }>;
|
|
updateProfile: (data: {
|
|
display_name?: string;
|
|
avatar_url?: string | null;
|
|
}) => Promise<{ error: AuthError | null; profile?: UserProfile }>;
|
|
isConfigured: boolean;
|
|
}
|
|
|
|
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
|
|
|
export function AuthProvider({ children }: { children: ReactNode }) {
|
|
const [user, setUser] = useState<User | null>(null);
|
|
const [session, setSession] = useState<Session | null>(null);
|
|
const [loading, setLoading] = useState(true);
|
|
|
|
const isConfigured = isSupabaseConfigured();
|
|
|
|
// Check if email is verified
|
|
// Supabase sets email_confirmed_at when email is verified
|
|
const isEmailVerified = Boolean(user?.email_confirmed_at);
|
|
|
|
// Get display name and avatar from user metadata
|
|
const displayName = (user?.user_metadata?.display_name as string) || null;
|
|
const avatarUrl = (user?.user_metadata?.avatar_url as string) || null;
|
|
|
|
useEffect(() => {
|
|
const client = getSupabaseClient();
|
|
|
|
// If Supabase is not configured, just set loading to false
|
|
if (!client) {
|
|
// eslint-disable-next-line react-hooks/set-state-in-effect -- initializes auth state from the external Supabase client
|
|
setLoading(false);
|
|
return;
|
|
}
|
|
|
|
// Get initial session
|
|
client.auth.getSession().then(({ data }: { data: { session: Session | null } }) => {
|
|
setSession(data.session);
|
|
setUser(data.session?.user ?? null);
|
|
setLoading(false);
|
|
});
|
|
|
|
// Listen for auth changes
|
|
const {
|
|
data: { subscription },
|
|
} = client.auth.onAuthStateChange((_event: string, newSession: Session | null) => {
|
|
setSession(newSession);
|
|
setUser(newSession?.user ?? null);
|
|
});
|
|
|
|
return () => subscription.unsubscribe();
|
|
}, []);
|
|
|
|
/**
|
|
* Sign in via rate-limited API route
|
|
*/
|
|
const signIn = async (email: string, password: string) => {
|
|
try {
|
|
const response = await fetch('/api/auth/signin', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ email, password }),
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (!response.ok) {
|
|
return {
|
|
error: createAuthError(data.error || 'Sign in failed', data.code, data.retryAfter),
|
|
};
|
|
}
|
|
|
|
// Refresh the session after successful API login
|
|
await getSupabaseClient()?.auth.getSession();
|
|
|
|
return { error: null };
|
|
} catch (err) {
|
|
return {
|
|
error: createAuthError('Network error. Please try again.'),
|
|
};
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Sign up via rate-limited API route
|
|
*/
|
|
const signUp = async (email: string, password: string) => {
|
|
try {
|
|
const response = await fetch('/api/auth/signup', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ email, password }),
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (!response.ok) {
|
|
return {
|
|
error: createAuthError(data.error || 'Sign up failed', data.code, data.retryAfter),
|
|
};
|
|
}
|
|
|
|
return { error: null };
|
|
} catch (err) {
|
|
return {
|
|
error: createAuthError('Network error. Please try again.'),
|
|
};
|
|
}
|
|
};
|
|
|
|
const signOut = async () => {
|
|
await getSupabaseClient()?.auth.signOut();
|
|
};
|
|
|
|
/**
|
|
* Request password reset via rate-limited API route
|
|
*/
|
|
const resetPassword = async (email: string) => {
|
|
try {
|
|
const response = await fetch('/api/auth/forgot-password', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ email }),
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (!response.ok) {
|
|
return {
|
|
error: createAuthError(
|
|
data.error || 'Failed to send reset email',
|
|
data.code,
|
|
data.retryAfter,
|
|
),
|
|
};
|
|
}
|
|
|
|
return { error: null };
|
|
} catch (err) {
|
|
return {
|
|
error: createAuthError('Network error. Please try again.'),
|
|
};
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Update password (called from reset-password page after email link)
|
|
* This still uses Supabase directly as the user already has a session
|
|
*/
|
|
const updatePassword = async (newPassword: string) => {
|
|
const { error } = await getSupabaseClient()?.auth.updateUser({
|
|
password: newPassword,
|
|
});
|
|
if (error) {
|
|
return { error: createAuthError(error.message) };
|
|
}
|
|
return { error: null };
|
|
};
|
|
|
|
/**
|
|
* Resend verification email via rate-limited API route
|
|
*/
|
|
const resendVerificationEmail = async () => {
|
|
try {
|
|
const response = await fetch('/api/auth/resend-verification', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (!response.ok) {
|
|
return {
|
|
error: createAuthError(
|
|
data.error || 'Failed to send verification email',
|
|
data.code,
|
|
data.retryAfter,
|
|
),
|
|
};
|
|
}
|
|
|
|
return { error: null };
|
|
} catch (err) {
|
|
return {
|
|
error: createAuthError('Network error. Please try again.'),
|
|
};
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Update user profile (display name, avatar URL)
|
|
*/
|
|
const updateProfile = useCallback(
|
|
async (data: { display_name?: string; avatar_url?: string | null }) => {
|
|
try {
|
|
const response = await fetch('/api/auth/profile', {
|
|
method: 'PUT',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(data),
|
|
});
|
|
|
|
const result = await response.json();
|
|
|
|
if (!response.ok) {
|
|
return {
|
|
error: createAuthError(
|
|
result.error || 'Failed to update profile',
|
|
result.code,
|
|
result.retryAfter,
|
|
),
|
|
};
|
|
}
|
|
|
|
// Refresh the session to get updated user metadata
|
|
await getSupabaseClient()?.auth.getSession();
|
|
|
|
return { error: null, profile: result.profile as UserProfile };
|
|
} catch (err) {
|
|
return {
|
|
error: createAuthError('Network error. Please try again.'),
|
|
};
|
|
}
|
|
},
|
|
[],
|
|
);
|
|
|
|
return (
|
|
<AuthContext.Provider
|
|
value={{
|
|
user,
|
|
session,
|
|
loading,
|
|
isEmailVerified,
|
|
displayName,
|
|
avatarUrl,
|
|
signIn,
|
|
signUp,
|
|
signOut,
|
|
resetPassword,
|
|
updatePassword,
|
|
resendVerificationEmail,
|
|
updateProfile,
|
|
isConfigured,
|
|
}}
|
|
>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useAuth() {
|
|
const context = useContext(AuthContext);
|
|
if (context === undefined) {
|
|
throw new Error('useAuth must be used within an AuthProvider');
|
|
}
|
|
return context;
|
|
}
|
|
|
|
/**
|
|
* Hook to require authentication
|
|
* Redirects to signin if not authenticated
|
|
*
|
|
* @param options.requireVerified - If true, also requires email to be verified
|
|
*/
|
|
export function useRequireAuth(options?: { requireVerified?: boolean }) {
|
|
const { user, loading, signOut, isEmailVerified, displayName, avatarUrl, updateProfile } =
|
|
useAuth();
|
|
const { requireVerified = false } = options ?? {};
|
|
|
|
useEffect(() => {
|
|
if (loading) return;
|
|
|
|
if (!user) {
|
|
window.location.href = ROUTES.AUTH.SIGNIN;
|
|
return;
|
|
}
|
|
|
|
// If verification is required but email is not verified, redirect to verify page
|
|
if (requireVerified && !isEmailVerified) {
|
|
window.location.href = ROUTES.AUTH.VERIFY_EMAIL;
|
|
}
|
|
}, [user, loading, isEmailVerified, requireVerified]);
|
|
|
|
return { user, loading, signOut, isEmailVerified, displayName, avatarUrl, updateProfile };
|
|
}
|
|
|
|
/**
|
|
* Check if an error is a rate limit error
|
|
*/
|
|
export function isRateLimitError(error: AuthError | null): boolean {
|
|
return error?.code === 'RATE_LIMIT';
|
|
}
|
|
|
|
/**
|
|
* Get retry after seconds from a rate limit error
|
|
*/
|
|
export function getRateLimitRetryAfter(error: AuthError | null): number {
|
|
return error?.retryAfter ?? 60;
|
|
}
|
|
|
|
/**
|
|
* Error state for an auth form: the message to show, and the countdown when
|
|
* the server refused for rate limiting.
|
|
*/
|
|
export function useAuthError() {
|
|
const [error, setError] = useState('');
|
|
const { rateLimitSeconds, setRateLimitSeconds, isRateLimited } = useRateLimitCountdown({
|
|
onExpire: () => setError(''),
|
|
});
|
|
|
|
const showAuthError = useCallback(
|
|
(err: AuthError) => {
|
|
if (isRateLimitError(err)) {
|
|
const retryAfter = getRateLimitRetryAfter(err);
|
|
setRateLimitSeconds(retryAfter);
|
|
setError(`Too many attempts. Please wait ${retryAfter} seconds.`);
|
|
} else {
|
|
setError(err.message);
|
|
}
|
|
},
|
|
[setRateLimitSeconds],
|
|
);
|
|
|
|
return { error, setError, showAuthError, rateLimitSeconds, isRateLimited };
|
|
}
|
|
|
|
/** Guests only: a signed-in user is sent on to their settings. */
|
|
export function useRedirectWhenSignedIn(user: User | null) {
|
|
// Runs in an effect (not during render) so the navigation side effect stays
|
|
// out of the render phase.
|
|
useEffect(() => {
|
|
if (user) {
|
|
window.location.href = ROUTES.SETTINGS;
|
|
}
|
|
}, [user]);
|
|
}
|