Skip to content
Merged
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
6 changes: 5 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,8 @@ NEXT_PUBLIC_APP_URL="http://localhost:3000"

# Demo
DEMO_MODE="true"
CRON_SECRET="" # openssl rand -base64 32
CRON_SECRET="" # openssl rand -base64 32

# Rate limiting (Upstash Redis) — optional in local dev, required in production
UPSTASH_REDIS_REST_URL=""
UPSTASH_REDIS_REST_TOKEN=""
49 changes: 24 additions & 25 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,35 +47,34 @@ Avant tout commit : `pnpm lint && pnpm typecheck && pnpm build` doivent passer.
### Structure

```
src/
├── app/
│ ├── (auth)/ # login, verify
│ ├── (marketing)/ # landing publique
│ ├── (dashboard)/ # privé, protégé par middleware
│ ├── b/[slug]/ # board public d'un utilisateur
│ └── api/auth/ # NextAuth uniquement
├── components/
│ ├── ui/ # shadcn (généré, ne pas modifier sans raison)
│ ├── posts/ board/ shared/
├── lib/
│ ├── auth.ts # config NextAuth
│ ├── db.ts # singleton Prisma
│ ├── env.ts # @t3-oss/env-nextjs
│ ├── validators/ # schémas Zod partagés
│ └── utils.ts
├── server/
│ ├── actions/ # Server Actions ("use server"), mutations
│ └── queries/ # fonctions de lecture réutilisables (Server only)
├── types/
└── middleware.ts
app/
├── (auth)/ # login, verify
├── (marketing)/ # landing publique
├── (dashboard)/ # privé, protégé par middleware
├── b/[slug]/ # board public d'un utilisateur
└── api/auth/ # NextAuth uniquement
components/
├── ui/ # shadcn (généré, ne pas modifier sans raison)
├── posts/ board/ shared/
lib/
├── auth.ts # config NextAuth
├── db.ts # singleton Prisma
├── ratelimit.ts # Upstash Redis — limiteurs createPost et toggleVote
├── validators/ # schémas Zod partagés
└── utils.ts
server/
├── actions/ # Server Actions ("use server"), mutations
└── queries/ # fonctions de lecture réutilisables (Server only)
types/
middleware.ts
```

**Règle clé** : séparation stricte `server/actions` (écriture, `"use server"`) vs `server/queries` (lecture, appelables depuis Server Components). Ne pas mélanger.

### Flux de données

1. **Lecture** : Server Component → `server/queries/*` → Prisma. Pas de fetch côté client pour les données initiales.
2. **Écriture** : Client Component → Server Action (`server/actions/*`) → Zod parse → Prisma → `revalidatePath`/`revalidateTag`.
2. **Écriture** : Client Component → Server Action (`server/actions/*`) → Zod parse → auth → rate limit → Prisma → `revalidatePath`/`revalidateTag`.
3. **État** : pas de store global. `useState` + `useOptimistic` + Server Actions suffisent à cette échelle. Ne pas introduire Zustand/Redux/Jotai.

### Conventions Next.js
Expand Down Expand Up @@ -148,7 +147,7 @@ export async function createPost(input: z.infer<typeof schema>) {

### Validation

Tous les schémas Zod réutilisables vont dans `src/lib/validators/`. Un fichier par domaine (`posts.ts`, `boards.ts`). Les Server Actions importent depuis là, jamais de schéma inline pour des entités principales.
Tous les schémas Zod réutilisables vont dans `lib/validators/`. Un fichier par domaine (`posts.ts`, `boards.ts`). Les Server Actions importent depuis là, jamais de schéma inline pour des entités principales.

### Erreurs UI

Expand Down Expand Up @@ -193,7 +192,7 @@ Modèle : 1 User → 1 Board (relation 1:1 pour ce MVP). Chaque Post appartient
## Sécurité

- `@t3-oss/env-nextjs` pour valider toutes les variables d'env au boot.
- Rate limiting (Upstash Redis) sur : envoi de magic link, création de post, vote. Clé = userId si auth, sinon IP.
- Rate limiting (Upstash Redis) sur : création de post (`createPost`), vote (`toggleVote`). Clé = `userId` (auth requise dans les deux cas). Magic link : hors scope — géré séparément dans le flow Auth.js si besoin.
- CSRF géré nativement par Auth.js et Server Actions (Next.js).
- Jamais de secret dans le client. Toute variable côté client doit être préfixée `NEXT_PUBLIC_`.
- Ne pas logger d'emails ou de données utilisateur en production.
Expand Down Expand Up @@ -229,7 +228,7 @@ Si une demande tombe dans cette liste, le signaler et demander confirmation avan

## Bonus envisagés (à ne traiter qu'après MVP stable)

Par ordre de priorité : OG images dynamiques, dark mode, emails transactionnels (React Email + Resend), rate limiting Upstash, webhook sortant Slack, export CSV, recherche full-text Postgres, Storybook, e2e Playwright étendu.
Par ordre de priorité : OG images dynamiques, dark mode, emails transactionnels (React Email + Resend), webhook sortant Slack, export CSV, recherche full-text Postgres, Storybook, e2e Playwright étendu.

## Style de réponse attendu

Expand Down
28 changes: 28 additions & 0 deletions lib/ratelimit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";

export type Limiter = { limit: (key: string) => Promise<{ success: boolean }> };

// No-op when Upstash is not configured (local dev without .env.local credentials)
const noop: Limiter = { limit: async () => ({ success: true }) };

const redis =
process.env["UPSTASH_REDIS_REST_URL"] && process.env["UPSTASH_REDIS_REST_TOKEN"]
? Redis.fromEnv()
: null;

export const createPostLimiter: Limiter = redis
? new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(5, "10 m"),
prefix: "rl:createPost",
})
: noop;

