mirror of
https://github.com/bitbaum/botsmann.git
synced 2026-12-04 08:39:12 +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>
210 lines
7.1 KiB
TypeScript
210 lines
7.1 KiB
TypeScript
/**
|
|
* Supabase Client for Botsmann
|
|
*
|
|
* This talks to OUR Supabase, self-hosted on bitbaum at supabase.orangecat.ch —
|
|
* there is no supabase.com project and no dashboard to log into. Capacity is
|
|
* whatever the box has, not a hosted tier.
|
|
*
|
|
* One database backs several apps, so every client here is pinned to the
|
|
* `botsmann` schema via DB_SCHEMA. An unpinned client reads `public`, which is
|
|
* orangecat's, where our tables simply do not exist — that reads as a dead
|
|
* database rather than as a misconfiguration.
|
|
*
|
|
* Setup: docs/SUPABASE_SETUP.md
|
|
*/
|
|
|
|
import { createClient } from '@supabase/supabase-js';
|
|
import { createBrowserClient } from '@supabase/ssr';
|
|
import { getClientEnv, getServerEnv } from '@/lib/config/env';
|
|
import { DB_SCHEMA } from '@/lib/constants';
|
|
|
|
// Database row types
|
|
export interface ConsultationRow {
|
|
id: string;
|
|
name: string;
|
|
email: string;
|
|
message: string;
|
|
status: 'new' | 'contacted' | 'resolved';
|
|
created_at: string;
|
|
updated_at: string;
|
|
}
|
|
|
|
export interface UserSettingsRow {
|
|
id: string;
|
|
preferred_model: 'groq' | 'openrouter' | 'ollama';
|
|
groq_api_key: string | null;
|
|
openrouter_api_key: string | null;
|
|
ollama_url: string | null;
|
|
created_at: string;
|
|
}
|
|
|
|
export interface DocumentRow {
|
|
id: string;
|
|
user_id: string;
|
|
name: string;
|
|
type: string;
|
|
size_bytes: number | null;
|
|
storage_path: string;
|
|
status: 'pending' | 'processing' | 'ready' | 'error';
|
|
error_message: string | null;
|
|
chunk_count: number;
|
|
created_at: string;
|
|
updated_at: string;
|
|
}
|
|
|
|
export interface DocumentChunkRow {
|
|
id: string;
|
|
document_id: string;
|
|
user_id: string;
|
|
content: string;
|
|
embedding: number[] | null;
|
|
metadata: Record<string, unknown>;
|
|
created_at: string;
|
|
}
|
|
|
|
// Helper to check if Supabase is configured
|
|
export function isSupabaseConfigured(): boolean {
|
|
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
|
|
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
|
|
return Boolean(supabaseUrl && supabaseAnonKey);
|
|
}
|
|
|
|
function createAnonClient() {
|
|
const { NEXT_PUBLIC_SUPABASE_URL: supabaseUrl, NEXT_PUBLIC_SUPABASE_ANON_KEY: supabaseAnonKey } =
|
|
getClientEnv();
|
|
|
|
return createClient(supabaseUrl, supabaseAnonKey, { db: { schema: DB_SCHEMA } });
|
|
}
|
|
|
|
/**
|
|
* A client scoped to OUR schema.
|
|
*
|
|
* The bare `SupabaseClient` type hardcodes `'public'` as its schema, so
|
|
* annotating with it silently asserts we query orangecat's tables — and the
|
|
* compiler rejects the client we actually build. Deriving the type from the
|
|
* factory keeps the two in step, and survives supabase-js changing the order
|
|
* of its generic parameters.
|
|
*/
|
|
export type AppSupabaseClient = ReturnType<typeof createAnonClient>;
|
|
|
|
// Lazy-loaded Supabase client singleton
|
|
let _supabaseClient: AppSupabaseClient | null = null;
|
|
|
|
export function getSupabaseClient(): AppSupabaseClient {
|
|
if (_supabaseClient) {
|
|
return _supabaseClient;
|
|
}
|
|
|
|
_supabaseClient = createAnonClient();
|
|
return _supabaseClient;
|
|
}
|
|
|
|
// Convenience export that throws if not configured
|
|
// Use isSupabaseConfigured() first if you want to check
|
|
export const supabase = {
|
|
from: (table: string) => {
|
|
return getSupabaseClient().from(table);
|
|
},
|
|
auth: {
|
|
get user() {
|
|
return getSupabaseClient().auth.getUser();
|
|
},
|
|
signIn: (credentials: { email: string; password: string }) => {
|
|
return getSupabaseClient().auth.signInWithPassword(credentials);
|
|
},
|
|
signOut: () => {
|
|
return getSupabaseClient().auth.signOut();
|
|
},
|
|
},
|
|
storage: {
|
|
from: (bucket: string) => {
|
|
return getSupabaseClient().storage.from(bucket);
|
|
},
|
|
},
|
|
};
|
|
|
|
// Server-side client with service role (for admin operations)
|
|
export function getServiceClient() {
|
|
const { NEXT_PUBLIC_SUPABASE_URL: supabaseUrl } = getClientEnv();
|
|
const { SUPABASE_SERVICE_ROLE_KEY: serviceRoleKey } = getServerEnv();
|
|
|
|
return createClient(supabaseUrl, serviceRoleKey, {
|
|
db: { schema: DB_SCHEMA },
|
|
auth: {
|
|
autoRefreshToken: false,
|
|
persistSession: false,
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Create Supabase client for client components
|
|
* Replaces deprecated createClientComponentClient from @supabase/auth-helpers-nextjs
|
|
*
|
|
* During SSG/SSR without env vars, returns a mock client to prevent build errors.
|
|
* The real client is created on the client side when env vars are available.
|
|
*/
|
|
export function createClientComponentClient() {
|
|
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
|
|
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
|
|
|
|
// During SSG or when env vars are missing, return a mock client
|
|
// This prevents build failures; the real client is created client-side
|
|
if (!supabaseUrl || !supabaseAnonKey) {
|
|
// Only throw in browser where we actually need the client
|
|
if (typeof window !== 'undefined') {
|
|
throw new Error(
|
|
'Supabase environment variables not configured. ' +
|
|
'Set NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY.',
|
|
);
|
|
}
|
|
// Return mock during SSG - will be replaced on hydration. Cast through
|
|
// unknown at the return: typing the full client mock would mean importing
|
|
// internal Supabase types, and it only ever runs at build-time SSG.
|
|
const mockClient = {
|
|
auth: {
|
|
getSession: () => Promise.resolve({ data: { session: null }, error: null }),
|
|
getUser: () => Promise.resolve({ data: { user: null }, error: null }),
|
|
onAuthStateChange: (_event: string, _callback: (event: string, session: null) => void) => {
|
|
// Return immediately with no-op subscription
|
|
return {
|
|
data: {
|
|
subscription: {
|
|
unsubscribe: () => {
|
|
/* no-op */
|
|
},
|
|
},
|
|
},
|
|
};
|
|
},
|
|
signInWithPassword: () =>
|
|
Promise.resolve({ data: { user: null, session: null }, error: null }),
|
|
signUp: () => Promise.resolve({ data: { user: null, session: null }, error: null }),
|
|
signOut: () => Promise.resolve({ error: null }),
|
|
updateUser: () => Promise.resolve({ data: { user: null }, error: null }),
|
|
resend: () => Promise.resolve({ error: null }),
|
|
exchangeCodeForSession: () => Promise.resolve({ data: { session: null }, error: null }),
|
|
resetPasswordForEmail: () => Promise.resolve({ error: null }),
|
|
},
|
|
from: () => ({
|
|
select: () => ({ single: () => Promise.resolve({ data: null, error: null }) }),
|
|
insert: () => ({
|
|
select: () => ({ single: () => Promise.resolve({ data: null, error: null }) }),
|
|
}),
|
|
update: () => ({ eq: () => Promise.resolve({ data: null, error: null }) }),
|
|
delete: () => ({ eq: () => Promise.resolve({ data: null, error: null }) }),
|
|
}),
|
|
storage: {
|
|
from: () => ({
|
|
upload: () => Promise.resolve({ data: null, error: null }),
|
|
download: () => Promise.resolve({ data: null, error: null }),
|
|
remove: () => Promise.resolve({ data: null, error: null }),
|
|
}),
|
|
},
|
|
};
|
|
return mockClient as unknown as ReturnType<typeof createBrowserClient>;
|
|
}
|
|
|
|
return createBrowserClient(supabaseUrl, supabaseAnonKey, { db: { schema: DB_SCHEMA } });
|
|
}
|