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
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# Local PostgreSQL, supplied by `docker compose up -d postgres minio`.
DATABASE_URL="postgresql://sidecause:sidecause@localhost:5432/sidecause?schema=public"
DATABASE_URL="postgresql://sidecause:sidecause@localhost:5433/sidecause?schema=public"

# Local S3-compatible object storage, supplied by AIStor.
S3_ENDPOINT="http://localhost:9000"
S3_REGION="us-east-1"
S3_BUCKET="sidecause"
S3_ACCESS_KEY_ID="minioadmin"
S3_SECRET_ACCESS_KEY="minioadmin"
Expand Down
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ npm run test:smoke

## Docker lifecycle

Start local services with `npm run docker:up`, apply migrations with `npm run prisma:deploy`, and optionally add local sample records with `npm run db:seed:examples`. Stop services with `npm run docker:down`; this retains named volumes. The example seed is limited to local database hosts. The smoke test uses a separate Compose project and removes its volumes automatically. Run `docker compose down --volumes` only when intentionally resetting local PostgreSQL and AIStor data. Start the profile-gated application container with `docker compose --profile app up --build`.
Start local services with `npm run docker:up`, apply migrations with `npm run prisma:deploy`, and optionally add local sample records with `npm run db:seed:examples`. PostgreSQL is published on host port `5433` to avoid common local database port conflicts; it listens on `5432` inside Compose. Stop services with `npm run docker:down`; this retains named volumes. The example seed is limited to local database hosts. The smoke test uses a separate Compose project and removes its volumes automatically. Run `docker compose down --volumes` only when intentionally resetting local PostgreSQL and AIStor data. Start the profile-gated application container with `docker compose --profile app up --build`.

## Change checklist

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ This repository contains the development foundation and initial App Router shell
npm ci
```

4. Start local PostgreSQL on `5432` and AIStor on `9000` (console `9001`).
4. Start local PostgreSQL on host port `5433` and AIStor on `9000` (console `9001`). PostgreSQL listens on `5432` inside Compose; host port `5433` avoids collisions with other local databases.

```sh
npm run docker:up
Expand Down Expand Up @@ -89,7 +89,7 @@ Dependabot checks npm, Docker, and GitHub Actions dependencies weekly. Releases
## Troubleshooting

- **`npm ci` rejects the lockfile:** use Node `26.8.2` and npm 11, then retry without editing `package-lock.json`.
- **A local port is occupied:** free or remap port `5432`, `9000`, or `9001` before starting Compose. Update `.env` if you remap a service used by application code.
- **A local port is occupied:** free or remap host port `5433`, `9000`, or `9001` before starting Compose. Update `.env` if you remap a service used by application code.
- **Docker permission/daemon error:** start Docker Desktop (or the Docker daemon) and ensure your account can run `docker compose`.
- **Prisma reports `DATABASE_URL` missing:** copy `.env.example` to `.env`, then run the command from the repository root.

Expand Down
147 changes: 147 additions & 0 deletions app/api/bounties/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import { randomUUID } from 'node:crypto'

import { Prisma } from '../../../generated/prisma/client'
import { auth } from '../../../auth'
import {
maxBountyImageBytes,
parseBountyCreationInput,
validateBountyImage,
} from '../../../lib/bounty-creation-input'
import { deleteObject, uploadObject } from '../../../lib/object-storage'
import { prisma } from '../../../lib/prisma'

export async function POST(request: Request) {
const session = await auth()
const posterId = session?.user?.id
if (!posterId) {
return apiError(401, 'UNAUTHENTICATED', 'Sign in to create a post.')
}

const declaredLength = Number(request.headers.get('content-length') ?? 0)
if (declaredLength > maxBountyImageBytes + 64 * 1024) {
return apiError(
422,
'VALIDATION_ERROR',
'The image must be 5 MB or smaller.',
)
}

let formData: FormData
try {
formData = await request.formData()
} catch {
return apiError(422, 'VALIDATION_ERROR', 'Enter valid post details.')
}

const parsed = parseBountyCreationInput(formData)
if ('error' in parsed) {
return apiError(422, 'VALIDATION_ERROR', parsed.error)
}

const imageValue = formData.get('image')
let upload: {
key: string
url: string
type: string
body: Uint8Array
} | null = null

if (imageValue instanceof File && imageValue.size > 0) {
const validatedImage = await validateBountyImage(imageValue)
if (!validatedImage) {
return apiError(
422,
'VALIDATION_ERROR',
'Choose a JPEG, PNG, or WebP image smaller than 5 MB.',
)
}
const key = `bounties/${randomUUID()}.${validatedImage.extension}`
upload = {
key,
url: `/api/media/${key}`,
type: imageValue.type,
body: validatedImage.body,
}
} else if (
imageValue &&
typeof imageValue === 'string' &&
imageValue !== ''
) {
return apiError(422, 'VALIDATION_ERROR', 'Choose a valid image file.')
}

try {
if (upload) {
await uploadObject(upload.key, upload.body, upload.type)
}

const bounty = await prisma.bounty.create({
data: {
title: parsed.title,
description: parsed.description,
locationLabel: parsed.location,
imageUrl: upload?.url ?? null,
latitude:
parsed.latitude === null ? null : new Prisma.Decimal(parsed.latitude),
longitude:
parsed.longitude === null
? null
: new Prisma.Decimal(parsed.longitude),
scheduledAt: parsed.scheduledAt,
deadline: parsed.deadline,
maxVolunteers: parsed.maximumVolunteers,
payPerVolunteer: new Prisma.Decimal(parsed.payPerVolunteer),
difficulty: parsed.difficulty,
posterId,
skillRequirements: {
create: parsed.skills,
},
equipmentRequirements: {
create: parsed.equipment,
},
},
select: {
id: true,
title: true,
description: true,
locationLabel: true,
status: true,
imageUrl: true,
latitude: true,
longitude: true,
scheduledAt: true,
deadline: true,
maxVolunteers: true,
payPerVolunteer: true,
difficulty: true,
createdAt: true,
skillRequirements: { select: { name: true, level: true } },
equipmentRequirements: { select: { name: true, level: true } },
},
})

return Response.json(
{
data: {
...bounty,
payPerVolunteer: bounty.payPerVolunteer.toString(),
currentVolunteers: 0,
},
},
{ status: 201 },
)
} catch {
if (upload) {
try {
await deleteObject(upload.key)
} catch {
// Keep the API response generic if cleanup cannot remove an orphan.
}
}
return apiError(500, 'INTERNAL_ERROR', 'The post could not be created.')
}
}

