14 Commits
Author SHA1 Message Date
CatoandClaude Opus 5 376b94f89d refactor: one rate limiter, one auth shell, one create flow, one icon frame (#198)
* 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>
2026-09-15 01:24:12 -07:00
9284c00dc7 fix(api): two LLM endpoints spent money with no rate limit (#139)
app/api/demo/chat is public and unauthenticated, and
app/api/custom-bots/[id]/chat lets anonymous callers chat with public
bots billed to the bot OWNER's API key. Neither had a limit. Nothing
failed, because nothing was checking.

Both are closed. The custom-bot limit is scoped per bot id so one hot
bot cannot drain another's budget.

The reason they drifted is that each route hand-rolled the same block:
read the IP, call checkRateLimit with inline magic numbers, return a
429 written slightly differently each time. So the budgets now live in
one place (RATE_LIMITS) behind one helper (enforceRateLimit), and the
seven existing copies were migrated onto it -- removing three different
429 response shapes and a hand-rolled copy of getClientIp.

Never-twice: tests/__tests__/api/rate-limit-coverage.test.ts reads every
route file and fails if one imports the LLM client without enforcing a
limit, or calls checkRateLimit directly with its own numbers. Verified
by mutation -- removing a limit makes it fail and name the file.

verify: format, lint, typecheck, 240 tests, build -- all green.


Claude-Session: https://claude.ai/code/session_01HVwg8DKHQktxJuHeLM3xpG

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-28 08:09:06 +02:00
GandClaude Opus 4.8 26b042cd86 chore(infra): remove Vercel references — self-hosted now (#120)
Botsmann now runs self-hosted on the Hetzner box "bitbaum" behind Caddy
(botsmann.orangecat.ch); Vercel is fully decommissioned.

- CI: rename the "Deploy to Vercel" workflow to a vendor-neutral CI workflow
  (build/lint/test only). Actual deploy runs from .husky/pre-push → Hetzner
  deploy script. Remove vercel.json and the Vercel-only deploy-monitor.sh.
- Docs: rewrite current-setup deploy/hosting text in .claude/CLAUDE.md,
  README badge, docs/COMMANDS.md and docs/SHARED_CONTEXT.md to the self-hosted
  box. Repoint the dead botsmann.vercel.app URL → botsmann.orangecat.ch.
- Code: neutralize "(Vercel)" route-segment comments; reword the warmup cron
  comment; update the demo page tech-stack line to self-hosted.
- Keep: secret-scan guardrail (VERCEL_OIDC_TOKEN) and `env -u VERCEL` in the
  husky hooks, the educational hosting-comparison page, historical docs/archive,
  and executive-docs business/finance planning material (see PR body).

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-28 09:23:49 +02:00
g-butandClaude Opus 4.6 318d0f7a65 refactor(chat): extract shared document search into lib/chat/search.ts
Create searchUserDocuments() that encapsulates the common pattern:
embed query → match_documents RPC → filter → build context + sources.
Used by both chat/route.ts and professional-chat/route.ts, removing
~50 duplicated lines across the two routes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 10:04:16 +01:00
g-butandClaude Opus 4.6 5c046fd1dc refactor(logging): replace console calls with structured logger
Create lib/logger.ts — lightweight wrapper that outputs plain text in dev
and structured JSON in production. Replace 117 console.log/error/warn
calls across 31 files (27 API routes + 4 lib files) with logger.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:55:28 +01:00
g-butandClaude Opus 4.6 82e4623105 feat(rate-limit): replace in-memory rate limiting with Supabase-based
In-memory rate limiting (LRU cache + Map) doesn't work correctly in
serverless — each function instance has its own memory. Replace with
a Supabase PostgreSQL function that atomically checks and increments
per key, shared across all instances.

- Add rate_limits table + check_rate_limit SQL function (migration 010)
- Rewrite lib/rate-limit.ts to call Supabase RPC instead of LRU cache
- Simplify lib/middleware/rate-limit.ts to wrap the new checkRateLimit
- Update all 7 routes using the old LRU-based limiter
- Remove lru-cache and @types/lru-cache dependencies
- Auth routes (5) unchanged — they already use the middleware wrapper

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:15 +01:00
g-butandClaude Opus 4.6 372fe46261 refactor(chat): extract shared utilities from 3 chat API routes
Create lib/chat/ module with shared utilities:
- embedding.ts: generateEmbeddingWithTimeout (embedding + timeout guard)
- settings.ts: getUserLLMSettings (provider/apiKey/ollamaUrl lookup)
- context.ts: truncateChunks + joinContext (context building)
- llm-errors.ts: handleLLMError (API key fallback, Ollama, AI unavailable)
- parse.ts: parseResponseWithSuggestions (extract >>> suggestions)

Update all 3 chat routes to use shared utilities, removing ~220 lines of
duplicated code. Also fix module-scope getServerEnv() call in llm-client
that caused SSG build failure.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:23:14 +01:00
g-butandClaude Opus 4.5 1c7abeebac docs(claude): add global standards reference and update date
- Add @~/.claude/CLAUDE.md import for global engineering standards
- Update Last Updated date to 2026-01-23

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 15:22:36 +01:00
g-butandClaude Sonnet 4.5 9aa417e273 refactor: clean up API routes and components, add shared utilities
Refactored multiple API routes and components to improve code organization and reduce duplication:
- Simplified API route implementations across chat, documents, consultations, and other endpoints
- Reorganized navigation components for better maintainability
- Added shared utility functions and hooks
- Created reusable Avatar and Logo components
- Added validation schemas and API utilities
- Improved type definitions and constants management

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-16 11:04:19 +01:00
g-but e648f4cca7 feat: add extended timeouts for embedding routes and improve error handling
- Add maxDuration config for chat, search, and process routes
- Add timeout wrapper for embedding generation with clear error message
- Add detailed logging throughout chat API for debugging
2026-01-15 04:20:51 +01:00
g-but 676ed7ef3e Add detailed logging to chat API for debugging 503 errors 2026-01-15 04:12:24 +01:00
g-butandClaude Opus 4.5 f392e4b551 fix(chat): user-friendly error messages
- Remove technical API key messages from error responses
- Show "AI service temporarily unavailable" instead of asking users to get API keys
- Simplify context-only fallback message
- Better error logging for debugging

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-15 01:23:38 +01:00
g-butandClaude Opus 4.5 7aadd04f29 feat(chat): add context-only fallback when LLM API key is missing
When no Groq/OpenAI API key is configured, the chat now returns the
retrieved document context instead of just an error. This allows users
to see that the RAG retrieval is working even before configuring an
LLM provider.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-14 13:08:19 +01:00
g-butandClaude Opus 4.5 403c9bf5a7 Add Phase 3: Document upload and RAG chat
- Add Transformers.js for local embeddings generation
- Create document upload API with Supabase Storage
- Create document processing pipeline (parse, chunk, embed)
- Create semantic search API using pgvector
- Create RAG chat API combining search + LLM
- Add documents page UI with upload, process, and chat
- Add database migration for document status columns
- Configure Next.js to externalize ONNX packages

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-14 12:39:43 +01:00