mirror of
https://github.com/bitbaum/botsmann.git
synced 2026-12-03 23:57:02 +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>
319 lines
8.4 KiB
TypeScript
319 lines
8.4 KiB
TypeScript
/**
|
|
* Centralized API Response Utilities
|
|
* @module lib/api/responses
|
|
*
|
|
* SSOT for API response patterns across all routes.
|
|
* Consolidates response creation, error handling, and Zod validation.
|
|
* Includes HTTP caching headers for performance optimization.
|
|
*/
|
|
|
|
import { NextResponse } from 'next/server';
|
|
import { ZodError, type ZodSchema } from 'zod';
|
|
|
|
// ============================================================================
|
|
// Cache Control
|
|
// ============================================================================
|
|
|
|
/**
|
|
* Cache control presets for different response types
|
|
*/
|
|
export const CACHE_CONTROL = {
|
|
/** No caching - for mutations, auth, sensitive data */
|
|
NONE: 'no-store, no-cache, must-revalidate',
|
|
|
|
/** Private short cache - user-specific data (1 minute) */
|
|
PRIVATE_SHORT: 'private, max-age=60',
|
|
|
|
/** Private medium cache - user data that changes less frequently (5 minutes) */
|
|
PRIVATE_MEDIUM: 'private, max-age=300',
|
|
|
|
/** Public short cache - public data (5 minutes) */
|
|
PUBLIC_SHORT: 'public, max-age=300',
|
|
|
|
/** Public medium cache - semi-static public data (1 hour) */
|
|
PUBLIC_MEDIUM: 'public, max-age=3600',
|
|
|
|
/** Immutable - truly static data (1 day, immutable) */
|
|
IMMUTABLE: 'public, max-age=86400, immutable',
|
|
} as const;
|
|
|
|
export type CacheControlPreset = keyof typeof CACHE_CONTROL;
|
|
|
|
/**
|
|
* Response options including cache control
|
|
*/
|
|
export interface ResponseOptions {
|
|
/** Cache control preset or custom header value */
|
|
cache?: CacheControlPreset | string;
|
|
/** Additional headers to include */
|
|
headers?: Record<string, string>;
|
|
}
|
|
|
|
/**
|
|
* Build headers object with cache control
|
|
*/
|
|
function buildHeaders(options?: ResponseOptions): HeadersInit {
|
|
const headers: Record<string, string> = {};
|
|
|
|
// Add cache control
|
|
if (options?.cache) {
|
|
const cacheValue =
|
|
options.cache in CACHE_CONTROL
|
|
? CACHE_CONTROL[options.cache as CacheControlPreset]
|
|
: options.cache;
|
|
headers['Cache-Control'] = cacheValue;
|
|
}
|
|
|
|
// Add any additional headers
|
|
if (options?.headers) {
|
|
Object.assign(headers, options.headers);
|
|
}
|
|
|
|
return headers;
|
|
}
|
|
|
|
/**
|
|
* Standard API response shape
|
|
*/
|
|
export interface ApiResponse<T = unknown> {
|
|
success: boolean;
|
|
data?: T;
|
|
message?: string;
|
|
error?: string;
|
|
code?: ErrorCode;
|
|
details?: ValidationError[];
|
|
/** Seconds until a RATE_LIMIT refusal lifts — what the auth forms count down. */
|
|
retryAfter?: number;
|
|
}
|
|
|
|
/**
|
|
* Error codes for categorizing API errors
|
|
*/
|
|
export type ErrorCode =
|
|
| 'VALIDATION_ERROR'
|
|
| 'UNAUTHORIZED'
|
|
| 'FORBIDDEN'
|
|
| 'NOT_FOUND'
|
|
| 'CONFLICT'
|
|
| 'DUPLICATE_SLUG'
|
|
| 'RATE_LIMIT'
|
|
| 'DATABASE_ERROR'
|
|
| 'SERVICE_UNAVAILABLE'
|
|
| 'LLM_UNAVAILABLE'
|
|
| 'INTERNAL_ERROR';
|
|
|
|
/**
|
|
* Validation error detail
|
|
*/
|
|
export interface ValidationError {
|
|
field: string;
|
|
message: string;
|
|
}
|
|
|
|
/**
|
|
* HTTP Status codes
|
|
*/
|
|
export const HTTP_STATUS = {
|
|
OK: 200,
|
|
CREATED: 201,
|
|
BAD_REQUEST: 400,
|
|
UNAUTHORIZED: 401,
|
|
FORBIDDEN: 403,
|
|
NOT_FOUND: 404,
|
|
CONFLICT: 409,
|
|
RATE_LIMIT: 429,
|
|
INTERNAL_ERROR: 500,
|
|
SERVICE_UNAVAILABLE: 503,
|
|
} as const;
|
|
|
|
type HttpStatusCode = (typeof HTTP_STATUS)[keyof typeof HTTP_STATUS];
|
|
|
|
/**
|
|
* Create a successful JSON response
|
|
*
|
|
* @param data - Response data
|
|
* @param options - Response options (cache, headers) or just a message string for backwards compatibility
|
|
* @param status - HTTP status code
|
|
*/
|
|
export function jsonSuccess<T>(
|
|
data: T,
|
|
options?: ResponseOptions | string,
|
|
status: HttpStatusCode = HTTP_STATUS.OK,
|
|
): NextResponse<ApiResponse<T>> {
|
|
const response: ApiResponse<T> = { success: true, data };
|
|
|
|
// Handle backwards compatibility: options can be a message string
|
|
let responseOptions: ResponseOptions | undefined;
|
|
if (typeof options === 'string') {
|
|
response.message = options;
|
|
} else {
|
|
responseOptions = options;
|
|
}
|
|
|
|
const headers = buildHeaders(responseOptions);
|
|
|
|
return NextResponse.json(response, {
|
|
status,
|
|
headers: Object.keys(headers).length > 0 ? headers : undefined,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Create a success response with just a message (no data)
|
|
*/
|
|
export function jsonMessage(
|
|
message: string,
|
|
status = HTTP_STATUS.OK,
|
|
options?: ResponseOptions,
|
|
): NextResponse<ApiResponse> {
|
|
const headers = buildHeaders(options);
|
|
return NextResponse.json(
|
|
{ success: true, message },
|
|
{
|
|
status,
|
|
headers: Object.keys(headers).length > 0 ? headers : undefined,
|
|
},
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Create an error JSON response
|
|
* Errors are never cached (Cache-Control: no-store)
|
|
*/
|
|
export function jsonError(
|
|
error: string,
|
|
code: ErrorCode = 'INTERNAL_ERROR',
|
|
status: HttpStatusCode = HTTP_STATUS.INTERNAL_ERROR,
|
|
details?: ValidationError[],
|
|
): NextResponse<ApiResponse> {
|
|
const response: ApiResponse = { success: false, error, code };
|
|
if (details?.length) response.details = details;
|
|
return NextResponse.json(response, {
|
|
status,
|
|
headers: { 'Cache-Control': CACHE_CONTROL.NONE },
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Create a validation error response
|
|
*/
|
|
export function jsonValidationError(
|
|
message: string,
|
|
details: ValidationError[],
|
|
): NextResponse<ApiResponse> {
|
|
return jsonError(message, 'VALIDATION_ERROR', HTTP_STATUS.BAD_REQUEST, details);
|
|
}
|
|
|
|
/**
|
|
* Create a rate limit error response
|
|
*/
|
|
export function jsonRateLimitError(
|
|
message = 'Rate limit exceeded. Please try again later.',
|
|
limit?: { retryAfter: number; headers?: Record<string, string> },
|
|
): NextResponse<ApiResponse> {
|
|
const response: ApiResponse = { success: false, error: message, code: 'RATE_LIMIT' };
|
|
if (limit) response.retryAfter = limit.retryAfter;
|
|
return NextResponse.json(response, {
|
|
status: HTTP_STATUS.RATE_LIMIT,
|
|
headers: { 'Cache-Control': CACHE_CONTROL.NONE, ...limit?.headers },
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Create an unauthorized error response
|
|
*/
|
|
export function jsonUnauthorized(message = 'Unauthorized'): NextResponse<ApiResponse> {
|
|
return jsonError(message, 'UNAUTHORIZED', HTTP_STATUS.UNAUTHORIZED);
|
|
}
|
|
|
|
/**
|
|
* Create a not found error response
|
|
*/
|
|
export function jsonNotFound(message = 'Not found'): NextResponse<ApiResponse> {
|
|
return jsonError(message, 'NOT_FOUND', HTTP_STATUS.NOT_FOUND);
|
|
}
|
|
|
|
/**
|
|
* Create a service unavailable error response
|
|
*/
|
|
export function jsonServiceUnavailable(
|
|
message = 'Service temporarily unavailable',
|
|
): NextResponse<ApiResponse> {
|
|
return jsonError(message, 'SERVICE_UNAVAILABLE', HTTP_STATUS.SERVICE_UNAVAILABLE);
|
|
}
|
|
|
|
/**
|
|
* No LLM provider could answer.
|
|
*
|
|
* This is a 503, not a 200 with an apology in the message body. A chat route
|
|
* that answers "I'm having a moment... could you try again?" with HTTP 200
|
|
* looks healthy to every uptime check while the product's core feature is
|
|
* dead -- which is exactly how a total outage went unnoticed.
|
|
*/
|
|
export function jsonLLMUnavailable(
|
|
message = 'The AI service is temporarily unavailable. Please try again shortly.',
|
|
): NextResponse<ApiResponse> {
|
|
return jsonError(message, 'LLM_UNAVAILABLE', HTTP_STATUS.SERVICE_UNAVAILABLE);
|
|
}
|
|
|
|
/**
|
|
* Convert ZodError to ValidationError array
|
|
*/
|
|
export function formatZodErrors(error: ZodError): ValidationError[] {
|
|
return error.issues.map((err) => ({
|
|
field: err.path.join('.'),
|
|
message: err.message,
|
|
}));
|
|
}
|
|
|
|
/**
|
|
* Validate request body with Zod schema
|
|
* Returns validated data or throws formatted validation error
|
|
*/
|
|
export async function validateBody<T>(
|
|
request: Request,
|
|
schema: ZodSchema<T>,
|
|
): Promise<{ data: T } | { error: NextResponse<ApiResponse> }> {
|
|
try {
|
|
const body = await request.json();
|
|
const result = schema.safeParse(body);
|
|
|
|
if (!result.success) {
|
|
return {
|
|
error: jsonValidationError('Validation failed', formatZodErrors(result.error)),
|
|
};
|
|
}
|
|
|
|
return { data: result.data };
|
|
} catch {
|
|
return {
|
|
error: jsonError('Invalid JSON body', 'VALIDATION_ERROR', HTTP_STATUS.BAD_REQUEST),
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Type guard to check if validation result has error
|
|
*/
|
|
export function hasValidationError<T>(
|
|
result: { data: T } | { error: NextResponse<ApiResponse> },
|
|
): result is { error: NextResponse<ApiResponse> } {
|
|
return 'error' in result;
|
|
}
|
|
|
|
/**
|
|
* Handle caught errors and return appropriate response
|
|
*/
|
|
export function handleError(error: unknown, fallbackMessage: string): NextResponse<ApiResponse> {
|
|
if (error instanceof ZodError) {
|
|
return jsonValidationError('Validation failed', formatZodErrors(error));
|
|
}
|
|
|
|
const errorWithCode = error as { code?: string };
|
|
if (errorWithCode.code === 'RATE_LIMIT') {
|
|
return jsonRateLimitError();
|
|
}
|
|
|
|
return jsonError(fallbackMessage, 'INTERNAL_ERROR', HTTP_STATUS.INTERNAL_ERROR);
|
|
}
|