function apiError(status: number, code: string, message: string) {
return Response.json({ error: { code, message, details: {} } }, { status })
}
82 changes: 82 additions & 0 deletions app/api/media/[...key]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { auth } from '../../../../auth'
import { canViewBounty } from '../../../../lib/bounty-visibility'
import { prisma } from '../../../../lib/prisma'
import { readObject } from '../../../../lib/object-storage'

type MediaRouteProps = {
params: Promise<{ key: string[] }>
}

export async function GET(_request: Request, { params }: MediaRouteProps) {
const { key: parts } = await params
const key = parts.join('/')
if (!isBountyImageKey(key)) return new Response(null, { status: 404 })

const imageUrl = `/api/media/${key}`
const session = await auth()
const viewerId = session?.user?.id ?? null
const bounty = await prisma.bounty.findFirst({
where: { imageUrl },
select: {
id: true,
status: true,
deadline: true,
posterId: true,
maxVolunteers: true,
volunteerAttendances: {
where: { volunteerId: viewerId ?? '' },
select: { status: true },
take: 1,
},
_count: {
select: {
volunteerAttendances: {
where: { status: 'JOINED' },
},
},
},
},
})

if (
!bounty ||
!canViewBounty({
status: bounty.status,
deadline: bounty.deadline,
posterId: bounty.posterId,
viewerId,
viewerAttendance: bounty.volunteerAttendances[0]?.status ?? null,
currentVolunteers: bounty._count.volunteerAttendances,
maximumVolunteers: bounty.maxVolunteers,
})
) {
return new Response(null, { status: 404 })
}

try {
const image = await readObject(key)
if (
!['image/jpeg', 'image/png', 'image/webp'].includes(image.contentType)
) {
return new Response(null, { status: 404 })
}

const responseBody = new ArrayBuffer(image.body.byteLength)
new Uint8Array(responseBody).set(image.body)

return new Response(responseBody, {
headers: {
'Cache-Control': 'private, no-store',
'Content-Length': String(image.body.byteLength),
'Content-Type': image.contentType,
'X-Content-Type-Options': 'nosniff',
},
})
} catch {
return new Response(null, { status: 404 })
}
}

function isBountyImageKey(key: string): boolean {
return /^bounties\/[0-9a-f-]{36}\.(?:jpg|png|webp)$/.test(key)
}
45 changes: 22 additions & 23 deletions app/posts/[id]/detail-data.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { canViewBounty } from '../../../lib/bounty-visibility'

export type PostRequirement = {
name: string
level: 'REQUIRED' | 'RECOMMENDED'
Expand Down Expand Up @@ -79,36 +81,33 @@ const databaseSource: PostDetailSource = {
return null
}

const now = new Date()
const viewerIsPoster = viewerId !== null && bounty.posterId === viewerId
const viewerAttendance = bounty.volunteerAttendances[0]?.status ?? null
const viewerIsActiveAttendee = viewerAttendance === 'JOINED'
const currentVolunteers = bounty._count.volunteerAttendances

const openAndAvailable =
bounty.status === 'OPEN' &&
bounty.deadline > now &&
currentVolunteers < bounty.maxVolunteers
const fullAndUnexpired = bounty.status === 'FULL' && bounty.deadline > now
const finished = bounty.status === 'FINISHED'
const restrictedViewer = viewerIsPoster || viewerIsActiveAttendee

if (
!openAndAvailable &&
!(fullAndUnexpired && restrictedViewer) &&
!(finished && restrictedViewer)
!canViewBounty({
status: bounty.status,
deadline: bounty.deadline,
posterId: bounty.posterId,
viewerId,
viewerAttendance,
currentVolunteers,
maximumVolunteers: bounty.maxVolunteers,
})
) {
return null
}

const posterEmail = restrictedViewer
? ((
await prisma.user.findUnique({
where: { id: bounty.posterId },
select: { email: true },
})
)?.email ?? null)
: null
const viewerIsPoster = viewerId !== null && bounty.posterId === viewerId
const viewerIsActiveAttendee = viewerAttendance === 'JOINED'
const posterEmail =
viewerIsPoster || viewerIsActiveAttendee
? ((
await prisma.user.findUnique({
where: { id: bounty.posterId },
select: { email: true },
})
)?.email ?? null)
: null

return {
id: bounty.id,
Expand Down
Loading
Loading