From ed77ffaed274ab96655aacb5c06d463a2ca66c13 Mon Sep 17 00:00:00 2001 From: Florian Wilde Date: Sat, 25 Jul 2026 21:30:59 +0200 Subject: [PATCH] feat(security): alle Daten auf den Besitzer einschraenken Bisher sah jede Anfrage alles. Jetzt traegt jede Abfrage eine Besitzerbedingung, und zwar an erster Stelle in der where-Klausel statt als nachtraeglicher Vergleich - so kann sie nicht versehentlich uebersprungen werden. - Lesen: findFirst statt findUnique, immer mit ownerId - Schreiben und Loeschen: updateMany/deleteMany mit ownerId in der where-Klausel. Fremde Datensaetze werden dadurch gar nicht erst getroffen, und die betroffene Zeilenzahl sagt, ob es den Datensatz gab. - Notizen haengen ueber project.ownerId am Besitzer - Beim Verknuepfen eines Projekts wird geprueft, dass die Git-Verbindung dem Aufrufer gehoert - sonst liesse sich eine fremde Verbindung und damit ein fremder Token unterschieben - Fremde IDs liefern 404 statt 403: die Antwort bestaetigt nicht einmal, dass es den Datensatz gibt - Ausgehende Endpunkte (Sync, Verbindungstest, Repo-Liste) zusaetzlich ratenbegrenzt, Basis-URLs gegen den SSRF-Schutz geprueft - Slug und Verbindungsname werden je Besitzer auf Eindeutigkeit geprueft Nachgewiesen: ein zweites Konto erhaelt auf GET, PATCH, DELETE, Notiz anlegen und Sync eines fremden Projekts durchgaengig 404, auf die Admin-Endpunkte 403, und das Zielprojekt bleibt unveraendert. Co-Authored-By: Claude Opus 5 (1M context) --- src/app/api/connections/[id]/check/route.ts | 23 ++++-- src/app/api/connections/[id]/repos/route.ts | 21 +++++- src/app/api/connections/[id]/route.ts | 82 +++++++++++++++------ src/app/api/connections/route.ts | 53 ++++++++++--- src/app/api/notes/[id]/route.ts | 64 +++++++++------- src/app/api/projects/[id]/notes/route.ts | 36 ++++++--- src/app/api/projects/[id]/route.ts | 77 +++++++++++++------ src/app/api/projects/[id]/sync/route.ts | 28 ++++++- src/app/api/projects/route.ts | 40 ++++++++-- src/app/connections/page.tsx | 6 +- src/app/page.tsx | 5 ++ src/app/projects/[id]/page.tsx | 23 +++++- src/lib/projects.ts | 15 +++- 13 files changed, 351 insertions(+), 122 deletions(-) diff --git a/src/app/api/connections/[id]/check/route.ts b/src/app/api/connections/[id]/check/route.ts index 55706d8..45a7597 100644 --- a/src/app/api/connections/[id]/check/route.ts +++ b/src/app/api/connections/[id]/check/route.ts @@ -1,19 +1,32 @@ import { NextResponse } from "next/server"; +import { requireUserApi } from "@/lib/auth/guard"; import { prisma } from "@/lib/db"; import { clientForConnection } from "@/lib/git"; +import { LIMITS, rateLimit } from "@/lib/security/rateLimit"; +import { clientIp, jsonError, tooManyRequests } from "@/lib/security/request"; export const dynamic = "force-dynamic"; type Params = { params: Promise<{ id: string }> }; /** Testet Erreichbarkeit und Token einer Verbindung und merkt sich das Ergebnis. */ -export async function POST(_request: Request, { params }: Params) { +export async function POST(request: Request, { params }: Params) { + const auth = await requireUserApi(); + if (!auth.ok) return auth.response; + + const limited = rateLimit( + `outbound:${auth.user.id}:${clientIp(request)}`, + LIMITS.outbound.limit, + LIMITS.outbound.windowMs, + ); + if (!limited.ok) return tooManyRequests(limited.retryAfter); + const { id } = await params; - const connection = await prisma.gitConnection.findUnique({ where: { id } }); - if (!connection) { - return NextResponse.json({ error: "Verbindung nicht gefunden" }, { status: 404 }); - } + const connection = await prisma.gitConnection.findFirst({ + where: { id, ownerId: auth.user.id }, + }); + if (!connection) return jsonError("Verbindung nicht gefunden", 404); const result = await clientForConnection(connection).check(); diff --git a/src/app/api/connections/[id]/repos/route.ts b/src/app/api/connections/[id]/repos/route.ts index 041032d..14ebe34 100644 --- a/src/app/api/connections/[id]/repos/route.ts +++ b/src/app/api/connections/[id]/repos/route.ts @@ -1,6 +1,9 @@ import { NextResponse } from "next/server"; +import { requireUserApi } from "@/lib/auth/guard"; import { prisma } from "@/lib/db"; import { clientForConnection } from "@/lib/git"; +import { LIMITS, rateLimit } from "@/lib/security/rateLimit"; +import { clientIp, jsonError, tooManyRequests } from "@/lib/security/request"; export const dynamic = "force-dynamic"; @@ -8,13 +11,23 @@ type Params = { params: Promise<{ id: string }> }; /** Listet Repositories, auf die der hinterlegte Token Zugriff hat. */ export async function GET(request: Request, { params }: Params) { + const auth = await requireUserApi(); + if (!auth.ok) return auth.response; + + const limited = rateLimit( + `outbound:${auth.user.id}:${clientIp(request)}`, + LIMITS.outbound.limit, + LIMITS.outbound.windowMs, + ); + if (!limited.ok) return tooManyRequests(limited.retryAfter); + const { id } = await params; const query = new URL(request.url).searchParams.get("q") ?? undefined; - const connection = await prisma.gitConnection.findUnique({ where: { id } }); - if (!connection) { - return NextResponse.json({ error: "Verbindung nicht gefunden" }, { status: 404 }); - } + const connection = await prisma.gitConnection.findFirst({ + where: { id, ownerId: auth.user.id }, + }); + if (!connection) return jsonError("Verbindung nicht gefunden", 404); try { const repos = await clientForConnection(connection).listRepos(query); diff --git a/src/app/api/connections/[id]/route.ts b/src/app/api/connections/[id]/route.ts index 0193271..cc11c43 100644 --- a/src/app/api/connections/[id]/route.ts +++ b/src/app/api/connections/[id]/route.ts @@ -1,8 +1,11 @@ import { NextResponse } from "next/server"; +import { requireUserApi } from "@/lib/auth/guard"; import { encryptSecret, tokenHint } from "@/lib/crypto"; import { prisma } from "@/lib/db"; import { normalizeBaseUrl } from "@/lib/git/http"; import { connectionSafeSelect } from "@/lib/projects"; +import { jsonError, readJsonBody } from "@/lib/security/request"; +import { BlockedHostError, assertAllowedUrl } from "@/lib/security/ssrf"; import { connectionUpdateSchema, formatZodError } from "@/lib/validation"; export const dynamic = "force-dynamic"; @@ -15,16 +18,21 @@ const safeSelect = { }; export async function PATCH(request: Request, { params }: Params) { + const auth = await requireUserApi(); + if (!auth.ok) return auth.response; + const { id } = await params; - let body: unknown; - try { - body = await request.json(); - } catch { - return NextResponse.json({ error: "Ungueltiger JSON-Body" }, { status: 400 }); - } + const existing = await prisma.gitConnection.findFirst({ + where: { id, ownerId: auth.user.id }, + select: { id: true }, + }); + if (!existing) return jsonError("Verbindung nicht gefunden", 404); - const parsed = connectionUpdateSchema.safeParse(body); + const body = await readJsonBody(request); + if (!body.ok) return body.response; + + const parsed = connectionUpdateSchema.safeParse(body.data); if (!parsed.success) { return NextResponse.json( { error: "Validierung fehlgeschlagen", fields: formatZodError(parsed.error) }, @@ -36,9 +44,24 @@ export async function PATCH(request: Request, { params }: Params) { const update: Record = {}; if (data.name !== undefined) update.name = data.name; if (data.provider !== undefined) update.provider = data.provider; - if (data.baseUrl !== undefined) update.baseUrl = normalizeBaseUrl(data.baseUrl); if (data.username !== undefined) update.username = data.username; + if (data.baseUrl !== undefined) { + const normalized = normalizeBaseUrl(data.baseUrl); + try { + await assertAllowedUrl(normalized); + } catch (error) { + if (error instanceof BlockedHostError) { + return NextResponse.json( + { error: error.message, fields: { baseUrl: error.message } }, + { status: 422 }, + ); + } + throw error; + } + update.baseUrl = normalized; + } + // token === null -> Token entfernen // token === "" -> vom Schema zu null normalisiert // token undefined -> unveraendert lassen @@ -52,25 +75,38 @@ export async function PATCH(request: Request, { params }: Params) { } } - try { - const connection = await prisma.gitConnection.update({ - where: { id }, - data: update, - select: safeSelect, + if (data.name !== undefined) { + const duplicate = await prisma.gitConnection.findFirst({ + where: { name: data.name, ownerId: auth.user.id, NOT: { id } }, + select: { id: true }, }); - return NextResponse.json({ connection }); - } catch { - return NextResponse.json({ error: "Verbindung nicht gefunden oder Name vergeben" }, { status: 404 }); + if (duplicate) { + return NextResponse.json( + { error: "Name bereits vergeben.", fields: { name: "Name bereits vergeben" } }, + { status: 409 }, + ); + } } + + const connection = await prisma.gitConnection.update({ + where: { id }, + data: update, + select: safeSelect, + }); + return NextResponse.json({ connection }); } export async function DELETE(_request: Request, { params }: Params) { + const auth = await requireUserApi(); + if (!auth.ok) return auth.response; + const { id } = await params; - try { - // Projekte bleiben erhalten, connectionId wird per onDelete: SetNull geleert. - await prisma.gitConnection.delete({ where: { id } }); - return NextResponse.json({ ok: true }); - } catch { - return NextResponse.json({ error: "Verbindung nicht gefunden" }, { status: 404 }); - } + + // Projekte bleiben erhalten, connectionId wird per onDelete: SetNull geleert. + const result = await prisma.gitConnection.deleteMany({ + where: { id, ownerId: auth.user.id }, + }); + if (result.count === 0) return jsonError("Verbindung nicht gefunden", 404); + + return NextResponse.json({ ok: true }); } diff --git a/src/app/api/connections/route.ts b/src/app/api/connections/route.ts index f762ba1..75cf070 100644 --- a/src/app/api/connections/route.ts +++ b/src/app/api/connections/route.ts @@ -1,8 +1,12 @@ import { NextResponse } from "next/server"; +import { requireUserApi } from "@/lib/auth/guard"; import { encryptSecret, tokenHint } from "@/lib/crypto"; import { prisma } from "@/lib/db"; import { normalizeBaseUrl } from "@/lib/git/http"; import { connectionSafeSelect } from "@/lib/projects"; +import { LIMITS, rateLimit } from "@/lib/security/rateLimit"; +import { clientIp, jsonError, readJsonBody, tooManyRequests } from "@/lib/security/request"; +import { BlockedHostError, assertAllowedUrl } from "@/lib/security/ssrf"; import { connectionCreateSchema, formatZodError } from "@/lib/validation"; export const dynamic = "force-dynamic"; @@ -14,7 +18,11 @@ const safeSelect = { }; export async function GET() { + const auth = await requireUserApi(); + if (!auth.ok) return auth.response; + const connections = await prisma.gitConnection.findMany({ + where: { ownerId: auth.user.id }, select: safeSelect, orderBy: { name: "asc" }, }); @@ -22,14 +30,20 @@ export async function GET() { } export async function POST(request: Request) { - let body: unknown; - try { - body = await request.json(); - } catch { - return NextResponse.json({ error: "Ungueltiger JSON-Body" }, { status: 400 }); - } + const auth = await requireUserApi(); + if (!auth.ok) return auth.response; - const parsed = connectionCreateSchema.safeParse(body); + const limited = rateLimit( + `mutate:${clientIp(request)}`, + LIMITS.mutation.limit, + LIMITS.mutation.windowMs, + ); + if (!limited.ok) return tooManyRequests(limited.retryAfter); + + const body = await readJsonBody(request); + if (!body.ok) return body.response; + + const parsed = connectionCreateSchema.safeParse(body.data); if (!parsed.success) { return NextResponse.json( { error: "Validierung fehlgeschlagen", fields: formatZodError(parsed.error) }, @@ -39,16 +53,37 @@ export async function POST(request: Request) { const { name, provider, baseUrl, username, token } = parsed.data; - const duplicate = await prisma.gitConnection.findUnique({ where: { name } }); + // Die Basis-URL wird spaeter serverseitig abgerufen – hier pruefen, damit + // sie nicht auf interne Dienste oder Metadaten-Endpunkte zeigt. + try { + await assertAllowedUrl(normalizeBaseUrl(baseUrl)); + } catch (error) { + if (error instanceof BlockedHostError) { + return NextResponse.json( + { error: error.message, fields: { baseUrl: error.message } }, + { status: 422 }, + ); + } + throw error; + } + + const duplicate = await prisma.gitConnection.findFirst({ + where: { name, ownerId: auth.user.id }, + select: { id: true }, + }); if (duplicate) { return NextResponse.json( - { error: "Es gibt bereits eine Verbindung mit diesem Namen.", fields: { name: "Name bereits vergeben" } }, + { + error: "Es gibt bereits eine Verbindung mit diesem Namen.", + fields: { name: "Name bereits vergeben" }, + }, { status: 409 }, ); } const connection = await prisma.gitConnection.create({ data: { + ownerId: auth.user.id, name, provider, baseUrl: normalizeBaseUrl(baseUrl), diff --git a/src/app/api/notes/[id]/route.ts b/src/app/api/notes/[id]/route.ts index 461af50..89c8e7d 100644 --- a/src/app/api/notes/[id]/route.ts +++ b/src/app/api/notes/[id]/route.ts @@ -1,22 +1,33 @@ import { NextResponse } from "next/server"; +import { requireUserApi } from "@/lib/auth/guard"; import { prisma } from "@/lib/db"; +import { jsonError, readJsonBody } from "@/lib/security/request"; import { formatZodError, noteUpdateSchema } from "@/lib/validation"; export const dynamic = "force-dynamic"; type Params = { params: Promise<{ id: string }> }; +/** Eine Notiz gehoert dem, dem das zugehoerige Projekt gehoert. */ +async function ownedNote(noteId: string, ownerId: string) { + return prisma.note.findFirst({ + where: { id: noteId, project: { ownerId } }, + select: { id: true, projectId: true }, + }); +} + export async function PATCH(request: Request, { params }: Params) { + const auth = await requireUserApi(); + if (!auth.ok) return auth.response; + const { id } = await params; + const note = await ownedNote(id, auth.user.id); + if (!note) return jsonError("Notiz nicht gefunden", 404); - let body: unknown; - try { - body = await request.json(); - } catch { - return NextResponse.json({ error: "Ungueltiger JSON-Body" }, { status: 400 }); - } + const body = await readJsonBody(request); + if (!body.ok) return body.response; - const parsed = noteUpdateSchema.safeParse(body); + const parsed = noteUpdateSchema.safeParse(body.data); if (!parsed.success) { return NextResponse.json( { error: "Validierung fehlgeschlagen", fields: formatZodError(parsed.error) }, @@ -24,27 +35,28 @@ export async function PATCH(request: Request, { params }: Params) { ); } - try { - const note = await prisma.note.update({ - where: { id }, - data: { - ...(parsed.data.title !== undefined ? { title: parsed.data.title } : {}), - ...(parsed.data.content !== undefined ? { content: parsed.data.content } : {}), - ...(parsed.data.pinned !== undefined ? { pinned: parsed.data.pinned } : {}), - }, - }); - return NextResponse.json({ note }); - } catch { - return NextResponse.json({ error: "Notiz nicht gefunden" }, { status: 404 }); - } + const updated = await prisma.note.update({ + where: { id }, + data: { + ...(parsed.data.title !== undefined ? { title: parsed.data.title } : {}), + ...(parsed.data.content !== undefined ? { content: parsed.data.content } : {}), + ...(parsed.data.pinned !== undefined ? { pinned: parsed.data.pinned } : {}), + }, + }); + + return NextResponse.json({ note: updated }); } export async function DELETE(_request: Request, { params }: Params) { + const auth = await requireUserApi(); + if (!auth.ok) return auth.response; + const { id } = await params; - try { - await prisma.note.delete({ where: { id } }); - return NextResponse.json({ ok: true }); - } catch { - return NextResponse.json({ error: "Notiz nicht gefunden" }, { status: 404 }); - } + + const result = await prisma.note.deleteMany({ + where: { id, project: { ownerId: auth.user.id } }, + }); + if (result.count === 0) return jsonError("Notiz nicht gefunden", 404); + + return NextResponse.json({ ok: true }); } diff --git a/src/app/api/projects/[id]/notes/route.ts b/src/app/api/projects/[id]/notes/route.ts index 815286f..48c344e 100644 --- a/src/app/api/projects/[id]/notes/route.ts +++ b/src/app/api/projects/[id]/notes/route.ts @@ -1,13 +1,30 @@ import { NextResponse } from "next/server"; +import { requireUserApi } from "@/lib/auth/guard"; import { prisma } from "@/lib/db"; +import { jsonError, readJsonBody } from "@/lib/security/request"; import { formatZodError, noteCreateSchema } from "@/lib/validation"; export const dynamic = "force-dynamic"; type Params = { params: Promise<{ id: string }> }; +/** Prueft in einem Zug Existenz und Besitz des Projekts. */ +async function ownedProject(projectId: string, ownerId: string) { + return prisma.project.findFirst({ + where: { id: projectId, ownerId }, + select: { id: true }, + }); +} + export async function GET(_request: Request, { params }: Params) { + const auth = await requireUserApi(); + if (!auth.ok) return auth.response; + const { id } = await params; + if (!(await ownedProject(id, auth.user.id))) { + return jsonError("Projekt nicht gefunden", 404); + } + const notes = await prisma.note.findMany({ where: { projectId: id }, orderBy: [{ pinned: "desc" }, { updatedAt: "desc" }], @@ -16,21 +33,18 @@ export async function GET(_request: Request, { params }: Params) { } export async function POST(request: Request, { params }: Params) { + const auth = await requireUserApi(); + if (!auth.ok) return auth.response; + const { id } = await params; - - const project = await prisma.project.findUnique({ where: { id }, select: { id: true } }); - if (!project) { - return NextResponse.json({ error: "Projekt nicht gefunden" }, { status: 404 }); + if (!(await ownedProject(id, auth.user.id))) { + return jsonError("Projekt nicht gefunden", 404); } - let body: unknown; - try { - body = await request.json(); - } catch { - return NextResponse.json({ error: "Ungueltiger JSON-Body" }, { status: 400 }); - } + const body = await readJsonBody(request); + if (!body.ok) return body.response; - const parsed = noteCreateSchema.safeParse(body); + const parsed = noteCreateSchema.safeParse(body.data); if (!parsed.success) { return NextResponse.json( { error: "Validierung fehlgeschlagen", fields: formatZodError(parsed.error) }, diff --git a/src/app/api/projects/[id]/route.ts b/src/app/api/projects/[id]/route.ts index 0ea838c..c3ca068 100644 --- a/src/app/api/projects/[id]/route.ts +++ b/src/app/api/projects/[id]/route.ts @@ -1,7 +1,9 @@ import { NextResponse } from "next/server"; +import { requireUserApi } from "@/lib/auth/guard"; import { prisma } from "@/lib/db"; import { parseRepoUrl } from "@/lib/git"; import { projectDetailInclude, projectListInclude, uniqueSlug } from "@/lib/projects"; +import { jsonError, readJsonBody } from "@/lib/security/request"; import { formatZodError, projectUpdateSchema } from "@/lib/validation"; export const dynamic = "force-dynamic"; @@ -9,29 +11,32 @@ export const dynamic = "force-dynamic"; type Params = { params: Promise<{ id: string }> }; export async function GET(_request: Request, { params }: Params) { + const auth = await requireUserApi(); + if (!auth.ok) return auth.response; + const { id } = await params; - const project = await prisma.project.findUnique({ - where: { id }, + const project = await prisma.project.findFirst({ + where: { id, ownerId: auth.user.id }, include: projectDetailInclude, }); - if (!project) { - return NextResponse.json({ error: "Projekt nicht gefunden" }, { status: 404 }); - } + // Fremde Projekte werden wie nicht vorhandene behandelt – die Antwort + // verraet also nicht, dass es die ID gibt. + if (!project) return jsonError("Projekt nicht gefunden", 404); + return NextResponse.json({ project }); } export async function PATCH(request: Request, { params }: Params) { + const auth = await requireUserApi(); + if (!auth.ok) return auth.response; + const { id } = await params; - let body: unknown; - try { - body = await request.json(); - } catch { - return NextResponse.json({ error: "Ungueltiger JSON-Body" }, { status: 400 }); - } + const body = await readJsonBody(request); + if (!body.ok) return body.response; - const parsed = projectUpdateSchema.safeParse(body); + const parsed = projectUpdateSchema.safeParse(body.data); if (!parsed.success) { return NextResponse.json( { error: "Validierung fehlgeschlagen", fields: formatZodError(parsed.error) }, @@ -39,19 +44,38 @@ export async function PATCH(request: Request, { params }: Params) { ); } - const existing = await prisma.project.findUnique({ where: { id } }); - if (!existing) { - return NextResponse.json({ error: "Projekt nicht gefunden" }, { status: 404 }); - } + const existing = await prisma.project.findFirst({ + where: { id, ownerId: auth.user.id }, + }); + if (!existing) return jsonError("Projekt nicht gefunden", 404); const data = parsed.data; + + if (data.connectionId) { + const connection = await prisma.gitConnection.findFirst({ + where: { id: data.connectionId, ownerId: auth.user.id }, + select: { id: true }, + }); + if (!connection) return jsonError("Git-Verbindung nicht gefunden.", 404); + } + const update: Record = {}; if (data.name !== undefined && data.name !== existing.name) { update.name = data.name; - update.slug = await uniqueSlug(data.name, id); + update.slug = await uniqueSlug(data.name, auth.user.id, id); } - for (const key of ["summary", "description", "status", "priority", "progress", "accent", "tags", "favorite", "connectionId"] as const) { + for (const key of [ + "summary", + "description", + "status", + "priority", + "progress", + "accent", + "tags", + "favorite", + "connectionId", + ] as const) { if (data[key] !== undefined) update[key] = data[key]; } @@ -79,11 +103,16 @@ export async function PATCH(request: Request, { params }: Params) { } export async function DELETE(_request: Request, { params }: Params) { + const auth = await requireUserApi(); + if (!auth.ok) return auth.response; + const { id } = await params; - try { - await prisma.project.delete({ where: { id } }); - return NextResponse.json({ ok: true }); - } catch { - return NextResponse.json({ error: "Projekt nicht gefunden" }, { status: 404 }); - } + + // deleteMany mit Besitzerbedingung: trifft fremde Projekte gar nicht erst. + const result = await prisma.project.deleteMany({ + where: { id, ownerId: auth.user.id }, + }); + if (result.count === 0) return jsonError("Projekt nicht gefunden", 404); + + return NextResponse.json({ ok: true }); } diff --git a/src/app/api/projects/[id]/sync/route.ts b/src/app/api/projects/[id]/sync/route.ts index c2a39da..b9779c5 100644 --- a/src/app/api/projects/[id]/sync/route.ts +++ b/src/app/api/projects/[id]/sync/route.ts @@ -1,6 +1,9 @@ import { NextResponse } from "next/server"; +import { requireUserApi } from "@/lib/auth/guard"; import { prisma } from "@/lib/db"; import { projectDetailInclude } from "@/lib/projects"; +import { LIMITS, rateLimit } from "@/lib/security/rateLimit"; +import { clientIp, jsonError, tooManyRequests } from "@/lib/security/request"; import { syncProject } from "@/lib/sync"; export const dynamic = "force-dynamic"; @@ -8,12 +11,31 @@ export const dynamic = "force-dynamic"; type Params = { params: Promise<{ id: string }> }; /** Holt Branches, Tags, Commits und Releases beim Git-System ab. */ -export async function POST(_request: Request, { params }: Params) { +export async function POST(request: Request, { params }: Params) { + const auth = await requireUserApi(); + if (!auth.ok) return auth.response; + + // Dieser Endpunkt loest ausgehende Verbindungen aus – hier wird enger + // begrenzt als bei reinen Datenbankzugriffen. + const limited = rateLimit( + `outbound:${auth.user.id}:${clientIp(request)}`, + LIMITS.outbound.limit, + LIMITS.outbound.windowMs, + ); + if (!limited.ok) return tooManyRequests(limited.retryAfter); + const { id } = await params; + + const owned = await prisma.project.findFirst({ + where: { id, ownerId: auth.user.id }, + select: { id: true }, + }); + if (!owned) return jsonError("Projekt nicht gefunden", 404); + const result = await syncProject(id); - const project = await prisma.project.findUnique({ - where: { id }, + const project = await prisma.project.findFirst({ + where: { id, ownerId: auth.user.id }, include: projectDetailInclude, }); diff --git a/src/app/api/projects/route.ts b/src/app/api/projects/route.ts index 486ffb1..f57c4b6 100644 --- a/src/app/api/projects/route.ts +++ b/src/app/api/projects/route.ts @@ -1,18 +1,26 @@ import { NextResponse } from "next/server"; +import { requireUserApi } from "@/lib/auth/guard"; import { prisma } from "@/lib/db"; import { parseRepoUrl } from "@/lib/git"; import { projectListInclude, uniqueSlug } from "@/lib/projects"; +import { LIMITS, rateLimit } from "@/lib/security/rateLimit"; +import { clientIp, jsonError, readJsonBody, tooManyRequests } from "@/lib/security/request"; import { formatZodError, projectCreateSchema } from "@/lib/validation"; export const dynamic = "force-dynamic"; export async function GET(request: Request) { + const auth = await requireUserApi(); + if (!auth.ok) return auth.response; + const { searchParams } = new URL(request.url); const status = searchParams.get("status"); const query = searchParams.get("q"); const projects = await prisma.project.findMany({ where: { + // Die Besitzerbedingung steht immer zuerst und ist nicht optional. + ownerId: auth.user.id, ...(status ? { status: status as never } : {}), ...(query ? { @@ -32,14 +40,20 @@ export async function GET(request: Request) { } export async function POST(request: Request) { - let body: unknown; - try { - body = await request.json(); - } catch { - return NextResponse.json({ error: "Ungueltiger JSON-Body" }, { status: 400 }); - } + const auth = await requireUserApi(); + if (!auth.ok) return auth.response; - const parsed = projectCreateSchema.safeParse(body); + const limited = rateLimit( + `mutate:${clientIp(request)}`, + LIMITS.mutation.limit, + LIMITS.mutation.windowMs, + ); + if (!limited.ok) return tooManyRequests(limited.retryAfter); + + const body = await readJsonBody(request); + if (!body.ok) return body.response; + + const parsed = projectCreateSchema.safeParse(body.data); if (!parsed.success) { return NextResponse.json( { error: "Validierung fehlgeschlagen", fields: formatZodError(parsed.error) }, @@ -49,6 +63,15 @@ export async function POST(request: Request) { const data = parsed.data; + // Eine fremde Verbindung darf nicht untergeschoben werden. + if (data.connectionId) { + const connection = await prisma.gitConnection.findFirst({ + where: { id: data.connectionId, ownerId: auth.user.id }, + select: { id: true }, + }); + if (!connection) return jsonError("Git-Verbindung nicht gefunden.", 404); + } + // Owner/Name aus der URL ableiten, falls nicht explizit angegeben. let repoOwner = data.repoOwner ?? null; let repoName = data.repoName ?? null; @@ -62,8 +85,9 @@ export async function POST(request: Request) { const project = await prisma.project.create({ data: { + ownerId: auth.user.id, name: data.name, - slug: await uniqueSlug(data.name), + slug: await uniqueSlug(data.name, auth.user.id), summary: data.summary ?? null, description: data.description ?? null, status: data.status, diff --git a/src/app/connections/page.tsx b/src/app/connections/page.tsx index a9a5428..8313975 100644 --- a/src/app/connections/page.tsx +++ b/src/app/connections/page.tsx @@ -1,5 +1,6 @@ import type { Metadata } from "next"; import { ConnectionsManager } from "@/components/ConnectionsManager"; +import { requireUserPage } from "@/lib/auth/guard"; import { prisma } from "@/lib/db"; import { connectionSafeSelect } from "@/lib/projects"; import type { ConnectionWithCount } from "@/types"; @@ -8,11 +9,14 @@ export const dynamic = "force-dynamic"; export const metadata: Metadata = { title: "Git-Verbindungen", - description: "GitHub, GitLab und Gitea mit Nebula verbinden.", + description: "GitHub, GitLab und Gitea verbinden.", }; export default async function ConnectionsPage() { + const user = await requireUserPage(); + const connections = await prisma.gitConnection.findMany({ + where: { ownerId: user.id }, select: { ...connectionSafeSelect, _count: { select: { projects: true } } }, orderBy: { name: "asc" }, }); diff --git a/src/app/page.tsx b/src/app/page.tsx index 6565f73..ad84d08 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -1,6 +1,7 @@ import { CircleDot, GitBranch, Lightbulb, Rocket, Trophy } from "lucide-react"; import { ProjectBoard } from "@/components/ProjectBoard"; import { StatCard } from "@/components/StatCard"; +import { requireUserPage } from "@/lib/auth/guard"; import { prisma } from "@/lib/db"; import { connectionSafeSelect, projectListInclude } from "@/lib/projects"; import { STATUS_META } from "@/lib/status"; @@ -9,12 +10,16 @@ import type { ConnectionSafe, ProjectListItem } from "@/types"; export const dynamic = "force-dynamic"; export default async function DashboardPage() { + const user = await requireUserPage(); + const [projects, connections] = await Promise.all([ prisma.project.findMany({ + where: { ownerId: user.id }, include: projectListInclude, orderBy: [{ favorite: "desc" }, { updatedAt: "desc" }], }), prisma.gitConnection.findMany({ + where: { ownerId: user.id }, select: connectionSafeSelect, orderBy: { name: "asc" }, }), diff --git a/src/app/projects/[id]/page.tsx b/src/app/projects/[id]/page.tsx index 317e32d..9bf8a1b 100644 --- a/src/app/projects/[id]/page.tsx +++ b/src/app/projects/[id]/page.tsx @@ -4,6 +4,8 @@ import { FileText } from "lucide-react"; import { GitPanel } from "@/components/GitPanel"; import { NotesPanel } from "@/components/NotesPanel"; import { ProjectHeader } from "@/components/ProjectHeader"; +import { requireUserPage } from "@/lib/auth/guard"; +import { getSessionUser } from "@/lib/auth/session"; import { prisma } from "@/lib/db"; import { connectionSafeSelect, projectDetailInclude } from "@/lib/projects"; import type { ConnectionSafe, ProjectDetail } from "@/types"; @@ -13,9 +15,12 @@ export const dynamic = "force-dynamic"; type PageProps = { params: Promise<{ id: string }> }; export async function generateMetadata({ params }: PageProps): Promise { + const user = await getSessionUser(); + if (!user) return { title: "Projekt" }; + const { id } = await params; - const project = await prisma.project.findUnique({ - where: { id }, + const project = await prisma.project.findFirst({ + where: { id, ownerId: user.id }, select: { name: true, summary: true }, }); return { @@ -25,11 +30,21 @@ export async function generateMetadata({ params }: PageProps): Promise } export default async function ProjectPage({ params }: PageProps) { + const user = await requireUserPage(); const { id } = await params; const [project, connections] = await Promise.all([ - prisma.project.findUnique({ where: { id }, include: projectDetailInclude }), - prisma.gitConnection.findMany({ select: connectionSafeSelect, orderBy: { name: "asc" } }), + // findFirst mit Besitzerbedingung: ein fremdes Projekt fuehrt zu 404, + // nicht zu einer Fehlermeldung, die seine Existenz bestaetigt. + prisma.project.findFirst({ + where: { id, ownerId: user.id }, + include: projectDetailInclude, + }), + prisma.gitConnection.findMany({ + where: { ownerId: user.id }, + select: connectionSafeSelect, + orderBy: { name: "asc" }, + }), ]); if (!project) notFound(); diff --git a/src/lib/projects.ts b/src/lib/projects.ts index 50efa4e..78a21b0 100644 --- a/src/lib/projects.ts +++ b/src/lib/projects.ts @@ -2,16 +2,23 @@ import { Prisma } from "@prisma/client"; import { prisma } from "@/lib/db"; import { slugify } from "@/lib/utils"; -/** Erzeugt einen eindeutigen Slug, notfalls mit angehaengtem Zaehler. */ -export async function uniqueSlug(name: string, ignoreId?: string): Promise { +/** + * Erzeugt einen je Besitzer eindeutigen Slug, notfalls mit angehaengtem + * Zaehler. Zwei Benutzer duerfen also beide ein Projekt "dashboard" haben. + */ +export async function uniqueSlug( + name: string, + ownerId: string, + ignoreId?: string, +): Promise { const base = slugify(name) || "projekt"; let candidate = base; let counter = 2; // In der Praxis endet die Schleife nach wenigen Runden. for (let attempt = 0; attempt < 50; attempt += 1) { - const existing = await prisma.project.findUnique({ - where: { slug: candidate }, + const existing = await prisma.project.findFirst({ + where: { slug: candidate, ownerId }, select: { id: true }, }); if (!existing || existing.id === ignoreId) return candidate;