export const toggleVoteLimiter: Limiter = redis
? new Ratelimit({
redis,
limiter: Ratelimit.fixedWindow(30, "1 m"),
prefix: "rl:toggleVote",
})
: noop;
45 changes: 43 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "feedbackflow",
"version": "1.0.7",
"version": "1.1.0",
"private": true,
"scripts": {
"dev": "next dev",
Expand All @@ -27,6 +27,8 @@
"@prisma/adapter-pg": "^7.8.0",
"@prisma/client": "^7.8.0",
"@types/pg": "^8.20.0",
"@upstash/ratelimit": "^2.0.8",
"@upstash/redis": "^1.38.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^1.16.0",
Expand Down
20 changes: 20 additions & 0 deletions server/actions/__tests__/posts-create.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ import { createPost } from "@/server/actions/posts";

vi.mock("@/auth", () => ({ auth: vi.fn() }));

const mockCreatePostLimit = vi.hoisted(() =>
vi.fn().mockResolvedValue({ success: true }),
);
vi.mock("@/lib/ratelimit", () => ({
createPostLimiter: { limit: mockCreatePostLimit },
}));

const mockedDb = db as unknown as ReturnType<typeof mockDeep<PrismaClient>>;

type AuthFn = () => Promise<Session | null>;
Expand Down Expand Up @@ -97,6 +104,19 @@ describe("createPost", () => {
expect(result).toMatchObject({ ok: false, error: "Invalid category" });
});

it("rejects when rate limit is exceeded", async () => {
mockCreatePostLimit.mockResolvedValueOnce({ success: false });
mockedDb.board.findUnique.mockResolvedValue({ id: "board-1", isPublic: true } as never);

const result = await createPost({
boardSlug: "demo",
title: "Valid title",
content: "Valid content with enough characters",
});
expect(result).toMatchObject({ ok: false, error: "Too many requests" });
expect(mockedDb.post.create).not.toHaveBeenCalled();
});

it("creates a post with valid input", async () => {
mockedDb.board.findUnique.mockResolvedValue({
id: "board-1",
Expand Down
16 changes: 16 additions & 0 deletions server/actions/__tests__/votes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ import { toggleVote } from "@/server/actions/votes";

vi.mock("@/auth", () => ({ auth: vi.fn() }));

const mockToggleVoteLimit = vi.hoisted(() =>
vi.fn().mockResolvedValue({ success: true }),
);
vi.mock("@/lib/ratelimit", () => ({
toggleVoteLimiter: { limit: mockToggleVoteLimit },
}));

const mockedDb = db as unknown as ReturnType<typeof mockDeep<PrismaClient>>;

type AuthFn = () => Promise<Session | null>;
Expand All @@ -33,6 +40,15 @@ describe("toggleVote", () => {
expect(result).toEqual({ ok: false, error: "Unauthorized" });
});

it("rejects when rate limit is exceeded", async () => {
mockToggleVoteLimit.mockResolvedValueOnce({ success: false });

const result = await toggleVote({ postId: "clxxxxxxxxxxxxxxxxxxxxxxx" });
expect(result).toMatchObject({ ok: false, error: "Too many requests" });
expect(mockedDb.vote.create).not.toHaveBeenCalled();
expect(mockedDb.vote.delete).not.toHaveBeenCalled();
});

it("creates a vote when none exists", async () => {
mockedDb.post.findUnique.mockResolvedValue({
id: "post-1",
Expand Down
4 changes: 4 additions & 0 deletions server/actions/posts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { revalidatePath } from "next/cache";
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { createPostLimiter } from "@/lib/ratelimit";
import {
changeStatusSchema,
createPostSchema,
Expand Down Expand Up @@ -31,6 +32,9 @@ export async function createPost(
const session = await auth();
if (!session?.user?.id) return { ok: false, error: "Unauthorized" };

const { success } = await createPostLimiter.limit(session.user.id);
if (!success) return { ok: false, error: "Too many requests" };

const board = await db.board.findUnique({
where: { slug: parsed.data.boardSlug },
select: { id: true, isPublic: true },
Expand Down
4 changes: 4 additions & 0 deletions server/actions/votes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { revalidatePath } from "next/cache";
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { toggleVoteLimiter } from "@/lib/ratelimit";
import { toggleVoteSchema, type ToggleVoteInput } from "@/lib/validators/votes";

type ActionResult<T = void> = { ok: true; data: T } | { ok: false; error: string };
Expand All @@ -16,6 +17,9 @@ export async function toggleVote(
const session = await auth();
if (!session?.user?.id) return { ok: false, error: "Unauthorized" };

const { success } = await toggleVoteLimiter.limit(session.user.id);
if (!success) return { ok: false, error: "Too many requests" };

const post = await db.post.findUnique({
where: { id: parsed.data.postId },
select: { id: true, board: { select: { slug: true, isPublic: true } } },
Expand Down
Loading