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
81 changes: 54 additions & 27 deletions README.md
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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 <access_token>` 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
Expand All @@ -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 <access_token>` 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).
4 changes: 3 additions & 1 deletion server/api/dashboard.get.ts
Original file line number Diff line number Diff line change
@@ -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')))
8 changes: 6 additions & 2 deletions server/api/dates/[id].delete.ts
Original file line number Diff line number Diff line change
@@ -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)
})
10 changes: 7 additions & 3 deletions server/api/dates/[id].patch.ts
Original file line number Diff line number Diff line change
@@ -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')
})
14 changes: 5 additions & 9 deletions server/api/dates/index.get.ts
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
11 changes: 8 additions & 3 deletions server/api/dates/index.post.ts
Original file line number Diff line number Diff line change
@@ -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())
})
4 changes: 3 additions & 1 deletion server/api/health.get.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export default defineEventHandler(() => ({ status: 'ok' }))
import { defineApiHandler } from '../utils/api-error'

export default defineApiHandler(() => ({ status: 'ok' }))
3 changes: 2 additions & 1 deletion server/api/location.get.ts
Original file line number Diff line number Diff line change
@@ -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]) }
Expand Down
14 changes: 8 additions & 6 deletions server/api/location.put.ts
Original file line number Diff line number Diff line change
@@ -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())
})
8 changes: 5 additions & 3 deletions server/api/photos/[name].delete.ts
Original file line number Diff line number Diff line change
@@ -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]))
Expand Down
8 changes: 5 additions & 3 deletions server/api/photos/index.get.ts
Original file line number Diff line number Diff line change
@@ -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 []
Expand Down
14 changes: 9 additions & 5 deletions server/api/photos/index.post.ts
Original file line number Diff line number Diff line change
@@ -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}))
})
4 changes: 3 additions & 1 deletion server/api/space/index.get.ts
Original file line number Diff line number Diff line change
@@ -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()))
4 changes: 3 additions & 1 deletion server/api/space/index.post.ts
Original file line number Diff line number Diff line change
@@ -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') }))
10 changes: 6 additions & 4 deletions server/api/space/join.post.ts
Original file line number Diff line number Diff line change
@@ -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') }
})
35 changes: 35 additions & 0 deletions server/utils/api-error.ts
Original file line number Diff line number Diff line change
@@ -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<ApiErrorCode, { statusCode: number; statusMessage: string }>

export function toApiError(code: ApiErrorCode, statusCode = errorDetails[code].statusCode) {
return createError({ ...errorDetails[code], statusCode, data: { code } })
}

export function defineApiHandler<Response>(handler: EventHandler<EventHandlerRequest, Response>) {
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')
}
})
}
Loading