diff --git a/README.md b/README.md index 59f6b38..d1449bb 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # Ons · Couple Planner -Nuxt 3 mit Nitro-API und Supabase (Postgres, Auth, privater Storage). Alle Zugriffe laufen mit dem Token des angemeldeten Partners und den Row-Level-Security-Regeln der Datenbank. +Ons is a Nuxt 3 app with a Nitro API and Supabase Postgres, Auth, and private Storage. The API forwards the signed-in user's token to Supabase, where row-level security controls data access. -## Lokal starten +## Local setup -Node 22.12 oder neuer, Docker und Supabase CLI installieren. Im Repository: +Install Node 22.12 or later, Docker, and the Supabase CLI. From the repository root, run: ```sh npm ci @@ -13,15 +13,15 @@ supabase migration up --local cp .env.example .env ``` -Den von `supabase status` ausgegebenen Publishable- bzw. anon-Key in `NUXT_PUBLIC_SUPABASE_KEY` eintragen. Mit `npm run dev` starten. Der lokale Auth-Dienst erlaubt Testkonten ohne Bestätigungsmail. Die Startseite verlinkt den Healthcheck. +Copy the public or anon key from `supabase status` to `NUXT_PUBLIC_SUPABASE_KEY` and start the app with `npm run dev`. Local Auth allows test signups without email confirmation. The home page links to the process health check. -Alternativ beide SQL-Migrationen in numerischer Reihenfolge im SQL Editor eines neuen Supabase-Projekts ausführen und dessen URL und öffentlichen Schlüssel eintragen. Für Vercel dieselben zwei Variablen konfigurieren, die HTTPS-Adresse in Supabase unter Auth → URL Configuration freigeben und E-Mail-Bestätigung für öffentliche Registrierungen aktivieren. Für Google-Login den Google-Provider mit Client-ID und Secret im Supabase-Dashboard aktivieren und die dort angezeigte Callback-URL in der Google-Konsole hinterlegen. +For a new hosted Supabase project, apply both SQL migrations in numerical order. Set the public Supabase URL and key in Vercel, allow the app's HTTPS origin in Supabase Auth URL Configuration, and enable email confirmation for public signups. To enable Google login, configure the Google provider in Supabase Auth and register the callback URL shown there in the Google Console. -## Auth und Demoablauf +## Auth and demo -Das Nuxt-Client-Plugin stellt den Supabase-Client als `useNuxtApp().$supabase` bereit. Registrierung über `auth.signUp({ email, password })`, Login über `auth.signInWithPassword({ email, password })`, Google über `auth.signInWithOAuth({ provider: 'google' })`, Logout über `auth.signOut()`. Supabase Auth übernimmt Passwortverarbeitung, Session-Erneuerung und Auth-Rate-Limits. Für jeden Nitro-Aufruf den aktuellen Access Token als `Authorization: Bearer ` senden. +The Nuxt plugin exposes the browser Supabase client as `useNuxtApp().$supabase`. Use `auth.signUp({ email, password })`, `auth.signInWithPassword({ email, password })`, `auth.signInWithOAuth({ provider: 'google' })`, and `auth.signOut()`. Supabase Auth handles passwords, session refresh, and rate limits. Send the current access token on protected Nitro calls. -Für einen lokalen Durchlauf ohne Frontend in Bash (curl und jq): +This local demo uses Bash, curl, and jq. ```sh source .env @@ -39,28 +39,55 @@ api() { api "$A" space -X POST CODE=$(api "$A" space | jq -r .invite) api "$B" space/join -d "$(jq -nc --arg code "$CODE" '{code:$code}')" -api "$A" dates -d '{"title":"Kinoabend","category":"cinema","meeting_at":"2027-01-15T18:00:00Z"}' +api "$A" dates -d '{"title":"Movie night","category":"cinema","meeting_at":"2027-01-15T18:00:00Z"}' api "$B" dates api "$B" dashboard ``` ## API -| Methode und Pfad unter /api | Inhalt | -| --- | --- | -| GET /health | Prozessstatus, ohne Login | -| GET /space | Eigener Raum, Mitglieder und offener Einladungscode, sonst null | -| POST /space · POST /space/join | Raum anlegen oder mit JSON-Feld code beitreten. Ein Konto pro Person, maximal zwei Mitglieder. Beitritt verbraucht den Code. | -| POST /dates | title, category, optional status (planned/done) und meeting_at (ISO-Zeit mit Zeitzone oder null) | -| GET /dates | q (Titelsuche), category, status, sort (created_at/title/meeting_at), order (asc/desc), offset. 50 Ideen je Seite. | -| PATCH /dates/:id · DELETE /dates/:id | Gemeinsame Idee ändern oder löschen | -| PUT /location | Eigenen Standort als lat und lon setzen | -| GET /location | Standorte, Luftlinie in km und geografischer Mittelpunkt. Fehlende Werte werden als null geliefert. | -| GET /dashboard | Nächstes geplantes Treffen, Serverzeit für den Countdown und Anzahl der Ideen nach Erstellmonat (UTC) und Kategorie | -| POST /photos | Bild als binären Request-Body senden. Content-Type image/jpeg, image/png oder image/webp, maximal 5 MiB (Hosting-Limit kann niedriger liegen). | -| GET /photos | Neueste Uploads zuerst, 30 pro Seite, optional offset. Bild-URLs sind fünf Minuten gültig. | -| DELETE /photos/:name | Foto anhand des von der Galerie gelieferten Namens löschen | - -## Prüfung - -`npm test` prüft die erste Migration in eingebettetem Postgres mit simulierten Supabase-Identitäten. `npm run build` erstellt den Nitro-Produktionsbuild. Der Datenbanktest deckt Einmalcode, Raumgrenze, gemeinsam sichtbare Termine, Standortbesitz und die Trennung fremder Räume ab. Für einen vollständigen Integrationstest werden laufende Auth- und Storage-Dienste benötigt. +Send `Authorization: Bearer ` on authenticated routes and `Accept: application/json` to request JSON errors. The request and response schemas and their TypeScript types are exported from [shared/api-contract.ts](shared/api-contract.ts). The error schema and `ApiErrorCode` are exported from [shared/api-errors.ts](shared/api-errors.ts). + +| Method and path | Auth | Request | Success | Error codes | +| --- | --- | --- | --- | --- | +| `GET /api/health` | Public | — | `200` with process status `{"status":"ok"}` | `internal` | +| `GET /api/space` | Bearer | — | `200` with `id`, `invite`, and `members`, or `204` when unpaired | `unauthorized`, `internal` | +| `POST /api/space` | Bearer | — | `200` with the new space `id` | `already_paired`, `unauthorized`, `internal` | +| `POST /api/space/join` | Bearer | JSON `code`, 32 lowercase hex characters | `200` with the joined space `id`. Joining consumes the invite. | `invite_invalid`, `already_paired`, `validation_failed`, `unauthorized`, `internal` | +| `GET /api/dates` | Bearer | Optional `q`, `category`, `status`, `sort`, `order`, `offset` | `200` with up to 50 date rows | `validation_failed`, `unauthorized`, `internal` | +| `POST /api/dates` | Bearer | JSON `title`, `category`, optional `status` and `meeting_at` | `200` with the created date row | `validation_failed`, `no_space`, `unauthorized`, `internal` | +| `PATCH /api/dates/:id` | Bearer | UUID `id` and at least one writable date field | `200` with the updated date row | `validation_failed`, `not_found`, `unauthorized`, `internal` | +| `DELETE /api/dates/:id` | Bearer | UUID `id` | `204` | `validation_failed`, `not_found`, `unauthorized`, `internal` | +| `GET /api/location` | Bearer | — | `200` with `partners`, `distanceKm`, and `midpoint`. Unavailable derived values are null. | `unauthorized`, `internal` | +| `PUT /api/location` | Bearer | JSON `lat` and `lon` | `200` with the saved location row | `validation_failed`, `no_space`, `unauthorized`, `internal` | +| `GET /api/dashboard` | Bearer | — | `200` with `serverTime`, `nextMeeting`, and `categoriesByMonth` using UTC months | `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` | + +### 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. | +| `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. | +| `unauthorized` | 401 | The access token is missing or rejected. | +| `internal` | 500, 503 | An unexpected server failure occurred or a dependency is unavailable. | + +A `PATCH /api/dates/not-a-uuid` request with `{"title":"Movie night"}` returns HTTP 400. The contract fields in the JSON response are: + +```json +{ + "statusCode": 400, + "data": { "code": "validation_failed" } +} +``` + +Map `data.code` to a translated message and keep the `401` sign-in handling. Failures generated by infrastructure, such as a hosting upload limit, can arrive without this envelope. Use a generic translated fallback in that case. + +## Verification + +`npm test` runs Vitest, including PGlite tests for all migrations, geo unit tests, and HTTP contract tests with a simulated Supabase transport. `npm run build` creates the production Nitro build. Real Auth and Storage smoke test results are in [docs/SMOKE_TEST.md](docs/SMOKE_TEST.md). diff --git a/server/api/dashboard.get.ts b/server/api/dashboard.get.ts index 668fff7..21d1194 100644 --- a/server/api/dashboard.get.ts +++ b/server/api/dashboard.get.ts @@ -1 +1,3 @@ -export default defineEventHandler(async event => result(await client(event).rpc('dashboard'))) +import { defineApiHandler } from '../utils/api-error' + +export default defineApiHandler(async event => result(await client(event).rpc('dashboard'))) diff --git a/server/api/dates/[id].delete.ts b/server/api/dates/[id].delete.ts index 061054e..d35455e 100644 --- a/server/api/dates/[id].delete.ts +++ b/server/api/dates/[id].delete.ts @@ -1,4 +1,8 @@ -export default defineEventHandler(async event => { - result(await client(event).from('dates').delete().eq('id',getRouterParam(event,'id')).select('id').single()) +import { defineApiHandler } from '../../utils/api-error' +import { dateParamsSchema } from '../../../shared/api-contract' + +export default defineApiHandler(async event => { + const { id } = await getValidatedRouterParams(event, dateParamsSchema.parse) + result(await client(event).from('dates').delete().eq('id', id).select('id').single(), 'mutateDate') return sendNoContent(event) }) diff --git a/server/api/dates/[id].patch.ts b/server/api/dates/[id].patch.ts index 7d5ea8e..b7253ee 100644 --- a/server/api/dates/[id].patch.ts +++ b/server/api/dates/[id].patch.ts @@ -1,4 +1,8 @@ -export default defineEventHandler(async event => { - const body = await readValidatedBody(event, dateFields.partial().refine(v => Object.keys(v).length > 0).parse) - return result(await client(event).from('dates').update(body).eq('id',getRouterParam(event,'id')).select().single()) +import { defineApiHandler } from '../../utils/api-error' +import { dateParamsSchema, updateDateRequestSchema } from '../../../shared/api-contract' + +export default defineApiHandler(async event => { + const { id } = await getValidatedRouterParams(event, dateParamsSchema.parse) + const body = await readValidatedBody(event, updateDateRequestSchema.parse) + return result(await client(event).from('dates').update(body).eq('id', id).select().single(), 'mutateDate') }) diff --git a/server/api/dates/index.get.ts b/server/api/dates/index.get.ts index c02b4ab..1421887 100644 --- a/server/api/dates/index.get.ts +++ b/server/api/dates/index.get.ts @@ -1,12 +1,8 @@ -import { z } from 'zod' -export default defineEventHandler(async event => { - const q = await getValidatedQuery(event, z.object({ - q: z.string().max(160).optional(), category: z.string().optional(), - status: z.enum(['planned','done']).optional(), - sort: z.enum(['title','meeting_at','created_at']).default('created_at'), - order: z.enum(['asc','desc']).default('desc'), - offset: z.coerce.number().int().nonnegative().default(0) - }).parse) +import { datesQuerySchema } from '../../../shared/api-contract' +import { defineApiHandler } from '../../utils/api-error' + +export default defineApiHandler(async event => { + const q = await getValidatedQuery(event, datesQuerySchema.parse) let query = client(event).from('dates').select() if (q.q) query = query.ilike('title', '%' + q.q.replace(/[\\%_]/g, '\\$&') + '%') if (q.category) query = query.eq('category', q.category) diff --git a/server/api/dates/index.post.ts b/server/api/dates/index.post.ts index a1fb7c5..459e70d 100644 --- a/server/api/dates/index.post.ts +++ b/server/api/dates/index.post.ts @@ -1,4 +1,9 @@ -export default defineEventHandler(async event => { - const body = await readValidatedBody(event, dateFields.parse) - return result(await client(event).from('dates').insert(body).select().single()) +import { defineApiHandler } from '../../utils/api-error' +import { createDateRequestSchema } from '../../../shared/api-contract' + +export default defineApiHandler(async event => { + const body = await readValidatedBody(event, createDateRequestSchema.parse) + const db = client(event) + await room(db) + return result(await db.from('dates').insert(body).select().single()) }) diff --git a/server/api/health.get.ts b/server/api/health.get.ts index e861a89..4e13256 100644 --- a/server/api/health.get.ts +++ b/server/api/health.get.ts @@ -1 +1,3 @@ -export default defineEventHandler(() => ({ status: 'ok' })) +import { defineApiHandler } from '../utils/api-error' + +export default defineApiHandler(() => ({ status: 'ok' })) diff --git a/server/api/location.get.ts b/server/api/location.get.ts index df51b84..48768eb 100644 --- a/server/api/location.get.ts +++ b/server/api/location.get.ts @@ -1,6 +1,7 @@ +import { defineApiHandler } from '../utils/api-error' import { distanceAndMidpoint } from '../utils/geo' -export default defineEventHandler(async event => { +export default defineApiHandler(async event => { const partners = result(await client(event).from('locations').select('user_id,lat,lon').order('user_id')) ?? [] if (partners.length !== 2) return { partners, distanceKm: null, midpoint: null } return { partners, ...distanceAndMidpoint(partners[0], partners[1]) } diff --git a/server/api/location.put.ts b/server/api/location.put.ts index d07ce35..a0eac86 100644 --- a/server/api/location.put.ts +++ b/server/api/location.put.ts @@ -1,7 +1,9 @@ -import { z } from 'zod' -export default defineEventHandler(async event => { - const coords = await readValidatedBody(event, z.strictObject({ - lat: z.number().min(-90).max(90), lon: z.number().min(-180).max(180) - }).parse) - return result(await client(event).from('locations').upsert(coords, { onConflict: 'user_id' }).select().single()) +import { defineApiHandler } from '../utils/api-error' +import { updateLocationRequestSchema } from '../../shared/api-contract' + +export default defineApiHandler(async event => { + const coords = await readValidatedBody(event, updateLocationRequestSchema.parse) + const db = client(event) + await room(db) + return result(await db.from('locations').upsert(coords, { onConflict: 'user_id' }).select().single()) }) diff --git a/server/api/photos/[name].delete.ts b/server/api/photos/[name].delete.ts index f2901c1..caef3b7 100644 --- a/server/api/photos/[name].delete.ts +++ b/server/api/photos/[name].delete.ts @@ -1,6 +1,8 @@ -import { z } from 'zod' -export default defineEventHandler(async event => { - const { name } = await getValidatedRouterParams(event,z.object({name:z.uuid()}).parse) +import { defineApiHandler } 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])) diff --git a/server/api/photos/index.get.ts b/server/api/photos/index.get.ts index d952ab0..8b053e3 100644 --- a/server/api/photos/index.get.ts +++ b/server/api/photos/index.get.ts @@ -1,8 +1,10 @@ -import { z } from 'zod' -export default defineEventHandler(async event => { +import { photosQuerySchema } from '../../../shared/api-contract' +import { defineApiHandler } from '../../utils/api-error' + +export default defineApiHandler(async event => { const db = client(event) const space = await room(db) - const { offset } = await getValidatedQuery(event,z.object({offset:z.coerce.number().int().nonnegative().default(0)}).parse) + const { offset } = await getValidatedQuery(event, photosQuerySchema.parse) const gallery = db.storage.from('gallery') const files = result(await gallery.list(space,{offset,limit:30,sortBy:{column:'created_at',order:'desc'}})) ?? [] if (!files.length) return [] diff --git a/server/api/photos/index.post.ts b/server/api/photos/index.post.ts index e039e13..0443cf9 100644 --- a/server/api/photos/index.post.ts +++ b/server/api/photos/index.post.ts @@ -1,22 +1,26 @@ import { randomUUID } from 'node:crypto' -export default defineEventHandler(async event => { +import { photoContentTypeSchema, photoUploadMaxBytes } from '../../../shared/api-contract' +import { defineApiHandler, toApiError } from '../../utils/api-error' + +export default defineApiHandler(async event => { const db = client(event) const space = await room(db) - const mime = getHeader(event,'content-type') - if (!['image/jpeg','image/png','image/webp'].includes(mime ?? '')) throw createError({statusCode:415}) + const mediaType = photoContentTypeSchema.safeParse(getHeader(event, 'content-type')) + if (!mediaType.success) throw toApiError('validation_failed', 415) + const mime = mediaType.data const chunks: Buffer[] = [] let length = 0 for await (const chunk of event.node.req) { const bytes = Buffer.from(chunk) length += bytes.length - if (length > 5 * 1024 * 1024) throw createError({statusCode:413}) + if (length > photoUploadMaxBytes) throw toApiError('validation_failed', 413) chunks.push(bytes) } const bytes = Buffer.concat(chunks) const valid = mime === 'image/jpeg' ? bytes.subarray(0,3).equals(Buffer.from([255,216,255])) : mime === 'image/png' ? bytes.subarray(0,8).equals(Buffer.from('89504e470d0a1a0a','hex')) : bytes.toString('ascii',0,4) === 'RIFF' && bytes.toString('ascii',8,12) === 'WEBP' - if (!valid) throw createError({statusCode:415}) + if (!valid) throw toApiError('validation_failed', 415) const path = space + '/' + randomUUID() return result(await db.storage.from('gallery').upload(path,bytes,{contentType:mime})) }) diff --git a/server/api/space/index.get.ts b/server/api/space/index.get.ts index 1417da2..0b2b74d 100644 --- a/server/api/space/index.get.ts +++ b/server/api/space/index.get.ts @@ -1 +1,3 @@ -export default defineEventHandler(async event => result(await client(event).from('spaces').select('id,invite,members(user_id,slot)').maybeSingle())) +import { defineApiHandler } from '../../utils/api-error' + +export default defineApiHandler(async event => result(await client(event).from('spaces').select('id,invite,members(user_id,slot)').maybeSingle())) diff --git a/server/api/space/index.post.ts b/server/api/space/index.post.ts index f1fe809..52dc06c 100644 --- a/server/api/space/index.post.ts +++ b/server/api/space/index.post.ts @@ -1 +1,3 @@ -export default defineEventHandler(async event => ({ id: result(await client(event).rpc('create_space')) })) +import { defineApiHandler } from '../../utils/api-error' + +export default defineApiHandler(async event => ({ id: result(await client(event).rpc('create_space'), 'createSpace') })) diff --git a/server/api/space/join.post.ts b/server/api/space/join.post.ts index 5b75de1..c880029 100644 --- a/server/api/space/join.post.ts +++ b/server/api/space/join.post.ts @@ -1,5 +1,7 @@ -import { z } from 'zod' -export default defineEventHandler(async event => { - const body = await readValidatedBody(event, z.strictObject({ code: z.string().regex(/^[a-f0-9]{32}$/) }).parse) - return { id: result(await client(event).rpc('join_space', body)) } +import { defineApiHandler } from '../../utils/api-error' +import { joinSpaceRequestSchema } from '../../../shared/api-contract' + +export default defineApiHandler(async event => { + const body = await readValidatedBody(event, joinSpaceRequestSchema.parse) + return { id: result(await client(event).rpc('join_space', body), 'joinSpace') } }) diff --git a/server/utils/api-error.ts b/server/utils/api-error.ts new file mode 100644 index 0000000..fe52234 --- /dev/null +++ b/server/utils/api-error.ts @@ -0,0 +1,35 @@ +import { createError, defineEventHandler, isError, type EventHandler, type EventHandlerRequest } from 'h3' +import { apiErrorCodeSchema, type ApiErrorCode } from '../../shared/api-errors' + +const errorDetails = { + invite_invalid: { statusCode: 400, statusMessage: 'Invalid or used invitation' }, + 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' }, + validation_failed: { statusCode: 400, statusMessage: 'Validation failed' }, + unauthorized: { statusCode: 401, statusMessage: 'Unauthorized' }, + internal: { statusCode: 500, statusMessage: 'Internal server error' }, +} satisfies Record + +export function toApiError(code: ApiErrorCode, statusCode = errorDetails[code].statusCode) { + return createError({ ...errorDetails[code], statusCode, data: { code } }) +} + +export function defineApiHandler(handler: EventHandler) { + return defineEventHandler(async event => { + try { + return await handler(event) + } catch (error) { + if (isError(error)) { + if (apiErrorCodeSchema.safeParse(error.data?.code).success) { + throw error + } + if (error.statusCode === 400 || error.statusCode === 413 || error.statusCode === 415) { + throw toApiError('validation_failed', error.statusCode) + } + } + console.error('Unexpected API handler failure', error) + throw toApiError('internal') + } + }) +} diff --git a/server/utils/backend.ts b/server/utils/backend.ts index 74be489..985788c 100644 --- a/server/utils/backend.ts +++ b/server/utils/backend.ts @@ -1,36 +1,56 @@ import { createClient } from '@supabase/supabase-js' -import type { H3Event } from 'h3' -import { z } from 'zod' +import { getHeader, type H3Event } from 'h3' +import { toApiError } from './api-error' export function client(event: H3Event) { const { supabaseUrl, supabaseKey } = useRuntimeConfig(event).public - if (!supabaseUrl || !supabaseKey) throw createError({ statusCode: 503, statusMessage: 'Configure Supabase first' }) + if (!supabaseUrl || !supabaseKey) { + console.error('Supabase runtime configuration is missing') + throw toApiError('internal', 503) + } const authorization = getHeader(event, 'authorization') - if (!authorization?.startsWith('Bearer ')) throw createError({ statusCode: 401 }) + if (!authorization || !/^Bearer \S+$/i.test(authorization)) { + throw toApiError('unauthorized') + } return createClient(supabaseUrl, supabaseKey, { auth: { persistSession: false, autoRefreshToken: false }, global: { headers: { Authorization: authorization } } }) } -export function result(response: { data: T, error: { code?: string, message: string } | null, status?: number }) { - if (response.error) { - const { code } = response.error - const statusCode = code === '23505' ? 409 : code === '22023' ? 400 : code === 'PGRST116' ? 404 : response.status || 500 - throw createError({ statusCode, statusMessage: statusCode === 409 ? 'Already paired' : 'Request failed' }) +type SupabaseResult = { + data: T + error: { code?: string; message: string; status?: number; statusCode?: string } | null + status?: number +} + +export function result(response: SupabaseResult, operation?: 'createSpace' | 'joinSpace' | 'mutateDate') { + if (!response.error) { + return response.data + } + + const { code, status, statusCode } = response.error + if (response.status === 401 || status === 401 || statusCode === '401') { + throw toApiError('unauthorized') } - return response.data + if (operation === 'joinSpace' && code === '22023') { + throw toApiError('invite_invalid') + } + if ((operation === 'joinSpace' || operation === 'createSpace') && code === '23505') { + throw toApiError('already_paired') + } + if (operation === 'mutateDate' && code === 'PGRST116') { + throw toApiError('not_found') + } + + console.error('Unexpected Supabase request failure', response.error) + throw toApiError('internal', response.status === 503 || status === 503 || statusCode === '503' ? 503 : 500) } export async function room(db: ReturnType) { const id = result(await db.rpc('my_space')) - if (!id) throw createError({ statusCode: 403, statusMessage: 'Join or create a space first' }) + if (!id) { + throw toApiError('no_space') + } return String(id) } - -export const dateFields = z.strictObject({ - title: z.string().trim().min(1).max(160), - category: z.string().trim().min(1).max(60), - status: z.enum(['planned','done']).optional(), - meeting_at: z.iso.datetime({ offset: true }).nullable().optional() -}) diff --git a/shared/api-contract.ts b/shared/api-contract.ts new file mode 100644 index 0000000..6b69203 --- /dev/null +++ b/shared/api-contract.ts @@ -0,0 +1,100 @@ +import { z } from 'zod' + +const uuid = z.uuid() +const timestamp = z.iso.datetime({ offset: true }) +const invite = z.string().regex(/^[a-f0-9]{32}$/) +const dateStatus = z.enum(['planned', 'done']) +const offset = z.coerce.number().int().nonnegative().default(0) +const coordinates = { + lat: z.number().min(-90).max(90), + lon: z.number().min(-180).max(180), +} + +export const joinSpaceRequestSchema = z.strictObject({ code: invite }) +export const createDateRequestSchema = z.strictObject({ + title: z.string().trim().min(1).max(160), + category: z.string().trim().min(1).max(60), + status: dateStatus.optional(), + meeting_at: timestamp.nullable().optional(), +}) +export const updateDateRequestSchema = createDateRequestSchema.partial().refine(value => Object.keys(value).length > 0) +export const dateParamsSchema = z.object({ id: uuid }) +export const datesQuerySchema = z.object({ + q: z.string().max(160).optional(), + category: z.string().optional(), + status: dateStatus.optional(), + sort: z.enum(['title', 'meeting_at', 'created_at']).default('created_at'), + order: z.enum(['asc', 'desc']).default('desc'), + offset, +}) +export const updateLocationRequestSchema = z.strictObject(coordinates) +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 healthResponseSchema = z.object({ status: z.literal('ok') }) +export const spaceIdResponseSchema = z.object({ id: uuid }) +export const spaceResponseSchema = spaceIdResponseSchema.extend({ + invite: invite.nullable(), + members: z.array(z.object({ user_id: uuid, slot: z.union([z.literal(1), z.literal(2)]) })), +}) +export const noContentResponseSchema = z.literal('') +export const dateResponseSchema = z.object({ + id: uuid, + space_id: uuid, + title: z.string(), + category: z.string(), + status: dateStatus, + meeting_at: timestamp.nullable(), + created_at: timestamp, +}) +export const datesResponseSchema = z.array(dateResponseSchema) +const partnerLocationSchema = z.object({ user_id: uuid, ...coordinates }) +export const locationResponseSchema = z.object({ + partners: z.array(partnerLocationSchema), + distanceKm: z.number().nullable(), + midpoint: z.object(coordinates).nullable(), +}) +export const savedLocationResponseSchema = partnerLocationSchema.extend({ space_id: uuid }) +export const dashboardResponseSchema = z.object({ + serverTime: timestamp, + nextMeeting: dateResponseSchema.nullable(), + categoriesByMonth: z.array(z.object({ + month: z.string().regex(/^\d{4}-\d{2}$/), + category: z.string(), + total: z.number().int().nonnegative(), + })), +}) +export const photosResponseSchema = z.array(z.object({ + name: uuid, + createdAt: timestamp, + url: z.url().nullish(), +})) +export const uploadPhotoResponseSchema = z.object({ id: uuid, path: z.string(), fullPath: z.string() }) + +export type JoinSpaceRequest = z.input +export type CreateDateRequest = z.input +export type UpdateDateRequest = z.input +export type DateParams = z.input +export type DatesQuery = z.input +export type UpdateLocationRequest = z.input +export type PhotosQuery = z.input +export type PhotoParams = z.input +export type PhotoContentType = z.infer +export type UploadPhotoRequest = z.input +export type HealthResponse = z.infer +export type SpaceIdResponse = z.infer +export type SpaceResponse = z.infer +export type NoContentResponse = z.infer +export type DateResponse = z.infer +export type DatesResponse = z.infer +export type LocationResponse = z.infer +export type SavedLocationResponse = z.infer +export type DashboardResponse = z.infer +export type PhotosResponse = z.infer +export type UploadPhotoResponse = z.infer diff --git a/shared/api-errors.ts b/shared/api-errors.ts new file mode 100644 index 0000000..001b5ad --- /dev/null +++ b/shared/api-errors.ts @@ -0,0 +1,19 @@ +import { z } from 'zod' + +export const apiErrorCodeSchema = z.enum([ + 'invite_invalid', + 'already_paired', + 'no_space', + 'not_found', + 'validation_failed', + 'unauthorized', + 'internal', +]) + +export const apiErrorResponseSchema = z.object({ + statusCode: z.number().int(), + data: z.object({ code: apiErrorCodeSchema }), +}) + +export type ApiErrorCode = z.infer +export type ApiErrorResponse = z.infer diff --git a/tests/api-errors.test.ts b/tests/api-errors.test.ts new file mode 100644 index 0000000..f82c4b1 --- /dev/null +++ b/tests/api-errors.test.ts @@ -0,0 +1,217 @@ +import { createServer } from 'node:http' +import { once } from 'node:events' +import type { AddressInfo } from 'node:net' +import * as h3 from 'h3' +import { afterAll, beforeAll, beforeEach, expect, test, vi } from 'vitest' +import { apiErrorResponseSchema } from '../shared/api-errors' +import * as contract from '../shared/api-contract' +import * as backend from '../server/utils/backend' + +const id = '36ac3324-27c7-4867-91ba-8d73375eacaa' +const invite = '0123456789abcdef0123456789abcdef' +const secret = 'private upstream diagnostic' +const upstream = vi.fn() +let configured = true +const fetchHttp = globalThis.fetch +let server: ReturnType +let origin: string + +const now = '2026-11-26T10:00:00+00:00' +const coordinates = { lat: 52, lon: 12 } +const partner = { user_id: id, ...coordinates } +const date = { id, space_id: id, title: 'Cinema', category: 'film', status: 'planned', meeting_at: null, created_at: now } +const space = { id, invite, members: [{ user_id: id, slot: 1 }] } +const dashboard = { serverTime: now, nextMeeting: null, categoriesByMonth: [{ month: '2026-11', category: 'film', total: 1 }] } +const photo = { id, path: id + '/' + id, fullPath: 'gallery/' + id + '/' + id } + +beforeAll(async () => { + for (const name of ['defineEventHandler', 'createError', 'getHeader', 'getRouterParam', 'getValidatedRouterParams', 'getValidatedQuery', 'readValidatedBody', 'sendNoContent'] as const) { + vi.stubGlobal(name, h3[name]) + } + for (const [name, value] of Object.entries(backend)) { + vi.stubGlobal(name, value) + } + vi.stubGlobal('useRuntimeConfig', () => ({ + public: configured ? { supabaseUrl: 'http://supabase.test', supabaseKey: 'public-key' } : {}, + })) + vi.stubGlobal('fetch', upstream) + + const router = h3.createRouter() + router.get('/api/health', (await import('../server/api/health.get')).default) + router.get('/api/space', (await import('../server/api/space/index.get')).default) + router.post('/api/space', (await import('../server/api/space/index.post')).default) + router.post('/api/space/join', (await import('../server/api/space/join.post')).default) + router.get('/api/dates', (await import('../server/api/dates/index.get')).default) + router.post('/api/dates', (await import('../server/api/dates/index.post')).default) + router.patch('/api/dates/:id', (await import('../server/api/dates/[id].patch')).default) + router.delete('/api/dates/:id', (await import('../server/api/dates/[id].delete')).default) + router.put('/api/location', (await import('../server/api/location.put')).default) + router.get('/api/location', (await import('../server/api/location.get')).default) + router.get('/api/dashboard', (await import('../server/api/dashboard.get')).default) + router.post('/api/photos', (await import('../server/api/photos/index.post')).default) + router.get('/api/photos', (await import('../server/api/photos/index.get')).default) + router.delete('/api/photos/:name', (await import('../server/api/photos/[name].delete')).default) + server = createServer(h3.toNodeListener(h3.createApp().use(router))).listen(0, '127.0.0.1') + await once(server, 'listening') + origin = 'http://127.0.0.1:' + (server.address() as AddressInfo).port +}) + +afterAll(async () => { + vi.unstubAllGlobals() + if (server?.listening) { + await new Promise((resolve, reject) => { + server.close(error => error ? reject(error) : resolve()) + }) + } +}) + +beforeEach(() => { + configured = true + upstream.mockReset().mockRejectedValue(new Error(secret)) +}) + +function postgresError(code: string, status: number) { + upstream.mockResolvedValueOnce(Response.json({ code, message: secret }, { status })) +} + +function request(method: string, path: string, body?: BodyInit, token = true, contentType = 'application/json') { + const headers = new Headers({ accept: 'application/json', 'content-type': contentType }) + if (token) { + headers.set('authorization', 'Bearer test-token') + } + return fetchHttp(origin + '/api' + path, { method, body, headers }) +} + +async function expectError(response: Response, status: number, code: string) { + expect(response.status).toBe(status) + const json = await response.json() + expect(apiErrorResponseSchema.parse(json)).toEqual({ statusCode: status, data: { code } }) + expect(JSON.stringify(json)).not.toContain(secret) +} + +test('returns invite_invalid for a well-formed, rejected invite', async () => { + postgresError('22023', 400) + await expectError(await request('POST', '/space/join', JSON.stringify({ code: invite })), 400, 'invite_invalid') +}) + +test.each(['/space', '/space/join'])('returns already_paired for membership conflicts on %s', async (path) => { + postgresError('23505', 409) + const body = path.endsWith('/join') ? JSON.stringify({ code: invite }) : undefined + await expectError(await request('POST', path, body), 409, 'already_paired') +}) + +test.each([ + ['POST', '/dates', { title: 'Cinema', category: 'film' }], + ['PUT', '/location', { lat: 52, lon: 12 }], +] as const)('returns no_space for an unpaired %s %s', async (method, path, body) => { + upstream.mockImplementation(async input => { + if (String(input).endsWith('/rpc/my_space')) return Response.json(null) + return Response.json({ code: '42501', message: secret }, { status: 403 }) + }) + await expectError(await request(method, path, JSON.stringify(body)), 403, 'no_space') + expect(upstream).toHaveBeenCalledTimes(1) +}) + +test('returns not_found for a missing or inaccessible date', async () => { + postgresError('PGRST116', 406) + await expectError(await request('DELETE', '/dates/' + id), 404, 'not_found') +}) + +test.each([ + ['PATCH', '/dates/not-a-uuid', '{"title":"Cinema"}'], + ['DELETE', '/dates/not-a-uuid'], + ['DELETE', '/photos/not-a-uuid'], + ['GET', '/dates?offset=-1'], + ['POST', '/space/join', '{"code":"bad"}'], + ['POST', '/dates', '{'], +])('returns validation_failed for an invalid %s %s', async (method, path, body) => { + await expectError(await request(method, path, body), 400, 'validation_failed') + expect(upstream).not.toHaveBeenCalled() +}) + +test('returns validation_failed and retains 415 for unsupported photo media', async () => { + upstream.mockResolvedValueOnce(Response.json(id)) + await expectError(await request('POST', '/photos', 'plain text', true, 'text/plain'), 415, 'validation_failed') +}) + +test('returns validation_failed and retains 413 for oversized photos', async () => { + upstream.mockResolvedValueOnce(Response.json(id)) + const body = new Uint8Array(5 * 1024 * 1024 + 1) + await expectError(await request('POST', '/photos', body, true, 'image/png'), 413, 'validation_failed') +}) + +test('returns unauthorized for missing and rejected bearer tokens', async () => { + await expectError(await request('GET', '/dashboard', undefined, false), 401, 'unauthorized') + expect(upstream).not.toHaveBeenCalled() + postgresError('PGRST301', 401) + await expectError(await request('GET', '/dashboard'), 401, 'unauthorized') +}) + +test('returns internal when Supabase configuration is unavailable', async () => { + configured = false + await expectError(await request('GET', '/dashboard'), 503, 'internal') +}) + +test('returns internal for unexpected upstream errors without claiming a pairing conflict', async () => { + postgresError('23505', 409) + await expectError(await request('GET', '/dashboard'), 500, 'internal') +}) + +test.each([ + { method: 'GET', path: '/health', schema: contract.healthResponseSchema, upstreamData: [] }, + { method: 'GET', path: '/space', schema: contract.spaceResponseSchema, upstreamData: [space] }, + { method: 'POST', path: '/space', schema: contract.spaceIdResponseSchema, upstreamData: [id] }, + { method: 'POST', path: '/space/join', schema: contract.spaceIdResponseSchema, upstreamData: [id], body: { code: invite } }, + { method: 'GET', path: '/dates', schema: contract.datesResponseSchema, upstreamData: [[date]] }, + { method: 'POST', path: '/dates', schema: contract.dateResponseSchema, upstreamData: [id, date], body: { title: 'Cinema', category: 'film' } }, + { method: 'PATCH', path: '/dates/' + id, schema: contract.dateResponseSchema, upstreamData: [date], body: { title: 'Cinema' } }, + { method: 'GET', path: '/location', schema: contract.locationResponseSchema, upstreamData: [[partner]] }, + { method: 'PUT', path: '/location', schema: contract.savedLocationResponseSchema, upstreamData: [id, { ...partner, space_id: id }], body: coordinates }, + { method: 'GET', path: '/dashboard', schema: contract.dashboardResponseSchema, upstreamData: [dashboard] }, + { + method: 'GET', + path: '/photos', + schema: contract.photosResponseSchema, + upstreamData: [ + id, + [{ name: id, created_at: now }], + [{ path: photo.path, error: null, signedURL: '/object/sign/' + photo.fullPath + '?token=test' }], + ], + }, +])('$method $path matches its shared response schema', async ({ method, path, schema, upstreamData, body }) => { + for (const data of upstreamData) { + upstream.mockResolvedValueOnce(Response.json(data)) + } + const response = await request(method, path, body === undefined ? undefined : JSON.stringify(body)) + expect(response.status).toBe(200) + schema.parse(await response.json()) +}) + +test('photo uploads match the shared response schema', async () => { + upstream.mockResolvedValueOnce(Response.json(id)) + upstream.mockImplementationOnce(async input => { + const key = new URL(String(input)).pathname.split('/object/')[1] + return Response.json({ Id: photo.id, Key: key }) + }) + const png = Uint8Array.from(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aE1sAAAAASUVORK5CYII=', 'base64')) + const uploadRequest = contract.uploadPhotoRequestSchema.parse({ body: png, contentType: 'image/png' }) + const response = await request('POST', '/photos', uploadRequest.body, true, uploadRequest.contentType) + expect(response.status).toBe(200) + const upload = contract.uploadPhotoResponseSchema.parse(await response.json()) + expect(upload.id).toBe(photo.id) + expect(upload.path).toMatch(new RegExp('^' + id + '/[a-f0-9-]{36}$')) + expect(upload.fullPath).toBe('gallery/' + upload.path) +}) + +test.each([ + { method: 'GET', path: '/space', upstreamData: [null] }, + { method: 'DELETE', path: '/dates/' + id, upstreamData: [{ id }] }, + { method: 'DELETE', path: '/photos/' + id, upstreamData: [id, []] }, +])('$method $path returns the shared empty response', async ({ method, path, upstreamData }) => { + for (const data of upstreamData) { + upstream.mockResolvedValueOnce(Response.json(data)) + } + const response = await request(method, path) + expect(response.status).toBe(204) + contract.noContentResponseSchema.parse(await response.text()) +})