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
29 changes: 24 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,10 @@ Send `Authorization: Bearer <access_token>` on authenticated routes and `Accept:
| `PUT /api/location` | Bearer | JSON `lat` and `lon` | `200` with the saved location row | `validation_failed`, `no_space`, `unauthorized`, `internal` |
| `DELETE /api/location` | Bearer | — | `204`, including when the caller has no saved location | `unauthorized`, `internal` |
| `GET /api/dashboard` | Bearer | — | `200` with `serverTime`, `nextMeeting`, twelve UTC `datesByMonth` totals, and historical `categoriesByMonth` grouped by UTC month and category key | `unauthorized`, `internal` |
| `GET /api/photos` | Bearer | Optional `offset` | `200` with up to 30 uploads newest first, with signed URLs valid for five minutes | `validation_failed`, `no_space`, `unauthorized`, `internal` |
| `POST /api/photos` | Bearer | Raw JPEG, PNG, or WebP bytes with matching `Content-Type`, up to 5 MiB in Nitro | `200` with Storage `id`, `path`, and `fullPath` | `validation_failed`, `no_space`, `unauthorized`, `internal` |
| `DELETE /api/photos/:name` | Bearer | UUID `name` from the gallery | `204`, including when the name is absent from the caller's gallery | `validation_failed`, `no_space`, `unauthorized`, `internal` |
| `GET /api/photos` | Bearer | Optional `offset` | `200` with up to 30 confirmed photos newest first. Each includes its metadata and a five-minute signed URL when available. | `validation_failed`, `no_space`, `unauthorized`, `internal` |
| `POST /api/photos/upload-url` | Bearer | JSON `mime` and `size` in bytes, up to 5 MiB | `200` with `uploadId`, `path`, `signedUrl`, and `token` | `validation_failed`, `quota_exceeded`, `no_space`, `unauthorized`, `internal` |
| `POST /api/photos/confirm` | Bearer | JSON `uploadId` from the reservation | `200` with the confirmed photo row. The uploader can retry using the same ID. | `validation_failed`, `not_found`, `no_space`, `unauthorized`, `internal` |
| `DELETE /api/photos/:name` | Bearer | UUID `name` from the gallery | `204` when a confirmed photo is removed | `validation_failed`, `not_found`, `no_space`, `unauthorized`, `internal` |

### Date category keys

Expand Down Expand Up @@ -117,15 +118,33 @@ For a space with three dates created in November 2026 and no upcoming meeting, t

Apply migration `006` before the frontend depends on `datesByMonth`.

### Direct photo uploads

1. Send `POST /api/photos/upload-url` with JSON such as `{"mime":"image/png","size":5242880}`. Supported MIME types are `image/jpeg`, `image/png`, and `image/webp`. Use the final compressed file's MIME and size.
2. Send the bytes directly to the private `gallery` bucket with the Supabase SDK. The signed token is for that path only. Keep it out of application logs.

```ts
const { error } = await supabase.storage.from('gallery')
.uploadToSignedUrl(reservation.path, reservation.token, file, { contentType: file.type })
if (error) throw error
```

3. Send `POST /api/photos/confirm` with `{"uploadId":"<reservation UUID>"}`. The server checks the stored MIME and byte count, then returns the registered photo. Retry confirmation with the same ID after an interrupted response. The gallery lists confirmed rows and may return a null URL when a file cannot be signed.

The old binary `POST /api/photos` returns `405`. Both upload POSTs carry JSON so the image bypasses the Vercel Function request-body limit. A space has a **50 MiB** quota. An open, unconfirmed upload holds **5 MiB** through the signing window, the signed token's lifetime, and a 15-minute transfer grace period. Confirmation releases the hold and counts the stored file size. Deleting the file frees those bytes immediately. If a hold expires with an unconfirmed file still in Storage, that file counts toward the quota until it is removed. [Supabase signed upload URLs](https://supabase.com/docs/reference/javascript/storage-from-createsigneduploadurl)

Apply migration `005` before serving this API version. Existing gallery objects with a compatible path, MIME, and size are backfilled. Objects without compatible metadata stay in Storage and count toward the quota.

### Error codes and statuses

| `data.code` | HTTP | Meaning |
| --- | --- | --- |
| `invite_invalid` | 400 | The invite is unknown or already consumed. |
| `already_paired` | 409 | The caller already belongs to a space when creating or joining, or the space already has two members when rotating an invite. |
| `no_space` | 403 | The operation requires the caller to belong to a space. |
| `not_found` | 404 | The date is missing or outside the caller's visible rows. |
| `validation_failed` | 400, 413, 415 | Input is invalid, an upload is too large, or the media type or signature is unsupported. |
| `not_found` | 404 | A date, photo, or upload is missing or outside the caller's visible rows. |
| `quota_exceeded` | 409 | Counted Storage bytes, active unconfirmed holds, and a new 5 MiB hold would exceed the space's 50 MiB quota. |
| `validation_failed` | 400, 405, 413, 415 | Input is invalid, the removed binary upload route was called, an upload is too large, or the media type is unsupported. |
| `unauthorized` | 401 | The access token is missing or rejected. |
| `internal` | 500, 503 | An unexpected server failure occurred or a dependency is unavailable. |

Expand Down
7 changes: 5 additions & 2 deletions server/api/photos/[name].delete.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { defineApiHandler } from '../../utils/api-error'
import { defineApiHandler, toApiError } from '../../utils/api-error'
import { photoParamsSchema } from '../../../shared/api-contract'

export default defineApiHandler(async event => {
const { name } = await getValidatedRouterParams(event, photoParamsSchema.parse)
const db = client(event)
const space = await room(db)
result(await db.storage.from('gallery').remove([space + '/' + name]))
const photo = result(await db.from('photos').select('path').eq('space_id', space).eq('id', name).maybeSingle())
if (!photo) throw toApiError('not_found')
result(await db.storage.from('gallery').remove([photo.path]))
result(await db.rpc('forget_photo', { photo_id: name }), 'photo')
return sendNoContent(event)
})
7 changes: 7 additions & 0 deletions server/api/photos/confirm.post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { confirmPhotoRequestSchema } from '../../../shared/api-contract'
import { defineApiHandler } from '../../utils/api-error'

export default defineApiHandler(async event => {
const { uploadId } = await readValidatedBody(event, confirmPhotoRequestSchema.parse)
return result(await client(event).rpc('confirm_photo', { photo_upload_id: uploadId }), 'photo')
})
13 changes: 0 additions & 13 deletions server/api/photos/index.get.ts

This file was deleted.

26 changes: 0 additions & 26 deletions server/api/photos/index.post.ts

This file was deleted.

26 changes: 26 additions & 0 deletions server/api/photos/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { isMethod, setResponseHeader } from 'h3'
import { photosQuerySchema } from '../../../shared/api-contract'
import { defineApiHandler, toApiError } from '../../utils/api-error'

export default defineApiHandler(async event => {
if (!isMethod(event, 'GET', true)) {
setResponseHeader(event, 'Allow', 'GET, HEAD')
throw toApiError('validation_failed', 405)
}
const db = client(event)
const space = await room(db)
const { offset } = await getValidatedQuery(event, photosQuerySchema.parse)
const photos = result(await db.from('photos').select('id,path,mime,size,uploaded_by,created_at')
.eq('space_id', space).order('created_at', { ascending: false }).order('id').range(offset, offset + 29)) ?? []
if (!photos.length) return []
const urls = result(await db.storage.from('gallery').createSignedUrls(photos.map(photo => photo.path), 300)) ?? []
const urlsByPath = new Map(urls.map(url => [url.path, url.signedUrl]))
return photos.map(photo => ({
name: photo.id,
createdAt: photo.created_at,
url: urlsByPath.get(photo.path) ?? null,
mime: photo.mime,
size: photo.size,
uploadedBy: photo.uploaded_by,
}))
})
24 changes: 24 additions & 0 deletions server/api/photos/upload-url.post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { photoUploadMaxBytes, photoUploadUrlRequestSchema } from '../../../shared/api-contract'
import { defineApiHandler, toApiError } from '../../utils/api-error'

export default defineApiHandler(async event => {
const body = await readBody(event)
const parsed = photoUploadUrlRequestSchema.safeParse(body)
if (!parsed.success) {
if (parsed.error.issues.some(issue => issue.path[0] === 'mime')) {
throw toApiError('validation_failed', 415)
}
if (typeof body?.size === 'number' && body.size > photoUploadMaxBytes) {
throw toApiError('validation_failed', 413)
}
throw toApiError('validation_failed')
}
const db = client(event)
const reservation = result(await db.rpc('reserve_photo_upload', {
upload_mime: parsed.data.mime,
upload_size: parsed.data.size,
}), 'photo')
const { signedUrl, token } = result(await db.storage.from('gallery')
.createSignedUploadUrl(reservation.path, { upsert: false }))
return { ...reservation, signedUrl, token }
})
1 change: 1 addition & 0 deletions server/utils/api-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const errorDetails = {
already_paired: { statusCode: 409, statusMessage: 'Already paired' },
no_space: { statusCode: 403, statusMessage: 'Join or create a space first' },
not_found: { statusCode: 404, statusMessage: 'Not found' },
quota_exceeded: { statusCode: 409, statusMessage: 'Photo quota exceeded' },
validation_failed: { statusCode: 400, statusMessage: 'Validation failed' },
unauthorized: { statusCode: 401, statusMessage: 'Unauthorized' },
internal: { statusCode: 500, statusMessage: 'Internal server error' },
Expand Down
8 changes: 7 additions & 1 deletion server/utils/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type SupabaseResult<T> = {
status?: number
}

export function result<T>(response: SupabaseResult<T>, operation?: 'createSpace' | 'joinSpace' | 'mutateDate' | 'regenerateInvite') {
export function result<T>(response: SupabaseResult<T>, operation?: 'createSpace' | 'joinSpace' | 'mutateDate' | 'regenerateInvite' | 'photo') {
if (!response.error) {
return response.data
}
Expand All @@ -48,6 +48,12 @@ export function result<T>(response: SupabaseResult<T>, operation?: 'createSpace'
if (operation === 'regenerateInvite' && code === 'PT409') {
throw toApiError('already_paired')
}
if (operation === 'photo') {
if (code === 'PT403') throw toApiError('no_space')
if (code === 'PT404') throw toApiError('not_found')
if (code === 'PT400') throw toApiError('validation_failed')
if (code === 'PT409') throw toApiError('quota_exceeded')
}

console.error('Unexpected Supabase request failure', response.error)
throw toApiError('internal', response.status === 503 || status === 503 || statusCode === '503' ? 503 : 500)
Expand Down
34 changes: 28 additions & 6 deletions shared/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,27 @@ export const photosQuerySchema = z.object({ offset })
export const photoParamsSchema = z.object({ name: uuid })
export const photoContentTypeSchema = z.enum(['image/jpeg', 'image/png', 'image/webp'])
export const photoUploadMaxBytes = 5 * 1024 * 1024
export const uploadPhotoRequestSchema = z.object({
contentType: photoContentTypeSchema,
body: z.instanceof(Uint8Array).refine(bytes => bytes.byteLength <= photoUploadMaxBytes),
export const photoSpaceQuotaBytes = 50 * 1024 * 1024
const photoSizeSchema = z.number().int().positive().max(photoUploadMaxBytes)
export const photoUploadUrlRequestSchema = z.strictObject({
mime: photoContentTypeSchema,
size: photoSizeSchema,
})
export const photoUploadUrlResponseSchema = z.object({
uploadId: uuid,
path: z.string(),
signedUrl: z.url(),
token: z.string().min(1),
})
export const confirmPhotoRequestSchema = z.strictObject({ uploadId: uuid })
export const photoResponseSchema = z.object({
id: uuid,
space_id: uuid,
path: z.string(),
mime: photoContentTypeSchema,
size: photoSizeSchema,
uploaded_by: uuid.nullable(),
created_at: timestamp,
})

export const healthResponseSchema = z.object({ status: z.literal('ok') })
Expand Down Expand Up @@ -85,8 +103,10 @@ export const photosResponseSchema = z.array(z.object({
name: uuid,
createdAt: timestamp,
url: z.url().nullish(),
mime: photoContentTypeSchema,
size: photoSizeSchema,
uploadedBy: uuid.nullable(),
}))
export const uploadPhotoResponseSchema = z.object({ id: uuid, path: z.string(), fullPath: z.string() })

export type JoinSpaceRequest = z.input<typeof joinSpaceRequestSchema>
export type CreateDateRequest = z.input<typeof createDateRequestSchema>
Expand All @@ -97,7 +117,10 @@ export type UpdateLocationRequest = z.input<typeof updateLocationRequestSchema>
export type PhotosQuery = z.input<typeof photosQuerySchema>
export type PhotoParams = z.input<typeof photoParamsSchema>
export type PhotoContentType = z.infer<typeof photoContentTypeSchema>
export type UploadPhotoRequest = z.input<typeof uploadPhotoRequestSchema>
export type PhotoUploadUrlRequest = z.input<typeof photoUploadUrlRequestSchema>
export type PhotoUploadUrlResponse = z.infer<typeof photoUploadUrlResponseSchema>
export type ConfirmPhotoRequest = z.input<typeof confirmPhotoRequestSchema>
export type PhotoResponse = z.infer<typeof photoResponseSchema>
export type HealthResponse = z.infer<typeof healthResponseSchema>
export type UpdateProfileRequest = z.input<typeof updateProfileRequestSchema>
export type ProfileResponse = z.infer<typeof profileResponseSchema>
Expand All @@ -111,4 +134,3 @@ export type LocationResponse = z.infer<typeof locationResponseSchema>
export type SavedLocationResponse = z.infer<typeof savedLocationResponseSchema>
export type DashboardResponse = z.infer<typeof dashboardResponseSchema>
export type PhotosResponse = z.infer<typeof photosResponseSchema>
export type UploadPhotoResponse = z.infer<typeof uploadPhotoResponseSchema>
1 change: 1 addition & 0 deletions shared/api-errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export const apiErrorCodeSchema = z.enum([
'already_paired',
'no_space',
'not_found',
'quota_exceeded',
'validation_failed',
'unauthorized',
'internal',
Expand Down
Loading