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
10 changes: 10 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ on:
pull_request:
branches: [main]

permissions:
contents: read

env:
NEXT_PUBLIC_SUPABASE_URL: ${{ secrets.NEXT_PUBLIC_SUPABASE_URL || 'https://placeholder.supabase.co' }}
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${{ secrets.NEXT_PUBLIC_SUPABASE_ANON_KEY || 'placeholder-key' }}
Expand All @@ -14,6 +17,8 @@ jobs:
lint-and-build:
name: Lint, Type Check & Build
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4

Expand All @@ -40,6 +45,9 @@ jobs:
name: E2E Tests (Playwright)
runs-on: ubuntu-latest
needs: lint-and-build
permissions:
contents: read
actions: read
steps:
- uses: actions/checkout@v4

Expand Down Expand Up @@ -68,6 +76,8 @@ jobs:
security-scan:
name: Security Scan
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
with:
Expand Down
10 changes: 8 additions & 2 deletions app/api/auth/signup/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,14 @@ export async function POST(request: NextRequest) {
}

// 4. Validate email format
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
if (!emailRegex.test(email)) {
const atIndex = email.lastIndexOf('@')
const hasValidEmailShape =
atIndex > 0 &&
atIndex < email.length - 3 &&
!email.includes(' ') &&
email.slice(atIndex + 1).includes('.')

if (!hasValidEmailShape) {
Comment on lines +41 to +48
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Reject multiple @ characters in email validation.

On Line 41, lastIndexOf('@') plus current checks allows malformed values like a@b@c.com. This is overly permissive for signup input validation.

Suggested fix
-    const atIndex = email.lastIndexOf('@')
+    const atIndex = email.indexOf('@')
+    const hasSingleAt = atIndex === email.lastIndexOf('@')
+    const domain = atIndex >= 0 ? email.slice(atIndex + 1) : ''
     const hasValidEmailShape =
+      hasSingleAt &&
       atIndex > 0 &&
       atIndex < email.length - 3 &&
       !email.includes(' ') &&
-      email.slice(atIndex + 1).includes('.')
+      domain.includes('.') &&
+      !domain.startsWith('.') &&
+      !domain.endsWith('.')
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const atIndex = email.lastIndexOf('@')
const hasValidEmailShape =
atIndex > 0 &&
atIndex < email.length - 3 &&
!email.includes(' ') &&
email.slice(atIndex + 1).includes('.')
if (!hasValidEmailShape) {
const atIndex = email.indexOf('@')
const hasSingleAt = atIndex === email.lastIndexOf('@')
const domain = atIndex >= 0 ? email.slice(atIndex + 1) : ''
const hasValidEmailShape =
hasSingleAt &&
atIndex > 0 &&
atIndex < email.length - 3 &&
!email.includes(' ') &&
domain.includes('.') &&
!domain.startsWith('.') &&
!domain.endsWith('.')
if (!hasValidEmailShape) {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/api/auth/signup/route.ts` around lines 41 - 48, The email validation
currently uses lastIndexOf('@') which allows multiple '@' characters (e.g.,
"a@b@c.com"); update the logic in the signup route where variables email,
atIndex, and hasValidEmailShape are computed to reject emails with more than one
'@' by checking email.indexOf('@') === email.lastIndexOf('@') (or counting '@'
occurrences) in addition to the existing checks so that hasValidEmailShape
becomes false when multiple '@' characters are present.

return NextResponse.json(
{ error: 'Invalid email format' },
{ status: 400 }
Expand Down
122 changes: 39 additions & 83 deletions app/api/projects/[id]/collaborators/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { NextResponse } from "next/server"
import { createAdminClient } from "@/lib/database/supabase-admin"
import { createServerSupabaseClient } from "@/lib/database/supabase-server"
import { getProjectAccessContext } from "@/lib/server/project-access"

const COLLABORATOR_ROLES = ["admin", "editor", "viewer"] as const
type CollaboratorRole = (typeof COLLABORATOR_ROLES)[number]
Expand All @@ -15,50 +17,35 @@ export async function GET(
) {
try {
const { id: projectId } = await params
const supabase = await createServerSupabaseClient()
const sessionClient = await createServerSupabaseClient()
const adminClient = createAdminClient()
const dataClient = adminClient || sessionClient

// Check if user is authenticated
const { data: { user }, error: authError } = await supabase.auth.getUser()
const { data: { user }, error: authError } = await sessionClient.auth.getUser()
if (authError || !user) {
return NextResponse.json(
{ error: "Unauthorized" },
{ status: 401 }
)
}

// Check if user has access to the project (owner or collaborator)
const { data: project } = await supabase
.from("projects")
.select("user_id")
.eq("id", projectId)
.single()

if (!project) {
const access = await getProjectAccessContext(dataClient, projectId, user.id)
if (!access) {
return NextResponse.json(
{ error: "Project not found" },
{ status: 404 }
)
}

const isOwner = project.user_id === user.id

const { data: collaborator } = await supabase
.from("project_collaborators")
.select("role")
.eq("project_id", projectId)
.eq("user_id", user.id)
.maybeSingle()

const hasAccess = isOwner || !!collaborator

if (!hasAccess) {
if (!access.hasAccess) {
return NextResponse.json(
{ error: "Access denied" },
{ status: 403 }
)
}

const { data: collaboratorRows, error: collaboratorError } = await supabase
const { data: collaboratorRows, error: collaboratorError } = await dataClient
.from("project_collaborators")
.select("id, project_id, user_id, role, invited_by, joined_at")
.eq("project_id", projectId)
Expand All @@ -77,7 +64,7 @@ export async function GET(
)

const { data: profiles, error: profilesError } = collaboratorIds.length
? await supabase
? await dataClient
.from("profiles")
.select("id, email, name, avatar")
.in("id", collaboratorIds)
Expand Down Expand Up @@ -133,8 +120,10 @@ export async function POST(
}

// 1. Authenticate Request
const supabase = await createServerSupabaseClient()
const { data: { user }, error: authError } = await supabase.auth.getUser()
const sessionClient = await createServerSupabaseClient()
const adminClient = createAdminClient()
const dataClient = adminClient || sessionClient
const { data: { user }, error: authError } = await sessionClient.auth.getUser()

if (authError || !user) {
return NextResponse.json(
Expand All @@ -144,40 +133,23 @@ export async function POST(
}

// 2. Check Permissions (Project Owner/Admin)
const { data: project } = await supabase
.from("projects")
.select("user_id")
.eq("id", projectId)
.single()

if (!project) {
const access = await getProjectAccessContext(dataClient, projectId, user.id)
if (!access) {
return NextResponse.json(
{ error: "Project not found" },
{ status: 404 }
)
}

const isOwner = project.user_id === user.id

if (!isOwner) {
// Check if user is an admin collaborator
const { data: userCollab } = await supabase
.from("project_collaborators")
.select("role")
.eq("project_id", projectId)
.eq("user_id", user.id)
.maybeSingle()

if (!userCollab || userCollab.role !== "admin") {
return NextResponse.json(
{ error: "Only project owners and admins can add collaborators" },
{ status: 403 }
)
}
if (!access.canManage) {
return NextResponse.json(
{ error: "Only project owners and admins can add collaborators" },
{ status: 403 }
)
}

// 3. User Lookup
const { data: userProfile, error: profileError } = await supabase
const { data: userProfile, error: profileError } = await dataClient
.from("profiles")
.select("id, email, name, avatar")
.ilike("email", normalizedEmail)
Expand Down Expand Up @@ -206,7 +178,7 @@ export async function POST(
)
}

if (userProfile.id === project.user_id) {
if (userProfile.id === access.project.user_id) {
return NextResponse.json(
{ error: "The project owner already has access" },
{ status: 400 }
Expand All @@ -215,7 +187,7 @@ export async function POST(

// 4. Add Collaborator
// First check if already exists
const { data: existingCollab } = await supabase
const { data: existingCollab } = await dataClient
.from("project_collaborators")
.select("user_id")
.eq("project_id", projectId)
Expand All @@ -229,7 +201,7 @@ export async function POST(
)
}

const { data: newCollaborator, error: insertError } = await supabase
const { data: newCollaborator, error: insertError } = await dataClient
.from("project_collaborators")
.insert({
project_id: projectId,
Expand Down Expand Up @@ -282,58 +254,42 @@ export async function DELETE(
)
}

const supabase = await createServerSupabaseClient()
const sessionClient = await createServerSupabaseClient()
const adminClient = createAdminClient()
const dataClient = adminClient || sessionClient

// Check if user is authenticated
const { data: { user }, error: authError } = await supabase.auth.getUser()
const { data: { user }, error: authError } = await sessionClient.auth.getUser()
if (authError || !user) {
return NextResponse.json(
{ error: "Unauthorized" },
{ status: 401 }
)
}

// Check if user is the project owner or admin
const { data: project } = await supabase
.from("projects")
.select("user_id")
.eq("id", projectId)
.single()

if (!project) {
const access = await getProjectAccessContext(dataClient, projectId, user.id)
if (!access) {
return NextResponse.json(
{ error: "Project not found" },
{ status: 404 }
)
}

const isOwner = project.user_id === user.id

if (userIdToRemove === project.user_id) {
if (userIdToRemove === access.project.user_id) {
return NextResponse.json(
{ error: "Project owner cannot be removed" },
{ status: 400 }
)
}

if (!isOwner) {
// Check if user is an admin collaborator
const { data: userCollab } = await supabase
.from("project_collaborators")
.select("role")
.eq("project_id", projectId)
.eq("user_id", user.id)
.maybeSingle()

if (!userCollab || userCollab.role !== "admin") {
return NextResponse.json(
{ error: "Only project owners and admins can remove collaborators" },
{ status: 403 }
)
}
if (!access.canManage) {
return NextResponse.json(
{ error: "Only project owners and admins can remove collaborators" },
{ status: 403 }
)
}

const { error: deleteError } = await supabase
const { error: deleteError } = await dataClient
.from("project_collaborators")
.delete()
.eq("project_id", projectId)
Expand Down
25 changes: 25 additions & 0 deletions app/api/projects/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { NextResponse } from "next/server"

import { createAdminClient } from "@/lib/database/supabase-admin"
import { createServerSupabaseClient } from "@/lib/database/supabase-server"
import { listAccessibleProjects, requireAuthenticatedUser } from "@/lib/server/project-access"

export async function GET() {
try {
const sessionClient = await createServerSupabaseClient()
const user = await requireAuthenticatedUser(sessionClient)

if (!user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}

const adminClient = createAdminClient()
const dataSource = adminClient || sessionClient
const projects = await listAccessibleProjects(dataSource, user.id)

return NextResponse.json({ projects })
} catch (error) {
console.error("Failed to fetch projects:", error)
return NextResponse.json({ error: "Failed to fetch projects" }, { status: 500 })
}
}
Loading
Loading