diff --git a/.claude/launch.json b/.claude/launch.json new file mode 100644 index 0000000..0ff6b9b --- /dev/null +++ b/.claude/launch.json @@ -0,0 +1,11 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "dev", + "runtimeExecutable": "pnpm", + "runtimeArgs": ["dev", "--ui=stream"], + "port": 3000 + } + ] +} diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..dcada95 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,17 @@ +# Kept out of what `docker build` is sent: nothing here belongs in an image. +**/node_modules +**/dist +**/.turbo +**/.tanstack +**/.output +**/.storage +**/*.tsbuildinfo +# Secrets and local settings; the examples carry no values. +**/.env* +!**/.env.example +.git +.github +.claude +**/.claude +deploy +docker-compose*.yml diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..4713544 --- /dev/null +++ b/.env.example @@ -0,0 +1,28 @@ +# Settings for docker-compose.yml (production). Copy to .env on the server +# and fill in; .env is never committed. Development doesn't use this file: +# see apps/api/.env.example and apps/web/.env.example. + +# The name people open. It, api. and livekit. must all point at this +# server (three A records, or one plus a wildcard). +DOMAIN=example.com + +# Letters and digits only, since it becomes part of a URL: openssl rand -hex 24 +POSTGRES_PASSWORD= +# Signs session cookies: openssl rand -base64 32 +BETTER_AUTH_SECRET= + +# A key pair of your own making for the call server. The secret needs at +# least 32 characters: openssl rand -hex 24 +LIVEKIT_API_KEY=electro4ort +LIVEKIT_API_SECRET= + +# Uploaded files are kept in a Docker volume unless an S3 bucket (or anything +# that speaks S3) is given. Its CORS rules must allow PUT and GET from +# https:// with the Content-Type header. +# STORAGE_DRIVER=s3 +# S3_BUCKET= +# S3_REGION= +# S3_ENDPOINT= +# S3_FORCE_PATH_STYLE=true +# S3_ACCESS_KEY_ID= +# S3_SECRET_ACCESS_KEY= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..0b3ce32 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,94 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +# A newer push to the same branch makes the older run pointless. +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + checks: + name: Lint, types, build, tests + runs-on: ubuntu-latest + timeout-minutes: 15 + services: + postgres: + image: postgres:19-alpine + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: electro4ort + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U postgres -d electro4ort" + --health-interval 5s + --health-timeout 5s + --health-retries 10 + redis: + image: redis:8-alpine + ports: + - 6379:6379 + options: >- + --health-cmd "redis-cli ping" + --health-interval 5s + --health-timeout 5s + --health-retries 10 + env: + # What apps/api needs to start; the e2e tests run against the services + # above. Nothing here is used outside this run. + DATABASE_URL: postgres://postgres:postgres@localhost:5432/electro4ort + REDIS_URL: redis://localhost:6379 + BETTER_AUTH_URL: http://localhost:3001 + TRUSTED_ORIGINS: http://localhost:3000 + steps: + - uses: actions/checkout@v5 + # The version comes from "packageManager" in package.json. + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v5 + with: + node-version: 24 + cache: pnpm + - run: pnpm install --frozen-lockfile + - name: A signing secret for this run + run: echo "BETTER_AUTH_SECRET=$(openssl rand -base64 32)" >> "$GITHUB_ENV" + - name: Lint, typecheck and build everything + run: pnpm turbo run lint typecheck build + - name: Unit tests + run: pnpm turbo run test + - name: Apply migrations + run: pnpm --filter api db:migrate + - name: API end-to-end tests + run: pnpm --filter api test:e2e + + images: + name: Docker images build + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v5 + - uses: docker/setup-buildx-action@v3 + - name: API image + uses: docker/build-push-action@v6 + with: + context: . + target: api + push: false + cache-from: type=gha,scope=api + cache-to: type=gha,scope=api,mode=max + - name: Web image + uses: docker/build-push-action@v6 + with: + context: . + target: web + push: false + build-args: VITE_API_URL=https://api.example.com + cache-from: type=gha,scope=web + cache-to: type=gha,scope=web,mode=max diff --git a/.gitignore b/.gitignore index b734661..9593564 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ dist dist-ssr *.local .env* +!.env.example .nitro .tanstack .wrangler @@ -17,3 +18,6 @@ todos.json # typescript *.tsbuildinfo + +# files uploaded to the API during development +.storage diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..c3c484b --- /dev/null +++ b/Dockerfile @@ -0,0 +1,72 @@ +# syntax=docker/dockerfile:1 +# Both images, built from the repo root: +# docker build --target api -t electro4ort-api . +# docker build --target web --build-arg VITE_API_URL=https://api.example.com -t electro4ort-web . +# docker-compose.yml does this for you. + +FROM node:24-alpine AS base +ENV PNPM_HOME=/pnpm +ENV PATH=$PNPM_HOME:$PATH +# The pnpm version comes from "packageManager" in package.json. +RUN corepack enable +WORKDIR /repo + +# Everything installed and the shared packages built, once for both images. +FROM base AS workspace +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ +COPY apps/api/package.json apps/api/ +COPY apps/web/package.json apps/web/ +COPY packages/contracts/package.json packages/contracts/ +COPY packages/ui/package.json packages/ui/ +RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --frozen-lockfile +COPY . . +RUN pnpm --filter @repo/contracts build + +FROM workspace AS api-build +RUN pnpm --filter api build +# The package alone with only what it needs to run, workspace packages included. +RUN --mount=type=cache,id=pnpm,target=/pnpm/store \ + pnpm --filter api deploy --prod --legacy /out + +FROM workspace AS web-build +# The API's public address is compiled into the pages. +ARG VITE_API_URL +RUN test -n "$VITE_API_URL" || (echo "VITE_API_URL is required: --build-arg VITE_API_URL=https://api.example.com" >&2; exit 1) +ENV VITE_API_URL=$VITE_API_URL +RUN pnpm --filter web build +RUN --mount=type=cache,id=pnpm,target=/pnpm/store \ + pnpm --filter web deploy --prod --legacy /out + +# The API. Before a new version starts, apply its migrations with the same +# image: `node dist/db/migrate.js`. +FROM node:24-alpine AS api +ENV NODE_ENV=production +ENV PORT=3000 +# Where files are kept when STORAGE_DRIVER is "local": mount a volume here. +ENV STORAGE_LOCAL_ROOT=/data/files +RUN mkdir -p /data/files && chown node:node /data/files +WORKDIR /app +COPY --from=api-build /out/package.json ./ +COPY --from=api-build /out/node_modules ./node_modules +# The build output is git-ignored, which keeps it out of `pnpm deploy`. +COPY --from=api-build /repo/apps/api/dist ./dist +COPY --from=api-build /repo/apps/api/drizzle ./drizzle +USER node +EXPOSE 3000 +HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=3 \ + CMD wget -qO /dev/null http://127.0.0.1:3000/health || exit 1 +CMD ["node", "dist/main.js"] + +# The web app: renders the first page on the server and serves the assets. +FROM node:24-alpine AS web +ENV NODE_ENV=production +ENV PORT=3000 +WORKDIR /app +COPY --from=web-build /out/package.json ./ +COPY --from=web-build /out/node_modules ./node_modules +COPY --from=web-build /repo/apps/web/dist ./dist +USER node +EXPOSE 3000 +HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=3 \ + CMD wget -qO /dev/null http://127.0.0.1:3000/login || exit 1 +CMD ["node_modules/.bin/srvx", "--prod", "-s", "../client", "dist/server/server.js"] diff --git a/README.md b/README.md index 4042488..4992ce7 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,62 @@ -# shadcn/ui monorepo template +# electro4ort -This is a TanStack Start monorepo template with shadcn/ui. +A chat app: friends and direct messages, group chats, **realms** with **cauldrons** (communities and the rooms in them), files, reactions, and voice and video calls. -## Adding components +| Where | What | +| -------------------- | ---------------------------------------------------------------------------- | +| `apps/api` | The API: NestJS, PostgreSQL through Drizzle, Better Auth, Socket.IO, LiveKit | +| `apps/web` | The web app: TanStack Start, TanStack Query, React 19 | +| `packages/contracts` | Request and response shapes shared by both, as Zod schemas | +| `packages/ui` | The components (shadcn/ui on Base UI) | -To add components to your app, run the following command at the root of your `web` app: +## Development + +Needs Node 24, pnpm and Docker. ```bash -pnpm dlx shadcn@latest add button -c apps/web +docker compose -f docker-compose.local.yml up -d # PostgreSQL, Redis, LiveKit +cp apps/api/.env.example apps/api/.env # then set BETTER_AUTH_SECRET +cp apps/web/.env.example apps/web/.env +pnpm install +pnpm --filter api db:migrate +pnpm dev # web on :3000, API on :3001 ``` -This will place the ui components in the `packages/ui/src/components` directory. +After changing the tables in `apps/api/src/db/schema`, run `pnpm db:generate --name ` and `pnpm db:migrate` in `apps/api`. -## Using components +To add a shadcn/ui component: `pnpm dlx shadcn@latest add button -c apps/web`. It lands in `packages/ui/src/components` and is imported as `@repo/ui/components/button`. -To use the components in your app, import them from the `ui` package. +## Checks -```tsx -import { Button } from "@workspace/ui/components/button"; +```bash +pnpm turbo run lint typecheck build # everything +pnpm turbo run test # unit tests +pnpm --filter api test:e2e # API end to end; needs the containers above ``` + +`.github/workflows/ci.yml` runs the same on every push and pull request, and builds both Docker images. + +## Deploying + +`docker-compose.yml` runs the whole app on one server: Caddy in front (HTTPS with certificates it fetches itself), the web app, the API, PostgreSQL, Redis and LiveKit. + +1. Point three DNS names at the server: `example.com`, `api.example.com` and `livekit.example.com` (yours in place of `example.com`). The web app and the API must share a parent domain like this: the session cookie is only sent between pages of one site. +2. Open the firewall for 80 and 443 (TCP), 443 (UDP), and for calls 7881 (TCP) and 7882 (UDP). +3. On the server, in a checkout of this repository: + + ```bash + cp .env.example .env # fill in the domain and the secrets; the file says how to make each + docker compose up -d --build + ``` + +To update: `git pull`, then `docker compose up -d --build` again. Migrations are applied by the `migrate` service before the new API starts. + +What to know before relying on it: + +- **Back up** the `postgres-data` volume (`docker compose exec postgres pg_dump -U electro4ort electro4ort`) and, unless files go to S3, the `files` volume. +- **Files** are kept on the server's disk by default. Set the `S3_*` variables in `.env` to keep them in a bucket instead, which is also what running more than one API instance needs. +- **Calls** work for people whose network allows UDP or TCP to the two ports above. Networks that only let HTTPS out need a TURN server, which LiveKit can run itself: see [its deployment guide](https://docs.livekit.io/home/self-hosting/deployment/). +- **Accounts** need no email confirmation and there is no password reset yet: both need an email provider. +- The API trusts one proxy in front of it (`TRUST_PROXY=1`, Caddy). Behind another load balancer as well, raise it, or rate limits count the balancer instead of the caller. + +To run the images elsewhere (Kubernetes, a platform): `docker build --target api .` and `docker build --target web --build-arg VITE_API_URL=https://api.example.com .`; the API's settings are listed in `apps/api/.env.example`, and its migrations run with `node dist/db/migrate.js` in the same image. diff --git a/apps/api/.env.example b/apps/api/.env.example index d629075..c79250d 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -1,12 +1,47 @@ # Copy to .env and fill in. The web app (apps/web) runs on 3000, so the API uses 3001. PORT=3001 +# How many reverse proxies (Caddy, nginx, a load balancer) stand between +# browsers and the API. 0 in development; 1 behind docker-compose.yml's Caddy. +# Rate limits count per caller's address, which is the proxy's unless this is right. +# TRUST_PROXY=0 +# "false" lifts the limits on how often routes may be called. +# RATE_LIMIT=true + # Matches docker-compose.local.yml in the repo root. DATABASE_URL=postgres://postgres:postgres@localhost:5432/electro4ort +# Matches docker-compose.local.yml in the repo root. +REDIS_URL=redis://localhost:6379 + # Generate with: openssl rand -base64 32 BETTER_AUTH_SECRET= # Public URL of this API. BETTER_AUTH_URL=http://localhost:3001 # Comma-separated origins allowed to call the auth endpoints (CORS + CSRF check). TRUSTED_ORIGINS=http://localhost:3000 + +# Where uploaded files are kept. "local" is a folder (STORAGE_LOCAL_ROOT, +# ".storage" by default) and needs nothing else. "s3" is an S3 bucket or any +# store that speaks S3 (Cloudflare R2, Backblaze B2, a self-hosted one). +STORAGE_DRIVER=local +# For STORAGE_DRIVER=s3. Browsers send files straight to the bucket, so its +# CORS rules must allow PUT and GET from the web app's origin with the +# Content-Type header. +# S3_BUCKET= +# S3_REGION= +# S3_ENDPOINT= +# S3_FORCE_PATH_STYLE=true +# S3_ACCESS_KEY_ID= +# S3_SECRET_ACCESS_KEY= + +# Voice and video calls go through a LiveKit server; leave these out to switch +# calls off. The values match docker-compose.local.yml in the repo root, which +# also tells LiveKit to report who joins and leaves to POST /livekit/webhook. +# In production: the wss:// address browsers reach, and a key pair of its own. +LIVEKIT_URL=ws://localhost:7880 +# Where the API itself reaches it, if that differs from what browsers use +# (its name on a private network, say). http:// or https://. +# LIVEKIT_INTERNAL_URL= +LIVEKIT_API_KEY=devkey +LIVEKIT_API_SECRET=local-development-secret-0123456789 diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.md index c9871f4..ef25763 100644 --- a/apps/api/AGENTS.md +++ b/apps/api/AGENTS.md @@ -27,7 +27,7 @@ A route handler can return a web `Response`, a `ReadableStream` or an async gene Nest's packages are ESM only, and this project is ESM too: relative imports are written without a file extension (the SWC build adds `.js`; `nest generate` still writes `.js`, which works but should be trimmed to match), `__dirname` doesn't exist (use `import.meta.dirname`), and tests run on Vitest, so mocks are `vi.fn()`, not `jest.fn()`. -In this project, `src/main.ts` creates the app and listens on `PORT` (3000 by default), `src/app.module.ts` is the root module that imports the others, and `AppController` and `AppService` are samples. Unit tests sit beside the code as `*.spec.ts` and the e2e test is in `test/`; Vitest runs them (`npm test`, `npm run test:e2e`). +In this project, `src/main.ts` creates the app and listens on `PORT` (3000 by default), `src/app.module.ts` is the root module that imports the others, and `AppController` and `AppService` are samples. Environment variables are declared and checked in `src/config/env.ts`. Request and response shapes shared with the web app are Zod schemas in `packages/contracts` (`@repo/contracts`): add them there, validate with `@Body({ schema })`, and run `pnpm --filter @repo/contracts build` (or `pnpm dev` at the root, which watches it) after changing them. Changes go over HTTP and updates go out over the socket: a service that changes something other people should see calls `RealtimeService.emitToUsers()` (or `emitToRealm()` for everyone in a realm; `src/realtime/`), and every event is declared in `ServerToClientEvents` in `packages/contracts/src/realtime.ts`; clients send nothing over the socket. Uploaded files are kept on the `StorageDisk` from `@nestjs/storage` (set up in `src/files/`, chosen with `STORAGE_DRIVER`: a local folder, S3, or memory in e2e tests): browsers send and fetch the bytes with signed URLs the API hands out, so no route of a feature receives a file body; `/files` stands in for S3 when the disk isn't one. Voice and video go through a LiveKit server (`src/calls/`, switched on by `LIVEKIT_URL` and its key pair): a call is a LiveKit room named after its conversation, with people in it under their user ids; the API hands out the tokens that let them in, and LiveKit reports who joined and left to `POST /livekit/webhook`, after which `CallsService.sync()` asks LiveKit for the truth, keeps it in Redis and emits `call:changed`. A change that takes away someone's access to a conversation calls `CallsService` to take them out of its call. Every route is rate limited per signed-in user, counted in Redis (`src/rate-limit/`, switched off in e2e tests by `RATE_LIMIT=false`): a route that costs something each time or reaches other people gets a tighter limit with `@AtMost(times, { seconds })`, and one that a page calls many times at once opts out with `@SkipThrottle()`; the routes under `/api/auth` have their own limits in `src/auth/auth.ts`. What every request passes first (proxy trust, security headers, CORS) is in `src/setup.ts`, which `main.ts` and the e2e tests both apply. e2e tests put a stand-in in place of `CallRooms`, the only class that calls LiveKit. Auth tables in `src/db/schema/auth.ts` are generated: change `src/auth/auth.ts`, then run `pnpm auth:generate` and `pnpm db:generate`. Unit tests sit beside the code as `*.spec.ts` and the e2e test is in `test/`; Vitest runs them (`npm test`, `npm run test:e2e`). When a task says how to test, follow it. When it says nothing, cover the behaviour you change with focused tests rather than adding broad e2e suites. diff --git a/apps/api/drizzle/20261201215428_usernames/migration.sql b/apps/api/drizzle/20261201215428_usernames/migration.sql new file mode 100644 index 0000000..5cc3682 --- /dev/null +++ b/apps/api/drizzle/20261201215428_usernames/migration.sql @@ -0,0 +1,3 @@ +ALTER TABLE "user" ADD COLUMN "username" text;--> statement-breakpoint +ALTER TABLE "user" ADD COLUMN "bio" text;--> statement-breakpoint +ALTER TABLE "user" ADD CONSTRAINT "user_username_key" UNIQUE("username"); \ No newline at end of file diff --git a/apps/api/drizzle/20261201215428_usernames/snapshot.json b/apps/api/drizzle/20261201215428_usernames/snapshot.json new file mode 100644 index 0000000..a0a1383 --- /dev/null +++ b/apps/api/drizzle/20261201215428_usernames/snapshot.json @@ -0,0 +1,115 @@ +{ + "type": "diff", + "version": "10", + "dialect": "postgres", + "id": "599a945d-6169-416b-9398-fe17247d8d99", + "prevIds": [ + "2041e3a9-973b-4348-98e7-0c5a0587d428" + ], + "footprints": [ + { + "statementType": "add_column", + "statementTarget": [ + "column", + "public", + "user", + "username" + ], + "writes": [ + "s|col|public.user.username", + "n|col|public.user.username", + "e|col|public.user.username" + ], + "reads": [ + "n|tbl|public.user", + "n|sch|public" + ] + }, + { + "statementType": "add_column", + "statementTarget": [ + "column", + "public", + "user", + "bio" + ], + "writes": [ + "s|col|public.user.bio", + "n|col|public.user.bio", + "e|col|public.user.bio" + ], + "reads": [ + "n|tbl|public.user", + "n|sch|public" + ] + }, + { + "statementType": "add_unique", + "statementTarget": [ + "table", + "public", + "user" + ], + "writes": [ + "s|uq|public.user.user_username_key", + "n|uq|public.user.user_username_key", + "e|uq|public.user.user_username_key", + "n|con|public.user.user_username_key", + "n|rel|public.user_username_key" + ], + "reads": [ + "n|tbl|public.user", + "n|sch|public", + "n|col|public.user.username" + ] + } + ], + "deltas": [ + { + "op": "create", + "row": { + "schema": "public", + "table": "user", + "name": "username", + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "user", + "name": "bio", + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "user", + "name": "user_username_key", + "nameExplicit": false, + "columns": [ + "username" + ], + "nullsNotDistinct": false, + "entityType": "uniques" + } + } + ] +} \ No newline at end of file diff --git a/apps/api/drizzle/20261201220558_friends_and_conversations/migration.sql b/apps/api/drizzle/20261201220558_friends_and_conversations/migration.sql new file mode 100644 index 0000000..95ea143 --- /dev/null +++ b/apps/api/drizzle/20261201220558_friends_and_conversations/migration.sql @@ -0,0 +1,46 @@ +CREATE TYPE "conversation_type" AS ENUM('direct');--> statement-breakpoint +CREATE TYPE "friendship_status" AS ENUM('pending', 'accepted');--> statement-breakpoint +CREATE TABLE "conversation" ( + "id" uuid PRIMARY KEY DEFAULT uuidv7(), + "type" "conversation_type" NOT NULL, + "direct_key" text UNIQUE, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "last_activity_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "conversation_member" ( + "conversation_id" uuid, + "user_id" text, + "joined_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "conversation_member_pkey" PRIMARY KEY("conversation_id","user_id") +); +--> statement-breakpoint +CREATE TABLE "message" ( + "id" uuid PRIMARY KEY DEFAULT uuidv7(), + "conversation_id" uuid NOT NULL, + "author_id" text NOT NULL, + "content" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "friendship" ( + "user_low_id" text, + "user_high_id" text, + "requested_by_id" text NOT NULL, + "status" "friendship_status" DEFAULT 'pending'::"friendship_status" NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "accepted_at" timestamp with time zone, + CONSTRAINT "friendship_pkey" PRIMARY KEY("user_low_id","user_high_id"), + CONSTRAINT "friendship_ordered_pair" CHECK ("user_low_id" < "user_high_id" COLLATE "C") +); +--> statement-breakpoint +CREATE INDEX "conversation_member_user_id_idx" ON "conversation_member" ("user_id");--> statement-breakpoint +CREATE INDEX "message_conversation_id_id_idx" ON "message" ("conversation_id","id");--> statement-breakpoint +CREATE INDEX "friendship_user_high_id_idx" ON "friendship" ("user_high_id");--> statement-breakpoint +ALTER TABLE "conversation_member" ADD CONSTRAINT "conversation_member_conversation_id_conversation_id_fkey" FOREIGN KEY ("conversation_id") REFERENCES "conversation"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "conversation_member" ADD CONSTRAINT "conversation_member_user_id_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "message" ADD CONSTRAINT "message_conversation_id_conversation_id_fkey" FOREIGN KEY ("conversation_id") REFERENCES "conversation"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "message" ADD CONSTRAINT "message_author_id_user_id_fkey" FOREIGN KEY ("author_id") REFERENCES "user"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "friendship" ADD CONSTRAINT "friendship_user_low_id_user_id_fkey" FOREIGN KEY ("user_low_id") REFERENCES "user"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "friendship" ADD CONSTRAINT "friendship_user_high_id_user_id_fkey" FOREIGN KEY ("user_high_id") REFERENCES "user"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "friendship" ADD CONSTRAINT "friendship_requested_by_id_user_id_fkey" FOREIGN KEY ("requested_by_id") REFERENCES "user"("id") ON DELETE CASCADE; \ No newline at end of file diff --git a/apps/api/drizzle/20261201220558_friends_and_conversations/snapshot.json b/apps/api/drizzle/20261201220558_friends_and_conversations/snapshot.json new file mode 100644 index 0000000..d71c1f0 --- /dev/null +++ b/apps/api/drizzle/20261201220558_friends_and_conversations/snapshot.json @@ -0,0 +1,1005 @@ +{ + "type": "diff", + "version": "10", + "dialect": "postgres", + "id": "093dfccd-003b-4b87-9780-15e56d12e34e", + "prevIds": [ + "599a945d-6169-416b-9398-fe17247d8d99" + ], + "footprints": [ + { + "statementType": "create_enum", + "statementTarget": [ + "enum", + "public", + "conversation_type" + ], + "writes": [ + "s|enum|public.conversation_type", + "n|enum|public.conversation_type", + "e|enum|public.conversation_type", + "n|type|public.conversation_type" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "create_enum", + "statementTarget": [ + "enum", + "public", + "friendship_status" + ], + "writes": [ + "s|enum|public.friendship_status", + "n|enum|public.friendship_status", + "e|enum|public.friendship_status", + "n|type|public.friendship_status" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "create_table", + "statementTarget": [ + "table", + "public", + "conversation" + ], + "writes": [ + "s|tbl|public.conversation", + "n|tbl|public.conversation", + "e|tbl|public.conversation", + "n|rel|public.conversation", + "n|type|public.conversation", + "n|rel|public.conversation_pkey", + "n|rel|public.conversation_direct_key_key" + ], + "reads": [ + "n|sch|public", + "n|enum|public.conversation_type" + ] + }, + { + "statementType": "create_table", + "statementTarget": [ + "table", + "public", + "conversation_member" + ], + "writes": [ + "s|tbl|public.conversation_member", + "n|tbl|public.conversation_member", + "e|tbl|public.conversation_member", + "n|rel|public.conversation_member", + "n|type|public.conversation_member", + "n|rel|public.conversation_member_pkey" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "create_table", + "statementTarget": [ + "table", + "public", + "message" + ], + "writes": [ + "s|tbl|public.message", + "n|tbl|public.message", + "e|tbl|public.message", + "n|rel|public.message", + "n|type|public.message", + "n|rel|public.message_pkey" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "create_table", + "statementTarget": [ + "table", + "public", + "friendship" + ], + "writes": [ + "s|tbl|public.friendship", + "n|tbl|public.friendship", + "e|tbl|public.friendship", + "n|rel|public.friendship", + "n|type|public.friendship", + "n|rel|public.friendship_pkey" + ], + "reads": [ + "n|sch|public", + "n|enum|public.friendship_status" + ] + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "public", + "conversation_member", + "conversation_member_user_id_idx" + ], + "writes": [ + "s|idx|public.conversation_member_user_id_idx", + "n|idx|public.conversation_member_user_id_idx", + "e|idx|public.conversation_member_user_id_idx", + "n|rel|public.conversation_member_user_id_idx" + ], + "reads": [ + "n|tbl|public.conversation_member", + "n|sch|public", + "n|col|public.conversation_member.user_id" + ] + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "public", + "message", + "message_conversation_id_id_idx" + ], + "writes": [ + "s|idx|public.message_conversation_id_id_idx", + "n|idx|public.message_conversation_id_id_idx", + "e|idx|public.message_conversation_id_id_idx", + "n|rel|public.message_conversation_id_id_idx" + ], + "reads": [ + "n|tbl|public.message", + "n|sch|public", + "n|col|public.message.conversation_id", + "n|col|public.message.id" + ] + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "public", + "friendship", + "friendship_user_high_id_idx" + ], + "writes": [ + "s|idx|public.friendship_user_high_id_idx", + "n|idx|public.friendship_user_high_id_idx", + "e|idx|public.friendship_user_high_id_idx", + "n|rel|public.friendship_user_high_id_idx" + ], + "reads": [ + "n|tbl|public.friendship", + "n|sch|public", + "n|col|public.friendship.user_high_id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "conversation_member" + ], + "writes": [ + "s|fk|public.conversation_member.conversation_member_conversation_id_conversation_id_fkey", + "n|fk|public.conversation_member.conversation_member_conversation_id_conversation_id_fkey", + "e|fk|public.conversation_member.conversation_member_conversation_id_conversation_id_fkey", + "n|con|public.conversation_member.conversation_member_conversation_id_conversation_id_fkey" + ], + "reads": [ + "n|tbl|public.conversation_member", + "n|sch|public", + "n|tbl|public.conversation", + "n|sch|public", + "n|col|public.conversation_member.conversation_id", + "n|col|public.conversation.id", + "e|uniqueness|public.conversation.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "conversation_member" + ], + "writes": [ + "s|fk|public.conversation_member.conversation_member_user_id_user_id_fkey", + "n|fk|public.conversation_member.conversation_member_user_id_user_id_fkey", + "e|fk|public.conversation_member.conversation_member_user_id_user_id_fkey", + "n|con|public.conversation_member.conversation_member_user_id_user_id_fkey" + ], + "reads": [ + "n|tbl|public.conversation_member", + "n|sch|public", + "n|tbl|public.user", + "n|sch|public", + "n|col|public.conversation_member.user_id", + "n|col|public.user.id", + "e|uniqueness|public.user.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "message" + ], + "writes": [ + "s|fk|public.message.message_conversation_id_conversation_id_fkey", + "n|fk|public.message.message_conversation_id_conversation_id_fkey", + "e|fk|public.message.message_conversation_id_conversation_id_fkey", + "n|con|public.message.message_conversation_id_conversation_id_fkey" + ], + "reads": [ + "n|tbl|public.message", + "n|sch|public", + "n|tbl|public.conversation", + "n|sch|public", + "n|col|public.message.conversation_id", + "n|col|public.conversation.id", + "e|uniqueness|public.conversation.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "message" + ], + "writes": [ + "s|fk|public.message.message_author_id_user_id_fkey", + "n|fk|public.message.message_author_id_user_id_fkey", + "e|fk|public.message.message_author_id_user_id_fkey", + "n|con|public.message.message_author_id_user_id_fkey" + ], + "reads": [ + "n|tbl|public.message", + "n|sch|public", + "n|tbl|public.user", + "n|sch|public", + "n|col|public.message.author_id", + "n|col|public.user.id", + "e|uniqueness|public.user.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "friendship" + ], + "writes": [ + "s|fk|public.friendship.friendship_user_low_id_user_id_fkey", + "n|fk|public.friendship.friendship_user_low_id_user_id_fkey", + "e|fk|public.friendship.friendship_user_low_id_user_id_fkey", + "n|con|public.friendship.friendship_user_low_id_user_id_fkey" + ], + "reads": [ + "n|tbl|public.friendship", + "n|sch|public", + "n|tbl|public.user", + "n|sch|public", + "n|col|public.friendship.user_low_id", + "n|col|public.user.id", + "e|uniqueness|public.user.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "friendship" + ], + "writes": [ + "s|fk|public.friendship.friendship_user_high_id_user_id_fkey", + "n|fk|public.friendship.friendship_user_high_id_user_id_fkey", + "e|fk|public.friendship.friendship_user_high_id_user_id_fkey", + "n|con|public.friendship.friendship_user_high_id_user_id_fkey" + ], + "reads": [ + "n|tbl|public.friendship", + "n|sch|public", + "n|tbl|public.user", + "n|sch|public", + "n|col|public.friendship.user_high_id", + "n|col|public.user.id", + "e|uniqueness|public.user.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "friendship" + ], + "writes": [ + "s|fk|public.friendship.friendship_requested_by_id_user_id_fkey", + "n|fk|public.friendship.friendship_requested_by_id_user_id_fkey", + "e|fk|public.friendship.friendship_requested_by_id_user_id_fkey", + "n|con|public.friendship.friendship_requested_by_id_user_id_fkey" + ], + "reads": [ + "n|tbl|public.friendship", + "n|sch|public", + "n|tbl|public.user", + "n|sch|public", + "n|col|public.friendship.requested_by_id", + "n|col|public.user.id", + "e|uniqueness|public.user.id" + ] + } + ], + "deltas": [ + { + "op": "create", + "row": { + "schema": "public", + "name": "conversation", + "isRlsEnabled": false, + "entityType": "tables" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "name": "conversation_member", + "isRlsEnabled": false, + "entityType": "tables" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "name": "message", + "isRlsEnabled": false, + "entityType": "tables" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "name": "friendship", + "isRlsEnabled": false, + "entityType": "tables" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "name": "conversation_type", + "values": [ + "direct" + ], + "entityType": "enums" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "name": "friendship_status", + "values": [ + "pending", + "accepted" + ], + "entityType": "enums" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation", + "name": "id", + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "uuidv7()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation", + "name": "type", + "type": "conversation_type", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation", + "name": "direct_key", + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation", + "name": "created_at", + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation", + "name": "last_activity_at", + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation_member", + "name": "conversation_id", + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation_member", + "name": "user_id", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation_member", + "name": "joined_at", + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "message", + "name": "id", + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "uuidv7()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "message", + "name": "conversation_id", + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "message", + "name": "author_id", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "message", + "name": "content", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "message", + "name": "created_at", + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "friendship", + "name": "user_low_id", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "friendship", + "name": "user_high_id", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "friendship", + "name": "requested_by_id", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "friendship", + "name": "status", + "type": "friendship_status", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": "'pending'", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "friendship", + "name": "created_at", + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "friendship", + "name": "accepted_at", + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation_member", + "name": "conversation_member_user_id_idx", + "nameExplicit": true, + "columns": [ + { + "value": "user_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "message", + "name": "message_conversation_id_id_idx", + "nameExplicit": true, + "columns": [ + { + "value": "conversation_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "friendship", + "name": "friendship_user_high_id_idx", + "nameExplicit": true, + "columns": [ + { + "value": "user_high_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation_member", + "name": "conversation_member_conversation_id_conversation_id_fkey", + "nameExplicit": false, + "columns": [ + "conversation_id" + ], + "schemaTo": "public", + "tableTo": "conversation", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation_member", + "name": "conversation_member_user_id_user_id_fkey", + "nameExplicit": false, + "columns": [ + "user_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "message", + "name": "message_conversation_id_conversation_id_fkey", + "nameExplicit": false, + "columns": [ + "conversation_id" + ], + "schemaTo": "public", + "tableTo": "conversation", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "message", + "name": "message_author_id_user_id_fkey", + "nameExplicit": false, + "columns": [ + "author_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "friendship", + "name": "friendship_user_low_id_user_id_fkey", + "nameExplicit": false, + "columns": [ + "user_low_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "friendship", + "name": "friendship_user_high_id_user_id_fkey", + "nameExplicit": false, + "columns": [ + "user_high_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "friendship", + "name": "friendship_requested_by_id_user_id_fkey", + "nameExplicit": false, + "columns": [ + "requested_by_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation_member", + "name": "conversation_member_pkey", + "columns": [ + "conversation_id", + "user_id" + ], + "nameExplicit": false, + "entityType": "pks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "friendship", + "name": "friendship_pkey", + "columns": [ + "user_low_id", + "user_high_id" + ], + "nameExplicit": false, + "entityType": "pks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation", + "name": "conversation_pkey", + "columns": [ + "id" + ], + "nameExplicit": false, + "entityType": "pks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "message", + "name": "message_pkey", + "columns": [ + "id" + ], + "nameExplicit": false, + "entityType": "pks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation", + "name": "conversation_direct_key_key", + "nameExplicit": false, + "columns": [ + "direct_key" + ], + "nullsNotDistinct": false, + "entityType": "uniques" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "friendship", + "name": "friendship_ordered_pair", + "value": "\"user_low_id\" < \"user_high_id\" COLLATE \"C\"", + "entityType": "checks" + } + } + ] +} \ No newline at end of file diff --git a/apps/api/drizzle/20261201222144_group_conversations/migration.sql b/apps/api/drizzle/20261201222144_group_conversations/migration.sql new file mode 100644 index 0000000..f2ed9fc --- /dev/null +++ b/apps/api/drizzle/20261201222144_group_conversations/migration.sql @@ -0,0 +1,4 @@ +ALTER TYPE "conversation_type" ADD VALUE 'group';--> statement-breakpoint +ALTER TABLE "conversation" ADD COLUMN "name" text;--> statement-breakpoint +ALTER TABLE "conversation" ADD COLUMN "owner_id" text;--> statement-breakpoint +ALTER TABLE "conversation" ADD CONSTRAINT "conversation_owner_id_user_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "user"("id") ON DELETE SET NULL; \ No newline at end of file diff --git a/apps/api/drizzle/20261201222144_group_conversations/snapshot.json b/apps/api/drizzle/20261201222144_group_conversations/snapshot.json new file mode 100644 index 0000000..6287714 --- /dev/null +++ b/apps/api/drizzle/20261201222144_group_conversations/snapshot.json @@ -0,0 +1,148 @@ +{ + "type": "diff", + "version": "10", + "dialect": "postgres", + "id": "d8d24fdc-bb81-4b87-8ec6-6d18c20db156", + "prevIds": [ + "093dfccd-003b-4b87-9780-15e56d12e34e" + ], + "footprints": [ + { + "statementType": "alter_enum", + "statementTarget": [ + "enum", + "public", + "conversation_type" + ], + "writes": [ + "s|enum|public.conversation_type" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "add_column", + "statementTarget": [ + "column", + "public", + "conversation", + "name" + ], + "writes": [ + "s|col|public.conversation.name", + "n|col|public.conversation.name", + "e|col|public.conversation.name" + ], + "reads": [ + "n|tbl|public.conversation", + "n|sch|public" + ] + }, + { + "statementType": "add_column", + "statementTarget": [ + "column", + "public", + "conversation", + "owner_id" + ], + "writes": [ + "s|col|public.conversation.owner_id", + "n|col|public.conversation.owner_id", + "e|col|public.conversation.owner_id" + ], + "reads": [ + "n|tbl|public.conversation", + "n|sch|public" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "conversation" + ], + "writes": [ + "s|fk|public.conversation.conversation_owner_id_user_id_fkey", + "n|fk|public.conversation.conversation_owner_id_user_id_fkey", + "e|fk|public.conversation.conversation_owner_id_user_id_fkey", + "n|con|public.conversation.conversation_owner_id_user_id_fkey" + ], + "reads": [ + "n|tbl|public.conversation", + "n|sch|public", + "n|tbl|public.user", + "n|sch|public", + "n|col|public.conversation.owner_id", + "n|col|public.user.id", + "e|uniqueness|public.user.id" + ] + } + ], + "deltas": [ + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation", + "name": "name", + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation", + "name": "owner_id", + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation", + "name": "conversation_owner_id_user_id_fkey", + "nameExplicit": false, + "columns": [ + "owner_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "entityType": "fks" + } + }, + { + "op": "alter", + "key": "enums\u0000[\"public\",\"conversation_type\"]", + "set": { + "values": [ + "direct", + "group" + ] + } + } + ] +} \ No newline at end of file diff --git a/apps/api/drizzle/20261202091655_realms/migration.sql b/apps/api/drizzle/20261202091655_realms/migration.sql new file mode 100644 index 0000000..7891592 --- /dev/null +++ b/apps/api/drizzle/20261202091655_realms/migration.sql @@ -0,0 +1,56 @@ +ALTER TYPE "conversation_type" ADD VALUE 'cauldron';--> statement-breakpoint +CREATE TABLE "realm" ( + "id" uuid PRIMARY KEY DEFAULT uuidv7(), + "name" text NOT NULL, + "owner_id" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "realm_invite" ( + "code" text PRIMARY KEY, + "realm_id" uuid NOT NULL, + "created_by_id" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "expires_at" timestamp with time zone, + "max_uses" integer, + "uses" integer DEFAULT 0 NOT NULL +); +--> statement-breakpoint +CREATE TABLE "realm_member" ( + "realm_id" uuid, + "user_id" text, + "joined_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "realm_member_pkey" PRIMARY KEY("realm_id","user_id") +); +--> statement-breakpoint +CREATE TABLE "realm_member_role" ( + "realm_id" uuid, + "user_id" text, + "role_id" uuid, + CONSTRAINT "realm_member_role_pkey" PRIMARY KEY("realm_id","user_id","role_id") +); +--> statement-breakpoint +CREATE TABLE "realm_role" ( + "id" uuid PRIMARY KEY DEFAULT uuidv7(), + "realm_id" uuid NOT NULL, + "name" text NOT NULL, + "permissions" text[] NOT NULL, + "is_default" boolean DEFAULT false NOT NULL +); +--> statement-breakpoint +ALTER TABLE "conversation" ADD COLUMN "realm_id" uuid;--> statement-breakpoint +CREATE INDEX "conversation_realm_id_idx" ON "conversation" ("realm_id");--> statement-breakpoint +CREATE INDEX "realm_invite_realm_id_idx" ON "realm_invite" ("realm_id");--> statement-breakpoint +CREATE INDEX "realm_member_user_id_idx" ON "realm_member" ("user_id");--> statement-breakpoint +CREATE INDEX "realm_member_role_role_id_idx" ON "realm_member_role" ("role_id");--> statement-breakpoint +CREATE INDEX "realm_role_realm_id_idx" ON "realm_role" ("realm_id");--> statement-breakpoint +CREATE UNIQUE INDEX "realm_role_one_default_idx" ON "realm_role" ("realm_id") WHERE "is_default";--> statement-breakpoint +ALTER TABLE "conversation" ADD CONSTRAINT "conversation_realm_id_realm_id_fkey" FOREIGN KEY ("realm_id") REFERENCES "realm"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "realm" ADD CONSTRAINT "realm_owner_id_user_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "user"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "realm_invite" ADD CONSTRAINT "realm_invite_realm_id_realm_id_fkey" FOREIGN KEY ("realm_id") REFERENCES "realm"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "realm_invite" ADD CONSTRAINT "realm_invite_created_by_id_user_id_fkey" FOREIGN KEY ("created_by_id") REFERENCES "user"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "realm_member" ADD CONSTRAINT "realm_member_realm_id_realm_id_fkey" FOREIGN KEY ("realm_id") REFERENCES "realm"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "realm_member" ADD CONSTRAINT "realm_member_user_id_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "realm_member_role" ADD CONSTRAINT "realm_member_role_role_id_realm_role_id_fkey" FOREIGN KEY ("role_id") REFERENCES "realm_role"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "realm_member_role" ADD CONSTRAINT "realm_member_role_member_fk" FOREIGN KEY ("realm_id","user_id") REFERENCES "realm_member"("realm_id","user_id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "realm_role" ADD CONSTRAINT "realm_role_realm_id_realm_id_fkey" FOREIGN KEY ("realm_id") REFERENCES "realm"("id") ON DELETE CASCADE; \ No newline at end of file diff --git a/apps/api/drizzle/20261202091655_realms/snapshot.json b/apps/api/drizzle/20261202091655_realms/snapshot.json new file mode 100644 index 0000000..0b3a90e --- /dev/null +++ b/apps/api/drizzle/20261202091655_realms/snapshot.json @@ -0,0 +1,1281 @@ +{ + "type": "diff", + "version": "10", + "dialect": "postgres", + "id": "7d8afcd9-0950-488b-b642-ef874960d2b3", + "prevIds": [ + "d8d24fdc-bb81-4b87-8ec6-6d18c20db156" + ], + "footprints": [ + { + "statementType": "alter_enum", + "statementTarget": [ + "enum", + "public", + "conversation_type" + ], + "writes": [ + "s|enum|public.conversation_type" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "create_table", + "statementTarget": [ + "table", + "public", + "realm" + ], + "writes": [ + "s|tbl|public.realm", + "n|tbl|public.realm", + "e|tbl|public.realm", + "n|rel|public.realm", + "n|type|public.realm", + "n|rel|public.realm_pkey" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "create_table", + "statementTarget": [ + "table", + "public", + "realm_invite" + ], + "writes": [ + "s|tbl|public.realm_invite", + "n|tbl|public.realm_invite", + "e|tbl|public.realm_invite", + "n|rel|public.realm_invite", + "n|type|public.realm_invite", + "n|rel|public.realm_invite_pkey" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "create_table", + "statementTarget": [ + "table", + "public", + "realm_member" + ], + "writes": [ + "s|tbl|public.realm_member", + "n|tbl|public.realm_member", + "e|tbl|public.realm_member", + "n|rel|public.realm_member", + "n|type|public.realm_member", + "n|rel|public.realm_member_pkey" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "create_table", + "statementTarget": [ + "table", + "public", + "realm_member_role" + ], + "writes": [ + "s|tbl|public.realm_member_role", + "n|tbl|public.realm_member_role", + "e|tbl|public.realm_member_role", + "n|rel|public.realm_member_role", + "n|type|public.realm_member_role", + "n|rel|public.realm_member_role_pkey" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "create_table", + "statementTarget": [ + "table", + "public", + "realm_role" + ], + "writes": [ + "s|tbl|public.realm_role", + "n|tbl|public.realm_role", + "e|tbl|public.realm_role", + "n|rel|public.realm_role", + "n|type|public.realm_role", + "n|rel|public.realm_role_pkey" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "add_column", + "statementTarget": [ + "column", + "public", + "conversation", + "realm_id" + ], + "writes": [ + "s|col|public.conversation.realm_id", + "n|col|public.conversation.realm_id", + "e|col|public.conversation.realm_id" + ], + "reads": [ + "n|tbl|public.conversation", + "n|sch|public" + ] + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "public", + "conversation", + "conversation_realm_id_idx" + ], + "writes": [ + "s|idx|public.conversation_realm_id_idx", + "n|idx|public.conversation_realm_id_idx", + "e|idx|public.conversation_realm_id_idx", + "n|rel|public.conversation_realm_id_idx" + ], + "reads": [ + "n|tbl|public.conversation", + "n|sch|public", + "n|col|public.conversation.realm_id" + ] + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "public", + "realm_invite", + "realm_invite_realm_id_idx" + ], + "writes": [ + "s|idx|public.realm_invite_realm_id_idx", + "n|idx|public.realm_invite_realm_id_idx", + "e|idx|public.realm_invite_realm_id_idx", + "n|rel|public.realm_invite_realm_id_idx" + ], + "reads": [ + "n|tbl|public.realm_invite", + "n|sch|public", + "n|col|public.realm_invite.realm_id" + ] + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "public", + "realm_member", + "realm_member_user_id_idx" + ], + "writes": [ + "s|idx|public.realm_member_user_id_idx", + "n|idx|public.realm_member_user_id_idx", + "e|idx|public.realm_member_user_id_idx", + "n|rel|public.realm_member_user_id_idx" + ], + "reads": [ + "n|tbl|public.realm_member", + "n|sch|public", + "n|col|public.realm_member.user_id" + ] + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "public", + "realm_member_role", + "realm_member_role_role_id_idx" + ], + "writes": [ + "s|idx|public.realm_member_role_role_id_idx", + "n|idx|public.realm_member_role_role_id_idx", + "e|idx|public.realm_member_role_role_id_idx", + "n|rel|public.realm_member_role_role_id_idx" + ], + "reads": [ + "n|tbl|public.realm_member_role", + "n|sch|public", + "n|col|public.realm_member_role.role_id" + ] + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "public", + "realm_role", + "realm_role_realm_id_idx" + ], + "writes": [ + "s|idx|public.realm_role_realm_id_idx", + "n|idx|public.realm_role_realm_id_idx", + "e|idx|public.realm_role_realm_id_idx", + "n|rel|public.realm_role_realm_id_idx" + ], + "reads": [ + "n|tbl|public.realm_role", + "n|sch|public", + "n|col|public.realm_role.realm_id" + ] + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "public", + "realm_role", + "realm_role_one_default_idx" + ], + "writes": [ + "s|idx|public.realm_role_one_default_idx", + "n|idx|public.realm_role_one_default_idx", + "e|idx|public.realm_role_one_default_idx", + "n|rel|public.realm_role_one_default_idx" + ], + "reads": [ + "n|tbl|public.realm_role", + "n|sch|public", + "n|col|public.realm_role.realm_id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "conversation" + ], + "writes": [ + "s|fk|public.conversation.conversation_realm_id_realm_id_fkey", + "n|fk|public.conversation.conversation_realm_id_realm_id_fkey", + "e|fk|public.conversation.conversation_realm_id_realm_id_fkey", + "n|con|public.conversation.conversation_realm_id_realm_id_fkey" + ], + "reads": [ + "n|tbl|public.conversation", + "n|sch|public", + "n|tbl|public.realm", + "n|sch|public", + "n|col|public.conversation.realm_id", + "n|col|public.realm.id", + "e|uniqueness|public.realm.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "realm" + ], + "writes": [ + "s|fk|public.realm.realm_owner_id_user_id_fkey", + "n|fk|public.realm.realm_owner_id_user_id_fkey", + "e|fk|public.realm.realm_owner_id_user_id_fkey", + "n|con|public.realm.realm_owner_id_user_id_fkey" + ], + "reads": [ + "n|tbl|public.realm", + "n|sch|public", + "n|tbl|public.user", + "n|sch|public", + "n|col|public.realm.owner_id", + "n|col|public.user.id", + "e|uniqueness|public.user.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "realm_invite" + ], + "writes": [ + "s|fk|public.realm_invite.realm_invite_realm_id_realm_id_fkey", + "n|fk|public.realm_invite.realm_invite_realm_id_realm_id_fkey", + "e|fk|public.realm_invite.realm_invite_realm_id_realm_id_fkey", + "n|con|public.realm_invite.realm_invite_realm_id_realm_id_fkey" + ], + "reads": [ + "n|tbl|public.realm_invite", + "n|sch|public", + "n|tbl|public.realm", + "n|sch|public", + "n|col|public.realm_invite.realm_id", + "n|col|public.realm.id", + "e|uniqueness|public.realm.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "realm_invite" + ], + "writes": [ + "s|fk|public.realm_invite.realm_invite_created_by_id_user_id_fkey", + "n|fk|public.realm_invite.realm_invite_created_by_id_user_id_fkey", + "e|fk|public.realm_invite.realm_invite_created_by_id_user_id_fkey", + "n|con|public.realm_invite.realm_invite_created_by_id_user_id_fkey" + ], + "reads": [ + "n|tbl|public.realm_invite", + "n|sch|public", + "n|tbl|public.user", + "n|sch|public", + "n|col|public.realm_invite.created_by_id", + "n|col|public.user.id", + "e|uniqueness|public.user.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "realm_member" + ], + "writes": [ + "s|fk|public.realm_member.realm_member_realm_id_realm_id_fkey", + "n|fk|public.realm_member.realm_member_realm_id_realm_id_fkey", + "e|fk|public.realm_member.realm_member_realm_id_realm_id_fkey", + "n|con|public.realm_member.realm_member_realm_id_realm_id_fkey" + ], + "reads": [ + "n|tbl|public.realm_member", + "n|sch|public", + "n|tbl|public.realm", + "n|sch|public", + "n|col|public.realm_member.realm_id", + "n|col|public.realm.id", + "e|uniqueness|public.realm.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "realm_member" + ], + "writes": [ + "s|fk|public.realm_member.realm_member_user_id_user_id_fkey", + "n|fk|public.realm_member.realm_member_user_id_user_id_fkey", + "e|fk|public.realm_member.realm_member_user_id_user_id_fkey", + "n|con|public.realm_member.realm_member_user_id_user_id_fkey" + ], + "reads": [ + "n|tbl|public.realm_member", + "n|sch|public", + "n|tbl|public.user", + "n|sch|public", + "n|col|public.realm_member.user_id", + "n|col|public.user.id", + "e|uniqueness|public.user.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "realm_member_role" + ], + "writes": [ + "s|fk|public.realm_member_role.realm_member_role_role_id_realm_role_id_fkey", + "n|fk|public.realm_member_role.realm_member_role_role_id_realm_role_id_fkey", + "e|fk|public.realm_member_role.realm_member_role_role_id_realm_role_id_fkey", + "n|con|public.realm_member_role.realm_member_role_role_id_realm_role_id_fkey" + ], + "reads": [ + "n|tbl|public.realm_member_role", + "n|sch|public", + "n|tbl|public.realm_role", + "n|sch|public", + "n|col|public.realm_member_role.role_id", + "n|col|public.realm_role.id", + "e|uniqueness|public.realm_role.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "realm_member_role" + ], + "writes": [ + "s|fk|public.realm_member_role.realm_member_role_member_fk", + "n|fk|public.realm_member_role.realm_member_role_member_fk", + "e|fk|public.realm_member_role.realm_member_role_member_fk", + "n|con|public.realm_member_role.realm_member_role_member_fk" + ], + "reads": [ + "n|tbl|public.realm_member_role", + "n|sch|public", + "n|tbl|public.realm_member", + "n|sch|public", + "n|col|public.realm_member_role.realm_id", + "n|col|public.realm_member_role.user_id", + "n|col|public.realm_member.realm_id", + "n|col|public.realm_member.user_id", + "e|uniqueness|public.realm_member.realm_id.user_id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "realm_role" + ], + "writes": [ + "s|fk|public.realm_role.realm_role_realm_id_realm_id_fkey", + "n|fk|public.realm_role.realm_role_realm_id_realm_id_fkey", + "e|fk|public.realm_role.realm_role_realm_id_realm_id_fkey", + "n|con|public.realm_role.realm_role_realm_id_realm_id_fkey" + ], + "reads": [ + "n|tbl|public.realm_role", + "n|sch|public", + "n|tbl|public.realm", + "n|sch|public", + "n|col|public.realm_role.realm_id", + "n|col|public.realm.id", + "e|uniqueness|public.realm.id" + ] + } + ], + "deltas": [ + { + "op": "create", + "row": { + "schema": "public", + "name": "realm", + "isRlsEnabled": false, + "entityType": "tables" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "name": "realm_invite", + "isRlsEnabled": false, + "entityType": "tables" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "name": "realm_member", + "isRlsEnabled": false, + "entityType": "tables" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "name": "realm_member_role", + "isRlsEnabled": false, + "entityType": "tables" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "name": "realm_role", + "isRlsEnabled": false, + "entityType": "tables" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation", + "name": "realm_id", + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm", + "name": "id", + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "uuidv7()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm", + "name": "name", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm", + "name": "owner_id", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm", + "name": "created_at", + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_invite", + "name": "code", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_invite", + "name": "realm_id", + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_invite", + "name": "created_by_id", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_invite", + "name": "created_at", + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_invite", + "name": "expires_at", + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_invite", + "name": "max_uses", + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_invite", + "name": "uses", + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "0", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_member", + "name": "realm_id", + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_member", + "name": "user_id", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_member", + "name": "joined_at", + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_member_role", + "name": "realm_id", + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_member_role", + "name": "user_id", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_member_role", + "name": "role_id", + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_role", + "name": "id", + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "uuidv7()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_role", + "name": "realm_id", + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_role", + "name": "name", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_role", + "name": "permissions", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 1, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_role", + "name": "is_default", + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation", + "name": "conversation_realm_id_idx", + "nameExplicit": true, + "columns": [ + { + "value": "realm_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_invite", + "name": "realm_invite_realm_id_idx", + "nameExplicit": true, + "columns": [ + { + "value": "realm_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_member", + "name": "realm_member_user_id_idx", + "nameExplicit": true, + "columns": [ + { + "value": "user_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_member_role", + "name": "realm_member_role_role_id_idx", + "nameExplicit": true, + "columns": [ + { + "value": "role_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_role", + "name": "realm_role_realm_id_idx", + "nameExplicit": true, + "columns": [ + { + "value": "realm_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_role", + "name": "realm_role_one_default_idx", + "nameExplicit": true, + "columns": [ + { + "value": "realm_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": "\"is_default\"", + "with": "", + "method": "btree", + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation", + "name": "conversation_realm_id_realm_id_fkey", + "nameExplicit": false, + "columns": [ + "realm_id" + ], + "schemaTo": "public", + "tableTo": "realm", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm", + "name": "realm_owner_id_user_id_fkey", + "nameExplicit": false, + "columns": [ + "owner_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_invite", + "name": "realm_invite_realm_id_realm_id_fkey", + "nameExplicit": false, + "columns": [ + "realm_id" + ], + "schemaTo": "public", + "tableTo": "realm", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_invite", + "name": "realm_invite_created_by_id_user_id_fkey", + "nameExplicit": false, + "columns": [ + "created_by_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_member", + "name": "realm_member_realm_id_realm_id_fkey", + "nameExplicit": false, + "columns": [ + "realm_id" + ], + "schemaTo": "public", + "tableTo": "realm", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_member", + "name": "realm_member_user_id_user_id_fkey", + "nameExplicit": false, + "columns": [ + "user_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_member_role", + "name": "realm_member_role_role_id_realm_role_id_fkey", + "nameExplicit": false, + "columns": [ + "role_id" + ], + "schemaTo": "public", + "tableTo": "realm_role", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_member_role", + "name": "realm_member_role_member_fk", + "nameExplicit": true, + "columns": [ + "realm_id", + "user_id" + ], + "schemaTo": "public", + "tableTo": "realm_member", + "columnsTo": [ + "realm_id", + "user_id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_role", + "name": "realm_role_realm_id_realm_id_fkey", + "nameExplicit": false, + "columns": [ + "realm_id" + ], + "schemaTo": "public", + "tableTo": "realm", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_member", + "name": "realm_member_pkey", + "columns": [ + "realm_id", + "user_id" + ], + "nameExplicit": false, + "entityType": "pks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_member_role", + "name": "realm_member_role_pkey", + "columns": [ + "realm_id", + "user_id", + "role_id" + ], + "nameExplicit": false, + "entityType": "pks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm", + "name": "realm_pkey", + "columns": [ + "id" + ], + "nameExplicit": false, + "entityType": "pks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_invite", + "name": "realm_invite_pkey", + "columns": [ + "code" + ], + "nameExplicit": false, + "entityType": "pks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_role", + "name": "realm_role_pkey", + "columns": [ + "id" + ], + "nameExplicit": false, + "entityType": "pks" + } + }, + { + "op": "alter", + "key": "enums\u0000[\"public\",\"conversation_type\"]", + "set": { + "values": [ + "direct", + "group", + "cauldron" + ] + } + } + ] +} \ No newline at end of file diff --git a/apps/api/drizzle/20261202102933_attachments_reactions_reads/migration.sql b/apps/api/drizzle/20261202102933_attachments_reactions_reads/migration.sql new file mode 100644 index 0000000..aa06d2b --- /dev/null +++ b/apps/api/drizzle/20261202102933_attachments_reactions_reads/migration.sql @@ -0,0 +1,36 @@ +CREATE TABLE "attachment" ( + "id" uuid PRIMARY KEY DEFAULT uuidv7(), + "uploader_id" text, + "message_id" uuid, + "filename" text NOT NULL, + "content_type" text NOT NULL, + "size" integer NOT NULL, + "width" integer, + "height" integer, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "conversation_read" ( + "user_id" text, + "conversation_id" uuid, + "last_read_message_id" uuid NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "conversation_read_pkey" PRIMARY KEY("user_id","conversation_id") +); +--> statement-breakpoint +CREATE TABLE "message_reaction" ( + "message_id" uuid, + "user_id" text, + "emoji" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "message_reaction_pkey" PRIMARY KEY("message_id","user_id","emoji") +); +--> statement-breakpoint +CREATE INDEX "attachment_message_id_idx" ON "attachment" ("message_id");--> statement-breakpoint +CREATE INDEX "attachment_uploader_id_idx" ON "attachment" ("uploader_id");--> statement-breakpoint +ALTER TABLE "attachment" ADD CONSTRAINT "attachment_uploader_id_user_id_fkey" FOREIGN KEY ("uploader_id") REFERENCES "user"("id") ON DELETE SET NULL;--> statement-breakpoint +ALTER TABLE "attachment" ADD CONSTRAINT "attachment_message_id_message_id_fkey" FOREIGN KEY ("message_id") REFERENCES "message"("id") ON DELETE SET NULL;--> statement-breakpoint +ALTER TABLE "conversation_read" ADD CONSTRAINT "conversation_read_user_id_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "conversation_read" ADD CONSTRAINT "conversation_read_conversation_id_conversation_id_fkey" FOREIGN KEY ("conversation_id") REFERENCES "conversation"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "message_reaction" ADD CONSTRAINT "message_reaction_message_id_message_id_fkey" FOREIGN KEY ("message_id") REFERENCES "message"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "message_reaction" ADD CONSTRAINT "message_reaction_user_id_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE CASCADE; \ No newline at end of file diff --git a/apps/api/drizzle/20261202102933_attachments_reactions_reads/snapshot.json b/apps/api/drizzle/20261202102933_attachments_reactions_reads/snapshot.json new file mode 100644 index 0000000..89bdba9 --- /dev/null +++ b/apps/api/drizzle/20261202102933_attachments_reactions_reads/snapshot.json @@ -0,0 +1,755 @@ +{ + "type": "diff", + "version": "10", + "dialect": "postgres", + "id": "97862caf-8fe6-4846-b50d-6852f29dfc94", + "prevIds": [ + "7d8afcd9-0950-488b-b642-ef874960d2b3" + ], + "footprints": [ + { + "statementType": "create_table", + "statementTarget": [ + "table", + "public", + "attachment" + ], + "writes": [ + "s|tbl|public.attachment", + "n|tbl|public.attachment", + "e|tbl|public.attachment", + "n|rel|public.attachment", + "n|type|public.attachment", + "n|rel|public.attachment_pkey" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "create_table", + "statementTarget": [ + "table", + "public", + "conversation_read" + ], + "writes": [ + "s|tbl|public.conversation_read", + "n|tbl|public.conversation_read", + "e|tbl|public.conversation_read", + "n|rel|public.conversation_read", + "n|type|public.conversation_read", + "n|rel|public.conversation_read_pkey" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "create_table", + "statementTarget": [ + "table", + "public", + "message_reaction" + ], + "writes": [ + "s|tbl|public.message_reaction", + "n|tbl|public.message_reaction", + "e|tbl|public.message_reaction", + "n|rel|public.message_reaction", + "n|type|public.message_reaction", + "n|rel|public.message_reaction_pkey" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "public", + "attachment", + "attachment_message_id_idx" + ], + "writes": [ + "s|idx|public.attachment_message_id_idx", + "n|idx|public.attachment_message_id_idx", + "e|idx|public.attachment_message_id_idx", + "n|rel|public.attachment_message_id_idx" + ], + "reads": [ + "n|tbl|public.attachment", + "n|sch|public", + "n|col|public.attachment.message_id" + ] + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "public", + "attachment", + "attachment_uploader_id_idx" + ], + "writes": [ + "s|idx|public.attachment_uploader_id_idx", + "n|idx|public.attachment_uploader_id_idx", + "e|idx|public.attachment_uploader_id_idx", + "n|rel|public.attachment_uploader_id_idx" + ], + "reads": [ + "n|tbl|public.attachment", + "n|sch|public", + "n|col|public.attachment.uploader_id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "attachment" + ], + "writes": [ + "s|fk|public.attachment.attachment_uploader_id_user_id_fkey", + "n|fk|public.attachment.attachment_uploader_id_user_id_fkey", + "e|fk|public.attachment.attachment_uploader_id_user_id_fkey", + "n|con|public.attachment.attachment_uploader_id_user_id_fkey" + ], + "reads": [ + "n|tbl|public.attachment", + "n|sch|public", + "n|tbl|public.user", + "n|sch|public", + "n|col|public.attachment.uploader_id", + "n|col|public.user.id", + "e|uniqueness|public.user.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "attachment" + ], + "writes": [ + "s|fk|public.attachment.attachment_message_id_message_id_fkey", + "n|fk|public.attachment.attachment_message_id_message_id_fkey", + "e|fk|public.attachment.attachment_message_id_message_id_fkey", + "n|con|public.attachment.attachment_message_id_message_id_fkey" + ], + "reads": [ + "n|tbl|public.attachment", + "n|sch|public", + "n|tbl|public.message", + "n|sch|public", + "n|col|public.attachment.message_id", + "n|col|public.message.id", + "e|uniqueness|public.message.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "conversation_read" + ], + "writes": [ + "s|fk|public.conversation_read.conversation_read_user_id_user_id_fkey", + "n|fk|public.conversation_read.conversation_read_user_id_user_id_fkey", + "e|fk|public.conversation_read.conversation_read_user_id_user_id_fkey", + "n|con|public.conversation_read.conversation_read_user_id_user_id_fkey" + ], + "reads": [ + "n|tbl|public.conversation_read", + "n|sch|public", + "n|tbl|public.user", + "n|sch|public", + "n|col|public.conversation_read.user_id", + "n|col|public.user.id", + "e|uniqueness|public.user.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "conversation_read" + ], + "writes": [ + "s|fk|public.conversation_read.conversation_read_conversation_id_conversation_id_fkey", + "n|fk|public.conversation_read.conversation_read_conversation_id_conversation_id_fkey", + "e|fk|public.conversation_read.conversation_read_conversation_id_conversation_id_fkey", + "n|con|public.conversation_read.conversation_read_conversation_id_conversation_id_fkey" + ], + "reads": [ + "n|tbl|public.conversation_read", + "n|sch|public", + "n|tbl|public.conversation", + "n|sch|public", + "n|col|public.conversation_read.conversation_id", + "n|col|public.conversation.id", + "e|uniqueness|public.conversation.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "message_reaction" + ], + "writes": [ + "s|fk|public.message_reaction.message_reaction_message_id_message_id_fkey", + "n|fk|public.message_reaction.message_reaction_message_id_message_id_fkey", + "e|fk|public.message_reaction.message_reaction_message_id_message_id_fkey", + "n|con|public.message_reaction.message_reaction_message_id_message_id_fkey" + ], + "reads": [ + "n|tbl|public.message_reaction", + "n|sch|public", + "n|tbl|public.message", + "n|sch|public", + "n|col|public.message_reaction.message_id", + "n|col|public.message.id", + "e|uniqueness|public.message.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "message_reaction" + ], + "writes": [ + "s|fk|public.message_reaction.message_reaction_user_id_user_id_fkey", + "n|fk|public.message_reaction.message_reaction_user_id_user_id_fkey", + "e|fk|public.message_reaction.message_reaction_user_id_user_id_fkey", + "n|con|public.message_reaction.message_reaction_user_id_user_id_fkey" + ], + "reads": [ + "n|tbl|public.message_reaction", + "n|sch|public", + "n|tbl|public.user", + "n|sch|public", + "n|col|public.message_reaction.user_id", + "n|col|public.user.id", + "e|uniqueness|public.user.id" + ] + } + ], + "deltas": [ + { + "op": "create", + "row": { + "schema": "public", + "name": "attachment", + "isRlsEnabled": false, + "entityType": "tables" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "name": "conversation_read", + "isRlsEnabled": false, + "entityType": "tables" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "name": "message_reaction", + "isRlsEnabled": false, + "entityType": "tables" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "attachment", + "name": "id", + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "uuidv7()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "attachment", + "name": "uploader_id", + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "attachment", + "name": "message_id", + "type": "uuid", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "attachment", + "name": "filename", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "attachment", + "name": "content_type", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "attachment", + "name": "size", + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "attachment", + "name": "width", + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "attachment", + "name": "height", + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "attachment", + "name": "created_at", + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation_read", + "name": "user_id", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation_read", + "name": "conversation_id", + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation_read", + "name": "last_read_message_id", + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation_read", + "name": "updated_at", + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "message_reaction", + "name": "message_id", + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "message_reaction", + "name": "user_id", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "message_reaction", + "name": "emoji", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "message_reaction", + "name": "created_at", + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "attachment", + "name": "attachment_message_id_idx", + "nameExplicit": true, + "columns": [ + { + "value": "message_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "attachment", + "name": "attachment_uploader_id_idx", + "nameExplicit": true, + "columns": [ + { + "value": "uploader_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "attachment", + "name": "attachment_uploader_id_user_id_fkey", + "nameExplicit": false, + "columns": [ + "uploader_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "attachment", + "name": "attachment_message_id_message_id_fkey", + "nameExplicit": false, + "columns": [ + "message_id" + ], + "schemaTo": "public", + "tableTo": "message", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation_read", + "name": "conversation_read_user_id_user_id_fkey", + "nameExplicit": false, + "columns": [ + "user_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation_read", + "name": "conversation_read_conversation_id_conversation_id_fkey", + "nameExplicit": false, + "columns": [ + "conversation_id" + ], + "schemaTo": "public", + "tableTo": "conversation", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "message_reaction", + "name": "message_reaction_message_id_message_id_fkey", + "nameExplicit": false, + "columns": [ + "message_id" + ], + "schemaTo": "public", + "tableTo": "message", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "message_reaction", + "name": "message_reaction_user_id_user_id_fkey", + "nameExplicit": false, + "columns": [ + "user_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "conversation_read", + "name": "conversation_read_pkey", + "columns": [ + "user_id", + "conversation_id" + ], + "nameExplicit": false, + "entityType": "pks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "message_reaction", + "name": "message_reaction_pkey", + "columns": [ + "message_id", + "user_id", + "emoji" + ], + "nameExplicit": false, + "entityType": "pks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "attachment", + "name": "attachment_pkey", + "columns": [ + "id" + ], + "nameExplicit": false, + "entityType": "pks" + } + } + ] +} \ No newline at end of file diff --git a/apps/api/drizzle/20261202125304_moderation/migration.sql b/apps/api/drizzle/20261202125304_moderation/migration.sql new file mode 100644 index 0000000..529711e --- /dev/null +++ b/apps/api/drizzle/20261202125304_moderation/migration.sql @@ -0,0 +1,22 @@ +CREATE TABLE "user_block" ( + "blocker_id" text, + "blocked_id" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "user_block_pkey" PRIMARY KEY("blocker_id","blocked_id") +); +--> statement-breakpoint +CREATE TABLE "realm_ban" ( + "realm_id" uuid, + "user_id" text, + "banned_by_id" text, + "reason" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "realm_ban_pkey" PRIMARY KEY("realm_id","user_id") +); +--> statement-breakpoint +CREATE INDEX "user_block_blocked_id_idx" ON "user_block" ("blocked_id");--> statement-breakpoint +ALTER TABLE "user_block" ADD CONSTRAINT "user_block_blocker_id_user_id_fkey" FOREIGN KEY ("blocker_id") REFERENCES "user"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "user_block" ADD CONSTRAINT "user_block_blocked_id_user_id_fkey" FOREIGN KEY ("blocked_id") REFERENCES "user"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "realm_ban" ADD CONSTRAINT "realm_ban_realm_id_realm_id_fkey" FOREIGN KEY ("realm_id") REFERENCES "realm"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "realm_ban" ADD CONSTRAINT "realm_ban_user_id_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE CASCADE;--> statement-breakpoint +ALTER TABLE "realm_ban" ADD CONSTRAINT "realm_ban_banned_by_id_user_id_fkey" FOREIGN KEY ("banned_by_id") REFERENCES "user"("id") ON DELETE SET NULL; \ No newline at end of file diff --git a/apps/api/drizzle/20261202125304_moderation/snapshot.json b/apps/api/drizzle/20261202125304_moderation/snapshot.json new file mode 100644 index 0000000..1dd6bfb --- /dev/null +++ b/apps/api/drizzle/20261202125304_moderation/snapshot.json @@ -0,0 +1,483 @@ +{ + "type": "diff", + "version": "10", + "dialect": "postgres", + "id": "8564cfc4-00fe-44c7-a0c7-513a03f6696a", + "prevIds": [ + "97862caf-8fe6-4846-b50d-6852f29dfc94" + ], + "footprints": [ + { + "statementType": "create_table", + "statementTarget": [ + "table", + "public", + "user_block" + ], + "writes": [ + "s|tbl|public.user_block", + "n|tbl|public.user_block", + "e|tbl|public.user_block", + "n|rel|public.user_block", + "n|type|public.user_block", + "n|rel|public.user_block_pkey" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "create_table", + "statementTarget": [ + "table", + "public", + "realm_ban" + ], + "writes": [ + "s|tbl|public.realm_ban", + "n|tbl|public.realm_ban", + "e|tbl|public.realm_ban", + "n|rel|public.realm_ban", + "n|type|public.realm_ban", + "n|rel|public.realm_ban_pkey" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "public", + "user_block", + "user_block_blocked_id_idx" + ], + "writes": [ + "s|idx|public.user_block_blocked_id_idx", + "n|idx|public.user_block_blocked_id_idx", + "e|idx|public.user_block_blocked_id_idx", + "n|rel|public.user_block_blocked_id_idx" + ], + "reads": [ + "n|tbl|public.user_block", + "n|sch|public", + "n|col|public.user_block.blocked_id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "user_block" + ], + "writes": [ + "s|fk|public.user_block.user_block_blocker_id_user_id_fkey", + "n|fk|public.user_block.user_block_blocker_id_user_id_fkey", + "e|fk|public.user_block.user_block_blocker_id_user_id_fkey", + "n|con|public.user_block.user_block_blocker_id_user_id_fkey" + ], + "reads": [ + "n|tbl|public.user_block", + "n|sch|public", + "n|tbl|public.user", + "n|sch|public", + "n|col|public.user_block.blocker_id", + "n|col|public.user.id", + "e|uniqueness|public.user.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "user_block" + ], + "writes": [ + "s|fk|public.user_block.user_block_blocked_id_user_id_fkey", + "n|fk|public.user_block.user_block_blocked_id_user_id_fkey", + "e|fk|public.user_block.user_block_blocked_id_user_id_fkey", + "n|con|public.user_block.user_block_blocked_id_user_id_fkey" + ], + "reads": [ + "n|tbl|public.user_block", + "n|sch|public", + "n|tbl|public.user", + "n|sch|public", + "n|col|public.user_block.blocked_id", + "n|col|public.user.id", + "e|uniqueness|public.user.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "realm_ban" + ], + "writes": [ + "s|fk|public.realm_ban.realm_ban_realm_id_realm_id_fkey", + "n|fk|public.realm_ban.realm_ban_realm_id_realm_id_fkey", + "e|fk|public.realm_ban.realm_ban_realm_id_realm_id_fkey", + "n|con|public.realm_ban.realm_ban_realm_id_realm_id_fkey" + ], + "reads": [ + "n|tbl|public.realm_ban", + "n|sch|public", + "n|tbl|public.realm", + "n|sch|public", + "n|col|public.realm_ban.realm_id", + "n|col|public.realm.id", + "e|uniqueness|public.realm.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "realm_ban" + ], + "writes": [ + "s|fk|public.realm_ban.realm_ban_user_id_user_id_fkey", + "n|fk|public.realm_ban.realm_ban_user_id_user_id_fkey", + "e|fk|public.realm_ban.realm_ban_user_id_user_id_fkey", + "n|con|public.realm_ban.realm_ban_user_id_user_id_fkey" + ], + "reads": [ + "n|tbl|public.realm_ban", + "n|sch|public", + "n|tbl|public.user", + "n|sch|public", + "n|col|public.realm_ban.user_id", + "n|col|public.user.id", + "e|uniqueness|public.user.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "realm_ban" + ], + "writes": [ + "s|fk|public.realm_ban.realm_ban_banned_by_id_user_id_fkey", + "n|fk|public.realm_ban.realm_ban_banned_by_id_user_id_fkey", + "e|fk|public.realm_ban.realm_ban_banned_by_id_user_id_fkey", + "n|con|public.realm_ban.realm_ban_banned_by_id_user_id_fkey" + ], + "reads": [ + "n|tbl|public.realm_ban", + "n|sch|public", + "n|tbl|public.user", + "n|sch|public", + "n|col|public.realm_ban.banned_by_id", + "n|col|public.user.id", + "e|uniqueness|public.user.id" + ] + } + ], + "deltas": [ + { + "op": "create", + "row": { + "schema": "public", + "name": "user_block", + "isRlsEnabled": false, + "entityType": "tables" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "name": "realm_ban", + "isRlsEnabled": false, + "entityType": "tables" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "user_block", + "name": "blocker_id", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "user_block", + "name": "blocked_id", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "user_block", + "name": "created_at", + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_ban", + "name": "realm_id", + "type": "uuid", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_ban", + "name": "user_id", + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_ban", + "name": "banned_by_id", + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_ban", + "name": "reason", + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_ban", + "name": "created_at", + "type": "timestamp with time zone", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "user_block", + "name": "user_block_blocked_id_idx", + "nameExplicit": true, + "columns": [ + { + "value": "blocked_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "user_block", + "name": "user_block_blocker_id_user_id_fkey", + "nameExplicit": false, + "columns": [ + "blocker_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "user_block", + "name": "user_block_blocked_id_user_id_fkey", + "nameExplicit": false, + "columns": [ + "blocked_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_ban", + "name": "realm_ban_realm_id_realm_id_fkey", + "nameExplicit": false, + "columns": [ + "realm_id" + ], + "schemaTo": "public", + "tableTo": "realm", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_ban", + "name": "realm_ban_user_id_user_id_fkey", + "nameExplicit": false, + "columns": [ + "user_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_ban", + "name": "realm_ban_banned_by_id_user_id_fkey", + "nameExplicit": false, + "columns": [ + "banned_by_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "user_block", + "name": "user_block_pkey", + "columns": [ + "blocker_id", + "blocked_id" + ], + "nameExplicit": false, + "entityType": "pks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "realm_ban", + "name": "realm_ban_pkey", + "columns": [ + "realm_id", + "user_id" + ], + "nameExplicit": false, + "entityType": "pks" + } + } + ] +} \ No newline at end of file diff --git a/apps/api/package.json b/apps/api/package.json index 7df8d81..0d9f85a 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -24,8 +24,10 @@ "test:e2e": "vitest run --config ./vitest.config.e2e.ts", "db:generate": "drizzle-kit generate", "db:migrate": "drizzle-kit migrate", + "db:migrate:prod": "node dist/db/migrate.js", + "db:push": "drizzle-kit push", "db:studio": "drizzle-kit studio", - "auth:generate": "auth generate --config src/auth/auth.cli.ts --output src/db/schema/auth.ts --yes" + "auth:generate": "auth generate --config src/auth/auth.cli.ts --output src/db/schema/auth.ts --yes && prettier --write src/db/schema/auth.ts" }, "dependencies": { "@better-auth/drizzle-adapter": "^1.7.29", @@ -34,12 +36,24 @@ "@nestjs/core": "^12.0.1", "@nestjs/drizzle": "^0.0.2", "@nestjs/platform-express": "^12.0.1", + "@nestjs/platform-socket.io": "^12.6.3", + "@nestjs/storage": "^0.0.5", + "@nestjs/terminus": "^12.2.0", + "@nestjs/throttler": "^6.8.0", + "@nestjs/websockets": "^12.6.3", + "@repo/contracts": "workspace:*", + "@socket.io/redis-adapter": "^8.3.0", "@thallesp/nestjs-better-auth": "^2.8.0", "better-auth": "^1.7.29", "drizzle-orm": "1.0.0-rc.6", + "helmet": "^8.3.0", + "ioredis": "^6.1.0", + "livekit-server-sdk": "^2.20.1", "pg": "^8.23.1", "reflect-metadata": "^0.2.2", - "rxjs": "^7.8.1" + "rxjs": "^7.8.1", + "socket.io": "^4.8.4", + "zod": "^4.6.7" }, "devDependencies": { "@nestjs/cli": "^12.0.0", @@ -55,6 +69,7 @@ "@vitest/coverage-v8": "^4.1.2", "auth": "1.7.29", "drizzle-kit": "1.0.0-rc.6", + "socket.io-client": "^4.8.4", "source-map-support": "^0.5.21", "supertest": "^7.0.0", "typescript": "^6.0.2", diff --git a/apps/api/src/app.controller.ts b/apps/api/src/app.controller.ts index 76006be..f5821f8 100644 --- a/apps/api/src/app.controller.ts +++ b/apps/api/src/app.controller.ts @@ -1,11 +1,6 @@ import { Controller, Get } from '@nestjs/common'; -import { - AllowAnonymous, - Session, - type UserSession, -} from '@thallesp/nestjs-better-auth'; +import { AllowAnonymous } from '@thallesp/nestjs-better-auth'; import { AppService } from './app.service'; -import type { Auth } from './auth/auth'; @Controller() export class AppController { @@ -16,10 +11,4 @@ export class AppController { getHello(): string { return this.appService.getHello(); } - - /** The signed-in user; 401 without a session. */ - @Get('me') - getMe(@Session() session: UserSession) { - return session.user; - } } diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts index 632bce5..c1cb19f 100644 --- a/apps/api/src/app.module.ts +++ b/apps/api/src/app.module.ts @@ -1,21 +1,38 @@ -import { Module } from '@nestjs/common'; +import type { IncomingMessage } from 'node:http'; +import type { Redis } from 'ioredis'; +import { Module, StandardSchemaValidationPipe } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; +import { APP_PIPE } from '@nestjs/core'; import { DrizzleModule, getDrizzleToken } from '@nestjs/drizzle'; import { AuthModule } from '@thallesp/nestjs-better-auth'; import { drizzle } from 'drizzle-orm/node-postgres'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { createAuth } from './auth/auth'; +import { CallsModule } from './calls/calls.module'; +import { envSchema, type Env } from './config/env'; import type { Database } from './db/database'; import { relations } from './db/relations'; +import { ConversationsModule } from './conversations/conversations.module'; +import { FILES_ROUTE } from './files/files.disk'; +import { FilesModule } from './files/files.module'; +import { FriendsModule } from './friends/friends.module'; +import { HealthModule } from './health/health.module'; +import { RateLimitModule } from './rate-limit/rate-limit.module'; +import { RealmsModule } from './realms/realms.module'; +import { RealtimeGatewayModule } from './realtime/realtime-gateway.module'; +import { RealtimeModule } from './realtime/realtime.module'; +import { RealtimeService } from './realtime/realtime.service'; +import { REDIS, RedisModule } from './redis/redis.module'; +import { UsersModule } from './users/users.module'; @Module({ imports: [ - ConfigModule.forRoot({ isGlobal: true }), + ConfigModule.forRoot({ isGlobal: true, validationSchema: envSchema }), DrizzleModule.forRootAsync({ - useFactory: (config: ConfigService) => ({ + useFactory: (config: ConfigService) => ({ drizzle, - connection: config.getOrThrow('DATABASE_URL'), + connection: config.getOrThrow('DATABASE_URL', { infer: true }), relations, }), inject: [ConfigService], @@ -23,20 +40,62 @@ import { relations } from './db/relations'; // Serves /api/auth/* and puts every other route behind sign-in; // open one with @AllowAnonymous(). AuthModule.forRootAsync({ - useFactory: (db: Database, config: ConfigService) => ({ + imports: [RealtimeModule, RedisModule], + useFactory: ( + db: Database, + config: ConfigService, + realtime: RealtimeService, + redis: Redis, + ) => ({ auth: createAuth(db, { - secret: config.getOrThrow('BETTER_AUTH_SECRET'), - baseURL: config.getOrThrow('BETTER_AUTH_URL'), - trustedOrigins: (config.get('TRUSTED_ORIGINS') ?? '') - .split(',') - .map((origin) => origin.trim()) - .filter(Boolean), + secret: config.getOrThrow('BETTER_AUTH_SECRET', { infer: true }), + baseURL: config.getOrThrow('BETTER_AUTH_URL', { infer: true }), + trustedOrigins: config.getOrThrow('TRUSTED_ORIGINS', { infer: true }), + // A signed-out session must not keep receiving events. + onSessionEnded: (sessionId) => realtime.disconnectSession(sessionId), + rateLimit: config.getOrThrow('RATE_LIMIT', { infer: true }) + ? { redis } + : false, }), + // The module's own CORS setup leaves out PATCH; main.ts enables CORS. + disableTrustedOriginsCors: true, + // A file sent to a signed upload URL is stored as it arrives, a JSON + // file included, so the body parsers leave those requests alone. + bodyParser: { + json: { type: parsedAs('application/json') }, + urlencoded: { type: parsedAs('application/x-www-form-urlencoded') }, + }, }), - inject: [getDrizzleToken(), ConfigService], + inject: [getDrizzleToken(), ConfigService, RealtimeService, REDIS], }), + // After AuthModule, so its guard knows who is asking. + RateLimitModule, + HealthModule, + FilesModule, + RealtimeGatewayModule, + UsersModule, + FriendsModule, + ConversationsModule, + RealmsModule, + CallsModule, ], controllers: [AppController], - providers: [AppService], + providers: [ + AppService, + // Validates every parameter that declares a schema, e.g. + // @Body({ schema: updateProfileSchema }), and answers 400 otherwise. + { provide: APP_PIPE, useClass: StandardSchemaValidationPipe }, + ], }) export class AppModule {} + +/** Matches requests with this content type, except uploads to /files. */ +function parsedAs(contentType: string) { + // Express keeps the whole address in `originalUrl`; `url` has lost the + // part the middleware is mounted on. + return (req: IncomingMessage & { originalUrl?: string }) => + !( + req.method === 'PUT' && + (req.originalUrl ?? req.url)?.startsWith(`/${FILES_ROUTE}?`) + ) && req.headers['content-type']?.startsWith(contentType) === true; +} diff --git a/apps/api/src/attachments/attachments.cleanup.ts b/apps/api/src/attachments/attachments.cleanup.ts new file mode 100644 index 0000000..c9791ac --- /dev/null +++ b/apps/api/src/attachments/attachments.cleanup.ts @@ -0,0 +1,41 @@ +import { + Injectable, + Logger, + type OnModuleDestroy, + type OnModuleInit, +} from '@nestjs/common'; +import { AttachmentsService } from './attachments.service'; + +const EVERY_MS = 60 * 60 * 1000; + +/** + * Clears out abandoned uploads once an hour. Every instance of the API does + * it; the work is small and doing it twice does no harm. + */ +@Injectable() +export class AttachmentsCleanup implements OnModuleInit, OnModuleDestroy { + private readonly logger = new Logger(AttachmentsCleanup.name); + private timer: NodeJS.Timeout | undefined; + + constructor(private readonly attachments: AttachmentsService) {} + + onModuleInit() { + this.timer = setInterval(() => void this.run(), EVERY_MS); + // Never the reason the process stays alive. + this.timer.unref(); + } + + onModuleDestroy() { + clearInterval(this.timer); + } + + private async run() { + try { + const removed = await this.attachments.removeAbandoned(); + if (removed > 0) + this.logger.log('Removed abandoned uploads', { removed }); + } catch (error) { + this.logger.error('Could not remove abandoned uploads', error); + } + } +} diff --git a/apps/api/src/attachments/attachments.controller.ts b/apps/api/src/attachments/attachments.controller.ts new file mode 100644 index 0000000..bbda18b --- /dev/null +++ b/apps/api/src/attachments/attachments.controller.ts @@ -0,0 +1,70 @@ +import { + Body, + Controller, + Delete, + Get, + Header, + HttpCode, + Param, + Post, + Redirect, +} from '@nestjs/common'; +import { + attachmentIdSchema, + createAttachmentSchema, + type CreateAttachment, +} from '@repo/contracts'; +import { Session, type UserSession } from '@thallesp/nestjs-better-auth'; +import type { Auth } from '../auth/auth'; +import { AttachmentsService } from './attachments.service'; +import { AtMost } from '../rate-limit/at-most'; +import { SkipThrottle } from '@nestjs/throttler'; + +/** + * Files for messages. Sending one takes three steps: POST here with its + * name, type and size; PUT the bytes to the address in the answer; then + * list the attachment's id in POST /conversations/:id/messages. + */ +@Controller('attachments') +export class AttachmentsController { + constructor(private readonly attachments: AttachmentsService) {} + + @Post() + @AtMost(30, { seconds: 60 }) + create( + @Session() session: UserSession, + @Body({ schema: createAttachmentSchema }) body: CreateAttachment, + ) { + return this.attachments.create(session.user.id, body); + } + + /** + * Redirects to the file itself, for anyone who can read its message, so + * this address works as an image source or a link. Browsers may reuse the + * redirect for a few minutes, for less time than it stays valid. + */ + // A page of history asks for every picture on it at once. + @SkipThrottle() + @Get(':id') + @Redirect() + @Header('Cache-Control', 'private, max-age=300') + async download( + @Session() session: UserSession, + @Param('id', { schema: attachmentIdSchema }) id: string, + ) { + return { + url: await this.attachments.downloadUrl(session.user.id, id), + statusCode: 302, + }; + } + + /** Takes back a file that was uploaded and not sent. */ + @Delete(':id') + @HttpCode(204) + remove( + @Session() session: UserSession, + @Param('id', { schema: attachmentIdSchema }) id: string, + ) { + return this.attachments.remove(session.user.id, id); + } +} diff --git a/apps/api/src/attachments/attachments.module.ts b/apps/api/src/attachments/attachments.module.ts new file mode 100644 index 0000000..0cc7bca --- /dev/null +++ b/apps/api/src/attachments/attachments.module.ts @@ -0,0 +1,21 @@ +import { Module } from '@nestjs/common'; +import { ConversationsRepository } from '../conversations/conversations.repository'; +import { AttachmentsCleanup } from './attachments.cleanup'; +import { AttachmentsController } from './attachments.controller'; +import { AttachmentsRepository } from './attachments.repository'; +import { AttachmentsService } from './attachments.service'; + +@Module({ + controllers: [AttachmentsController], + // ConversationsRepository is listed here rather than importing its module + // (which imports this one): it has no state, and is only asked who can + // read a message. + providers: [ + AttachmentsService, + AttachmentsRepository, + AttachmentsCleanup, + ConversationsRepository, + ], + exports: [AttachmentsService], +}) +export class AttachmentsModule {} diff --git a/apps/api/src/attachments/attachments.repository.ts b/apps/api/src/attachments/attachments.repository.ts new file mode 100644 index 0000000..e8c9f4f --- /dev/null +++ b/apps/api/src/attachments/attachments.repository.ts @@ -0,0 +1,96 @@ +import { Injectable } from '@nestjs/common'; +import { InjectDrizzle } from '@nestjs/drizzle'; +import { and, eq, gt, inArray, isNull, lt, sql } from 'drizzle-orm'; +import type { Database } from '../db/database'; +import { attachment } from '../db/schema'; + +export type AttachmentRow = typeof attachment.$inferSelect; +type NewAttachment = Pick< + typeof attachment.$inferInsert, + 'uploaderId' | 'filename' | 'contentType' | 'size' | 'width' | 'height' +>; + +@Injectable() +export class AttachmentsRepository { + constructor(@InjectDrizzle() private readonly db: Database) {} + + async create(values: NewAttachment): Promise { + const [row] = await this.db.insert(attachment).values(values).returning(); + return row; + } + + /** How many files someone has uploaded since `since` and not sent. */ + async countPending(uploaderId: string, since: Date): Promise { + const [row] = await this.db + .select({ count: sql`count(*)::int` }) + .from(attachment) + .where( + and( + eq(attachment.uploaderId, uploaderId), + isNull(attachment.messageId), + gt(attachment.createdAt, since), + ), + ); + return row.count; + } + + /** An attachment and, when it was sent, the message it is on. */ + findWithMessage(id: string) { + return this.db.query.attachment.findFirst({ + where: { id }, + with: { message: true }, + }); + } + + /** Those of the given files that this person uploaded and hasn't sent. */ + findPending(ids: string[], uploaderId: string): Promise { + if (ids.length === 0) return Promise.resolve([]); + return this.db + .select() + .from(attachment) + .where( + and( + inArray(attachment.id, ids), + eq(attachment.uploaderId, uploaderId), + isNull(attachment.messageId), + ), + ); + } + + /** Forgets an upload that wasn't sent. False when there was none. */ + async deletePending(id: string, uploaderId: string): Promise { + const rows = await this.db + .delete(attachment) + .where( + and( + eq(attachment.id, id), + eq(attachment.uploaderId, uploaderId), + isNull(attachment.messageId), + ), + ) + .returning({ id: attachment.id }); + return rows.length > 0; + } + + /** + * Forgets up to `limit` attachments made before `before` that are on no + * message, and answers with their ids so their files can go too. + */ + async deleteAbandoned(before: Date, limit: number): Promise { + const abandoned = this.db + .select({ id: attachment.id }) + .from(attachment) + .where( + and(isNull(attachment.messageId), lt(attachment.createdAt, before)), + ) + .limit(limit); + const rows = await this.db + .delete(attachment) + // Checked again on the row itself: one may have just been sent. + .where( + and(inArray(attachment.id, abandoned), isNull(attachment.messageId)), + ) + .returning({ id: attachment.id }); + return rows.map((row) => row.id); + } +} diff --git a/apps/api/src/attachments/attachments.service.spec.ts b/apps/api/src/attachments/attachments.service.spec.ts new file mode 100644 index 0000000..80bc92d --- /dev/null +++ b/apps/api/src/attachments/attachments.service.spec.ts @@ -0,0 +1,38 @@ +import { InMemoryDisk } from '@nestjs/storage'; +import type { ConversationsRepository } from '../conversations/conversations.repository'; +import type { AttachmentsRepository } from './attachments.repository'; +import { + ABANDONED_AFTER_MS, + attachmentKey, + AttachmentsService, +} from './attachments.service'; + +describe('AttachmentsService.removeAbandoned', () => { + it('deletes the files of the rows it removed, batch after batch', async () => { + const disk = new InMemoryDisk({}); + for (const id of ['a', 'b', 'c', 'kept']) { + await disk.put(attachmentKey(id), 'bytes'); + } + const deleteAbandoned = vi + .fn() + .mockResolvedValueOnce(['a', 'b']) + .mockResolvedValueOnce(['c']) + .mockResolvedValue([]); + const service = new AttachmentsService( + { deleteAbandoned } as unknown as AttachmentsRepository, + {} as ConversationsRepository, + disk, + ); + + const now = new Date('2026-12-02T12:00:00Z'); + expect(await service.removeAbandoned(now)).toBe(3); + + // Only what is a day old is asked for. + expect(deleteAbandoned.mock.calls[0][0]).toEqual( + new Date(now.getTime() - ABANDONED_AFTER_MS), + ); + expect(await disk.exists(attachmentKey('a'))).toBe(false); + expect(await disk.exists(attachmentKey('c'))).toBe(false); + expect(await disk.exists(attachmentKey('kept'))).toBe(true); + }); +}); diff --git a/apps/api/src/attachments/attachments.service.ts b/apps/api/src/attachments/attachments.service.ts new file mode 100644 index 0000000..68f7f04 --- /dev/null +++ b/apps/api/src/attachments/attachments.service.ts @@ -0,0 +1,170 @@ +import { + BadRequestException, + HttpException, + HttpStatus, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import { + INLINE_IMAGE_TYPES, + PENDING_ATTACHMENTS_MAX, + type Attachment, + type AttachmentUpload, + type CreateAttachment, +} from '@repo/contracts'; +import { StorageDisk, StorageFileNotFoundError } from '@nestjs/storage'; +import { ConversationsRepository } from '../conversations/conversations.repository'; +import { + AttachmentsRepository, + type AttachmentRow, +} from './attachments.repository'; + +/** How long an upload that was never sent is kept. */ +export const ABANDONED_AFTER_MS = 24 * 60 * 60 * 1000; +const CLEANUP_BATCH = 200; + +/** Where an attachment's file is kept in storage. */ +export const attachmentKey = (id: string) => `attachments/${id}`; + +export function toAttachment(row: AttachmentRow): Attachment { + return { + id: row.id, + filename: row.filename, + contentType: row.contentType, + size: row.size, + width: row.width, + height: row.height, + }; +} + +/** + * Files posted with messages. The bytes never pass through the API's own + * routes: the browser sends them to a signed upload URL and fetches them + * from a signed download URL, both made here. + */ +@Injectable() +export class AttachmentsService { + constructor( + private readonly attachments: AttachmentsRepository, + private readonly conversations: ConversationsRepository, + private readonly disk: StorageDisk, + ) {} + + /** Notes a file about to be uploaded and says where to send it. */ + async create( + userId: string, + file: CreateAttachment, + ): Promise { + const since = new Date(Date.now() - ABANDONED_AFTER_MS); + const pending = await this.attachments.countPending(userId, since); + if (pending >= PENDING_ATTACHMENTS_MAX) { + throw new HttpException( + 'You have too many files waiting to be sent. Send or remove some first.', + HttpStatus.TOO_MANY_REQUESTS, + ); + } + + // Sizes are only kept for what the chat shows as a picture. + const isPicture = INLINE_IMAGE_TYPES.includes(file.contentType); + const row = await this.attachments.create({ + uploaderId: userId, + filename: file.filename, + contentType: file.contentType, + size: file.size, + width: isPicture ? (file.width ?? null) : null, + height: isPicture ? (file.height ?? null) : null, + }); + // Signed for this type and exactly this many bytes, so the limit checked + // on `size` holds for what is actually sent. + const upload = await this.disk.signedUpload(attachmentKey(row.id), { + contentType: row.contentType, + contentLength: row.size, + expiresIn: '15m', + }); + return { + attachment: toAttachment(row), + upload: { + url: upload.url, + method: upload.method, + headers: upload.headers, + }, + }; + } + + /** Takes back an upload that wasn't sent. */ + async remove(userId: string, attachmentId: string): Promise { + if (!(await this.attachments.deletePending(attachmentId, userId))) { + throw new NotFoundException('File not found.'); + } + await this.disk.delete(attachmentKey(attachmentId)); + } + + /** + * A short-lived address for a file, for someone who can read the message + * it is on (or who uploaded it and hasn't sent it yet). Pictures open in + * the browser; everything else downloads under its own name. + */ + async downloadUrl(userId: string, attachmentId: string): Promise { + const row = await this.attachments.findWithMessage(attachmentId); + const allowed = + row && + (row.message + ? await this.conversations.canRead(row.message.conversationId, userId) + : row.uploaderId === userId); + // The same answer for a file that isn't theirs to see, so ids can't be + // probed for existence. + if (!allowed) throw new NotFoundException('File not found.'); + return this.disk.signedUrl(attachmentKey(row.id), { + expiresIn: '10m', + filename: row.filename, + disposition: INLINE_IMAGE_TYPES.includes(row.contentType) + ? 'inline' + : 'attachment', + }); + } + + /** + * Checks, before a message is posted, that each file is the sender's, not + * on a message yet and fully uploaded. + */ + async assertReady(userId: string, attachmentIds: string[]): Promise { + if (attachmentIds.length === 0) return; + const rows = await this.attachments.findPending(attachmentIds, userId); + if (rows.length !== attachmentIds.length) { + throw new BadRequestException( + 'A file is missing or was already sent. Attach it again.', + ); + } + await Promise.all(rows.map((row) => this.assertUploaded(row))); + } + + private async assertUploaded(row: AttachmentRow) { + try { + const file = await this.disk.stat(attachmentKey(row.id)); + if (file.size === row.size) return; + } catch (error) { + if (!(error instanceof StorageFileNotFoundError)) throw error; + } + throw new BadRequestException( + `"${row.filename}" hasn't finished uploading.`, + ); + } + + /** + * Deletes uploads that were never sent and files whose message is gone + * (deleted with its conversation, realm or author), once they are a day + * old. Answers with how many went. + */ + async removeAbandoned(now = new Date()): Promise { + const before = new Date(now.getTime() - ABANDONED_AFTER_MS); + let removed = 0; + for (;;) { + // Rows first: a file without a row is only wasted space, while a row + // without its file would be a broken attachment. + const ids = await this.attachments.deleteAbandoned(before, CLEANUP_BATCH); + if (ids.length === 0) return removed; + await this.disk.delete(ids.map(attachmentKey)); + removed += ids.length; + } + } +} diff --git a/apps/api/src/auth/auth.ts b/apps/api/src/auth/auth.ts index e4bf48a..5ad10c4 100644 --- a/apps/api/src/auth/auth.ts +++ b/apps/api/src/auth/auth.ts @@ -1,7 +1,17 @@ import { drizzleAdapter } from '@better-auth/drizzle-adapter/relations-v2'; +import { + displayNameSchema, + USERNAME_MAX_LENGTH, + USERNAME_MIN_LENGTH, + USERNAME_PATTERN, +} from '@repo/contracts'; import { betterAuth } from 'better-auth'; +import { APIError, createAuthMiddleware } from 'better-auth/api'; +import { username } from 'better-auth/plugins'; +import type { Redis } from 'ioredis'; import type { Database } from '../db/database'; import * as schema from '../db/schema'; +import { countInWindow } from '../rate-limit/fixed-window'; export interface AuthConfig { /** Signs cookies and tokens. At least 32 random bytes. */ @@ -10,8 +20,23 @@ export interface AuthConfig { baseURL: string; /** Front-end origins allowed to call the auth endpoints. */ trustedOrigins: string[]; + /** Called when a session ends (sign-out, revocation), with its id. */ + onSessionEnded?: (sessionId: string) => void; + /** + * Limits how often one address may call the auth endpoints, counted in + * this Redis so the limit holds across API instances. Off when false or + * left out. + */ + rateLimit?: { redis: Redis } | false; } +/** + * The request header Better Auth reads the caller's address from, for its + * rate limits and the session list. `setUpHttp()` overwrites it on every + * request with the address Express worked out, so a caller can't choose it. + */ +export const CLIENT_ADDRESS_HEADER = 'x-client-address'; + /** * Builds the Better Auth instance on top of the app's Drizzle database. * Auth endpoints are served under /api/auth/*. @@ -20,12 +45,100 @@ export interface AuthConfig { * `pnpm auth:generate` and then `pnpm db:generate`. */ export function createAuth(db: Database, config: AuthConfig) { + const { rateLimit } = config; return betterAuth({ secret: config.secret, baseURL: config.baseURL, trustedOrigins: config.trustedOrigins, database: drizzleAdapter(db, { provider: 'pg', schema }), - emailAndPassword: { enabled: true }, + // Per address: 100 calls in 10 seconds, and far fewer for the routes + // that check a password, so guessing one is slow. + rateLimit: rateLimit + ? { + enabled: true, + window: 10, + max: 100, + customRules: { + '/sign-in/*': { window: 60, max: 10 }, + '/sign-up/*': { window: 60, max: 5 }, + '/change-password': { window: 60, max: 5 }, + }, + customStorage: { + consume: async (key, { window, max }) => { + const { hits, remainingMs } = await countInWindow( + rateLimit.redis, + `auth:${key}`, + window * 1000, + ); + return hits > max + ? { allowed: false, retryAfter: Math.ceil(remainingMs / 1000) } + : { allowed: true, retryAfter: null }; + }, + }, + } + : { enabled: false }, + advanced: { + ipAddress: { + ipAddressHeaders: [CLIENT_ADDRESS_HEADER], + }, + }, + // Sign-up signs the user in straight away; no email confirmation step. + emailAndPassword: { enabled: true, requireEmailVerification: false }, + user: { + additionalFields: { + // Edited through PATCH /users/me, not through the auth endpoints. + bio: { type: 'string', required: false, input: false }, + }, + }, + plugins: [ + // Adds a unique, lower-cased `username` to users, plus sign-in by + // username. The rules are the ones in @repo/contracts. + username({ + displayUsername: false, + minUsernameLength: USERNAME_MIN_LENGTH, + maxUsernameLength: USERNAME_MAX_LENGTH, + usernameValidator: (value) => USERNAME_PATTERN.test(value), + validationOrder: { username: 'post-normalization' }, + }), + ], + databaseHooks: { + session: { + delete: { + after: async (session) => { + config.onSessionEnded?.(session.id); + }, + }, + }, + }, + hooks: { + before: createAuthMiddleware(async (ctx) => { + if (ctx.path !== '/sign-up/email' && ctx.path !== '/update-user') { + return; + } + const body = ctx.body as Record | undefined; + + // The plugin treats the username as optional; new accounts need one. + if ( + ctx.path === '/sign-up/email' && + typeof body?.username !== 'string' + ) { + throw new APIError('BAD_REQUEST', { + message: 'Username is required.', + }); + } + + // Same display-name rules as PATCH /users/me. + if (body?.name !== undefined) { + const name = displayNameSchema.safeParse(body.name); + if (!name.success) { + throw new APIError('BAD_REQUEST', { + message: name.error.issues[0]?.message ?? 'Name is invalid.', + }); + } + return { context: { ...ctx, body: { ...body, name: name.data } } }; + } + }), + }, }); } diff --git a/apps/api/src/calls/call-rooms.ts b/apps/api/src/calls/call-rooms.ts new file mode 100644 index 0000000..dbb4675 --- /dev/null +++ b/apps/api/src/calls/call-rooms.ts @@ -0,0 +1,60 @@ +import { Injectable } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { RoomServiceClient, ServerError } from 'livekit-server-sdk'; +import type { Env } from '../config/env'; + +/** + * The calls as the LiveKit server has them. Each call is a LiveKit room + * named after its conversation, and the people in it go by their user ids. + * Only CallsService talks to this; e2e tests put a stand-in in its place. + */ +@Injectable() +export class CallRooms { + private readonly client: RoomServiceClient | undefined; + + constructor(config: ConfigService) { + const url = + config.get('LIVEKIT_INTERNAL_URL', { infer: true }) ?? + config.get('LIVEKIT_URL', { infer: true }); + this.client = url + ? new RoomServiceClient( + url, + config.get('LIVEKIT_API_KEY', { infer: true }), + config.get('LIVEKIT_API_SECRET', { infer: true }), + ) + : undefined; + } + + /** The names of the rooms with a call going on. */ + async list(): Promise { + const rooms = (await this.client?.listRooms()) ?? []; + return rooms.map((room) => room.name); + } + + /** Who is in a room, first to join first. Nobody when there is no room. */ + async participants(room: string): Promise { + const participants = (await this.client?.listParticipants(room)) ?? []; + return participants + .toSorted((a, b) => Number(a.joinedAtMs - b.joinedAtMs)) + .map((participant) => participant.identity); + } + + /** Disconnects someone from a room; fine if they weren't in it. */ + async remove(room: string, identity: string): Promise { + await ignoreMissing(this.client?.removeParticipant(room, identity)); + } + + /** Ends a call for everyone in it; fine if there was none. */ + async close(room: string): Promise { + await ignoreMissing(this.client?.deleteRoom(room)); + } +} + +async function ignoreMissing(request: Promise | undefined) { + try { + await request; + } catch (error) { + if (error instanceof ServerError && error.status === 404) return; + throw error; + } +} diff --git a/apps/api/src/calls/calls.controller.ts b/apps/api/src/calls/calls.controller.ts new file mode 100644 index 0000000..09b4ec5 --- /dev/null +++ b/apps/api/src/calls/calls.controller.ts @@ -0,0 +1,75 @@ +import { + Controller, + Get, + Headers, + HttpCode, + Param, + PayloadTooLargeException, + Post, + Req, +} from '@nestjs/common'; +import { conversationIdSchema } from '@repo/contracts'; +import { + AllowAnonymous, + Session, + type UserSession, +} from '@thallesp/nestjs-better-auth'; +import type { Request } from 'express'; +import type { Auth } from '../auth/auth'; +import { CallsService } from './calls.service'; +import { AtMost } from '../rate-limit/at-most'; +import { SkipThrottle } from '@nestjs/throttler'; + +// Reports are a few kilobytes; nothing genuine comes near this. +const WEBHOOK_MAX_BYTES = 256 * 1024; + +@Controller() +export class CallsController { + constructor(private readonly calls: CallsService) {} + + /** The calls going on in the user's conversations and cauldrons. */ + @Get('calls') + overview(@Session() session: UserSession) { + return this.calls.overview(session.user.id); + } + + /** What the browser needs to join the call here; the first one in starts it. */ + @Post('conversations/:id/call') + @AtMost(20, { seconds: 60 }) + @HttpCode(200) + join( + @Session() session: UserSession, + @Param('id', { schema: conversationIdSchema }) conversationId: string, + ) { + return this.calls.join(session.user.id, conversationId); + } + + /** + * Where the media server reports who joined and left. No session: the + * report is signed with the server's own key, over the body exactly as + * sent, which is why the body is read here and not parsed on the way in + * (its type, application/webhook+json, isn't one the parsers take). + */ + @Post('livekit/webhook') + @AllowAnonymous() + // All of them come from the one media server, as fast as people join. + @SkipThrottle() + @HttpCode(200) + async webhook( + @Req() req: Request, + @Headers('authorization') authorization: string | undefined, + ) { + await this.calls.handleWebhook(await readText(req), authorization); + } +} + +async function readText(req: Request): Promise { + const chunks: Buffer[] = []; + let size = 0; + for await (const chunk of req as AsyncIterable) { + size += chunk.length; + if (size > WEBHOOK_MAX_BYTES) throw new PayloadTooLargeException(); + chunks.push(chunk); + } + return Buffer.concat(chunks).toString('utf8'); +} diff --git a/apps/api/src/calls/calls.module.ts b/apps/api/src/calls/calls.module.ts new file mode 100644 index 0000000..a3cfd70 --- /dev/null +++ b/apps/api/src/calls/calls.module.ts @@ -0,0 +1,34 @@ +import { Module } from '@nestjs/common'; +import { ConversationAccess } from '../conversations/conversation-access'; +import { ConversationsRepository } from '../conversations/conversations.repository'; +import { FriendsRepository } from '../friends/friends.repository'; +import { RealmsRepository } from '../realms/realms.repository'; +import { RealtimeModule } from '../realtime/realtime.module'; +import { RedisModule } from '../redis/redis.module'; +import { UsersRepository } from '../users/users.repository'; +import { CallRooms } from './call-rooms'; +import { CallsController } from './calls.controller'; +import { CallsReconciler } from './calls.reconciler'; +import { CallsService } from './calls.service'; +import { CallsStore } from './calls.store'; + +@Module({ + imports: [RealtimeModule, RedisModule], + controllers: [CallsController], + // The other features' repositories and the access check have no state; + // they are listed here rather than importing their modules, which import + // this one to take people out of calls. + providers: [ + CallsService, + CallsStore, + CallRooms, + CallsReconciler, + ConversationAccess, + ConversationsRepository, + FriendsRepository, + RealmsRepository, + UsersRepository, + ], + exports: [CallsService], +}) +export class CallsModule {} diff --git a/apps/api/src/calls/calls.reconciler.ts b/apps/api/src/calls/calls.reconciler.ts new file mode 100644 index 0000000..888bc08 --- /dev/null +++ b/apps/api/src/calls/calls.reconciler.ts @@ -0,0 +1,46 @@ +import { + Injectable, + Logger, + type OnModuleDestroy, + type OnModuleInit, +} from '@nestjs/common'; +import { CallsService } from './calls.service'; + +const EVERY_MS = 60 * 1000; + +/** + * Checks what the API remembers about calls against the media server once + * a minute. Reports from the media server keep the two in step the rest of + * the time; this is for the ones that never arrived. Every instance of the + * API does it, and doing it twice does no harm. + */ +@Injectable() +export class CallsReconciler implements OnModuleInit, OnModuleDestroy { + private readonly logger = new Logger(CallsReconciler.name); + private timer: NodeJS.Timeout | undefined; + private failing = false; + + constructor(private readonly calls: CallsService) {} + + onModuleInit() { + if (!this.calls.enabled) return; + this.timer = setInterval(() => void this.run(), EVERY_MS); + // Never the reason the process stays alive. + this.timer.unref(); + } + + onModuleDestroy() { + clearInterval(this.timer); + } + + private async run() { + try { + await this.calls.reconcile(); + this.failing = false; + } catch (error) { + // Once per outage, not once a minute for as long as it lasts. + if (!this.failing) this.logger.error('Could not check on calls', error); + this.failing = true; + } + } +} diff --git a/apps/api/src/calls/calls.service.spec.ts b/apps/api/src/calls/calls.service.spec.ts new file mode 100644 index 0000000..8c6a4c5 --- /dev/null +++ b/apps/api/src/calls/calls.service.spec.ts @@ -0,0 +1,115 @@ +import { NotFoundException, ServiceUnavailableException } from '@nestjs/common'; +import type { ConfigService } from '@nestjs/config'; +import type { Env } from '../config/env'; +import type { ConversationAccess } from '../conversations/conversation-access'; +import type { ConversationsRepository } from '../conversations/conversations.repository'; +import type { RealmsRepository } from '../realms/realms.repository'; +import type { RealtimeService } from '../realtime/realtime.service'; +import type { UsersRepository } from '../users/users.repository'; +import type { CallRooms } from './call-rooms'; +import { CallsService } from './calls.service'; +import type { CallsStore, CallState } from './calls.store'; + +const LIVEKIT: Partial = { + LIVEKIT_URL: 'ws://livekit.invalid', + LIVEKIT_API_KEY: 'key', + LIVEKIT_API_SECRET: 'secret-0123456789-0123456789-0123456789', +}; + +const REMEMBERED = '019adf00-0000-7000-8000-000000000001'; +const UNHEARD_OF = '019adf00-0000-7000-8000-000000000002'; + +/** A service over a media server and a store that are plain maps. */ +function setUp(env: Partial) { + const live = new Map(); + const remembered = new Map(); + const emitToUsers = vi.fn(); + const service = new CallsService( + { + get: (name: keyof Env) => env[name], + } as unknown as ConfigService, + {} as ConversationAccess, + { + findAudience: () => Promise.resolve({ userIds: ['ann', 'ben'] }), + } as unknown as ConversationsRepository, + {} as RealmsRepository, + { + findByIds: (ids: string[]) => + Promise.resolve( + ids.map((id) => ({ id, name: id, username: id, image: null })), + ), + } as unknown as UsersRepository, + { + list: () => Promise.resolve([...live.keys()]), + participants: (room: string) => Promise.resolve(live.get(room) ?? []), + } as unknown as CallRooms, + { + ids: () => Promise.resolve([...remembered.keys()]), + get: (id: string) => Promise.resolve(remembered.get(id)), + set: (id: string, state: CallState) => + Promise.resolve(void remembered.set(id, state)), + delete: (id: string) => Promise.resolve(void remembered.delete(id)), + } as unknown as CallsStore, + { emitToUsers } as unknown as RealtimeService, + ); + return { service, live, remembered, emitToUsers }; +} + +describe('CallsService', () => { + it('is switched off without a media server', async () => { + const { service } = setUp({}); + expect(service.enabled).toBe(false); + expect(await service.overview('ann')).toEqual({ + enabled: false, + calls: [], + }); + await expect(service.join('ann', REMEMBERED)).rejects.toThrow( + ServiceUnavailableException, + ); + await expect(service.handleWebhook('{}', 'token')).rejects.toThrow( + NotFoundException, + ); + // Nothing to put right, and nothing is asked of anyone. + await service.reconcile(); + await service.removeParticipant(REMEMBERED, 'ann'); + }); + + it('reconciles what it remembers with what the media server has', async () => { + const { service, live, remembered, emitToUsers } = setUp(LIVEKIT); + // A call that ended without a report, and one that started without. + remembered.set(REMEMBERED, { + realmId: null, + userIds: ['ann'], + startedAt: '2026-12-02T10:00:00.000Z', + }); + live.set(UNHEARD_OF, ['ben', 'ann']); + live.set('not-one-of-ours', ['someone']); + + await service.reconcile(); + + expect([...remembered.keys()]).toEqual([UNHEARD_OF]); + expect(remembered.get(UNHEARD_OF)?.userIds).toEqual(['ben', 'ann']); + const told = emitToUsers.mock.calls.map(([, , call]) => call); + expect(told).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + conversationId: REMEMBERED, + participants: [], + startedAt: '2026-12-02T10:00:00.000Z', + }), + expect.objectContaining({ + conversationId: UNHEARD_OF, + participants: [ + expect.objectContaining({ id: 'ben' }), + expect.objectContaining({ id: 'ann' }), + ], + }), + ]), + ); + expect(told).toHaveLength(2); + + // With the two in step, another pass says nothing. + await service.reconcile(); + expect(emitToUsers).toHaveBeenCalledTimes(2); + }); +}); diff --git a/apps/api/src/calls/calls.service.ts b/apps/api/src/calls/calls.service.ts new file mode 100644 index 0000000..0c39727 --- /dev/null +++ b/apps/api/src/calls/calls.service.ts @@ -0,0 +1,327 @@ +import { + ForbiddenException, + Injectable, + Logger, + NotFoundException, + ServiceUnavailableException, + UnauthorizedException, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { + conversationIdSchema, + type Call, + type CallAccess, + type CallsOverview, +} from '@repo/contracts'; +import { AccessToken, WebhookReceiver } from 'livekit-server-sdk'; +import type { Env } from '../config/env'; +import { ConversationAccess } from '../conversations/conversation-access'; +import { ConversationsRepository } from '../conversations/conversations.repository'; +import { permissionsOf } from '../realms/realm-permissions'; +import { RealmsRepository } from '../realms/realms.repository'; +import { RealtimeService } from '../realtime/realtime.service'; +import { toUserSummary } from '../users/user-summary'; +import { UsersRepository } from '../users/users.repository'; +import { CallRooms } from './call-rooms'; +import { CallsStore, type CallState } from './calls.store'; + +/** + * How long a token lets its holder into a call. It only has to last from + * the request to the connection; once connected, the media server keeps + * the browser's token fresh by itself. + */ +const TOKEN_TTL = '5m'; + +/** What the media server reports that changes who is in a call. */ +const MEMBERSHIP_EVENTS = new Set([ + 'room_started', + 'room_finished', + 'participant_joined', + 'participant_left', + 'participant_connection_aborted', +]); + +/** + * Voice and video calls. The media server (LiveKit) carries them and is the + * one that knows who is in which call: a call is one of its rooms, named + * after the conversation, and people are in it under their user ids. The + * API decides who gets in (by handing out tokens), remembers who is in each + * call so it can show that without asking the media server every time, and + * tells the people who can see a call when that changes. + */ +@Injectable() +export class CallsService { + private readonly logger = new Logger(CallsService.name); + private readonly settings: + { url: string; apiKey: string; apiSecret: string } | undefined; + private readonly webhooks: WebhookReceiver | undefined; + /** The sync under way for each conversation; they run one at a time. */ + private readonly syncing = new Map>(); + + constructor( + config: ConfigService, + private readonly access: ConversationAccess, + private readonly conversations: ConversationsRepository, + private readonly realms: RealmsRepository, + private readonly users: UsersRepository, + private readonly rooms: CallRooms, + private readonly store: CallsStore, + private readonly realtime: RealtimeService, + ) { + const url = config.get('LIVEKIT_URL', { infer: true }); + const apiKey = config.get('LIVEKIT_API_KEY', { infer: true }); + const apiSecret = config.get('LIVEKIT_API_SECRET', { infer: true }); + if (url && apiKey && apiSecret) { + this.settings = { url, apiKey, apiSecret }; + this.webhooks = new WebhookReceiver(apiKey, apiSecret); + } + } + + /** False when the server has no media server to send calls through. */ + get enabled(): boolean { + return this.settings !== undefined; + } + + /** The calls going on in the places the user can read. */ + async overview(userId: string): Promise { + if (!this.enabled) return { enabled: false, calls: [] }; + const ids = await this.conversations.listReadableIds(userId); + const states = await this.store.getMany(ids); + const calls = await Promise.all( + [...states].map(([id, state]) => this.toCall(id, state)), + ); + return { enabled: true, calls }; + } + + /** + * Lets the user into the call of a conversation or cauldron, which starts + * it if nobody is there. Open to whoever could post a message there. + */ + async join(userId: string, conversationId: string): Promise { + if (!this.settings) { + throw new ServiceUnavailableException( + "Calls aren't set up on this server.", + ); + } + const place = await this.access.locate(userId, conversationId); + await this.access.assertCanTakePart(place, userId); + if ( + place.kind === 'cauldron' && + !permissionsOf(place.membership, userId).includes('sendMessages') + ) { + throw new ForbiddenException( + "You don't have permission to join calls in this realm.", + ); + } + const user = await this.users.findById(userId); + if (!user) throw new NotFoundException('User not found.'); + + const { url, apiKey, apiSecret } = this.settings; + const token = new AccessToken(apiKey, apiSecret, { + identity: user.id, + name: user.name, + ttl: TOKEN_TTL, + }); + token.addGrant({ + room: conversationId, + roomJoin: true, + canPublish: true, + canSubscribe: true, + canPublishData: false, + }); + return { url, token: await token.toJwt() }; + } + + /** + * Takes a report from the media server. `authorization` is the header it + * signs the body with; anything not signed with the server's key is + * refused. + */ + async handleWebhook( + body: string, + authorization: string | undefined, + ): Promise { + if (!this.webhooks) throw new NotFoundException(); + let event; + try { + event = await this.webhooks.receive(body, authorization); + } catch { + throw new UnauthorizedException('The signature is missing or wrong.'); + } + const room = event.room?.name; + if (MEMBERSHIP_EVENTS.has(event.event) && isConversationId(room)) { + // A failure answers 500, and the media server sends the report again. + await this.sync(room); + } + } + + /** + * Asks the media server who is in a call, and if that isn't what the API + * remembers, updates it and tells everyone who can see the call. Asking + * rather than trusting the report at hand means reports that arrive late, + * twice or out of order do no harm. + */ + sync(conversationId: string): Promise { + const before = this.syncing.get(conversationId) ?? Promise.resolve(); + const run = before + .catch(() => undefined) + .then(() => this.syncNow(conversationId)) + .finally(() => { + if (this.syncing.get(conversationId) === run) { + this.syncing.delete(conversationId); + } + }); + this.syncing.set(conversationId, run); + return run; + } + + /** + * Syncs every call either side knows of. Catches what a lost report left + * behind, such as a call that ended while the API was down. + */ + async reconcile(): Promise { + if (!this.enabled) return; + const [remembered, live] = await Promise.all([ + this.store.ids(), + this.rooms.list(), + ]); + const ids = new Set([...remembered, ...live.filter(isConversationId)]); + await Promise.all([...ids].map((id) => this.sync(id))); + } + + /** Disconnects someone who may no longer be in a conversation's call. */ + async removeParticipant( + conversationId: string, + userId: string, + ): Promise { + await this.afterwards('remove someone from a call', async () => { + const state = await this.store.get(conversationId); + if (!state?.userIds.includes(userId)) return; + await this.rooms.remove(conversationId, userId); + await this.sync(conversationId); + }); + } + + /** Disconnects someone who left a realm from the calls in its cauldrons. */ + async removeFromRealm(realmId: string, userId: string): Promise { + await this.afterwards('remove someone from a realm’s calls', async () => { + const cauldrons = await this.realms.listCauldrons(realmId); + const states = await this.store.getMany( + cauldrons.map((cauldron) => cauldron.id), + ); + await Promise.all( + [...states] + .filter(([, state]) => state.userIds.includes(userId)) + .map(async ([id]) => { + await this.rooms.remove(id, userId); + await this.sync(id); + }), + ); + }); + } + + /** + * Ends the calls in these conversations for everyone, e.g. because the + * conversations were deleted. + */ + async end(conversationIds: string[]): Promise { + await this.afterwards('end a call', async () => { + const states = await this.store.getMany(conversationIds); + await Promise.all( + [...states.keys()].map(async (id) => { + await this.rooms.close(id); + await this.sync(id); + }), + ); + }); + } + + /** Ends the call between two people who stopped being friends. */ + async endDirect(userId: string, otherUserId: string): Promise { + if (!this.enabled) return; + const id = await this.conversations.findDirectId(userId, otherUserId); + if (id) await this.end([id]); + } + + private async syncNow(conversationId: string): Promise { + const [present, audience, before] = await Promise.all([ + this.rooms.participants(conversationId), + this.conversations.findAudience(conversationId), + this.store.get(conversationId), + ]); + if (!audience) { + // The conversation was deleted: nobody is left to tell. + if (before) await this.store.delete(conversationId); + if (present.length > 0) await this.rooms.close(conversationId); + return; + } + const realmId = 'realmId' in audience ? audience.realmId : null; + const userIds = [...new Set(present)]; + + let call: Call; + if (userIds.length === 0) { + if (!before) return; + await this.store.delete(conversationId); + call = { + conversationId, + realmId, + participants: [], + startedAt: before.startedAt, + }; + } else { + if (before && sameList(before.userIds, userIds)) return; + const state: CallState = { + realmId, + userIds, + startedAt: before?.startedAt ?? new Date().toISOString(), + }; + await this.store.set(conversationId, state); + call = await this.toCall(conversationId, state); + } + + if ('realmId' in audience) { + this.realtime.emitToRealm(audience.realmId, 'call:changed', call); + } else { + this.realtime.emitToUsers(audience.userIds, 'call:changed', call); + } + } + + private async toCall( + conversationId: string, + state: CallState, + ): Promise { + const rows = await this.users.findByIds(state.userIds); + const byId = new Map(rows.map((row) => [row.id, row])); + return { + conversationId, + realmId: state.realmId, + participants: state.userIds.flatMap((id) => { + const row = byId.get(id); + return row ? [toUserSummary(row)] : []; + }), + startedAt: state.startedAt, + }; + } + + /** + * Runs the part of a change that concerns calls, after the change itself + * is made. The change stands even if the media server can't be reached; + * the next reconcile puts the calls right. + */ + private async afterwards(what: string, work: () => Promise) { + if (!this.enabled) return; + try { + await work(); + } catch (error) { + this.logger.error(`Could not ${what}`, error); + } + } +} + +function isConversationId(name: string | undefined): name is string { + return conversationIdSchema.safeParse(name).success; +} + +function sameList(a: string[], b: string[]): boolean { + return a.length === b.length && a.every((item, index) => item === b[index]); +} diff --git a/apps/api/src/calls/calls.store.ts b/apps/api/src/calls/calls.store.ts new file mode 100644 index 0000000..841b429 --- /dev/null +++ b/apps/api/src/calls/calls.store.ts @@ -0,0 +1,66 @@ +import { Inject, Injectable } from '@nestjs/common'; +import type { Redis } from 'ioredis'; +import { z } from 'zod'; +import { REDIS } from '../redis/redis.module'; + +const callStateSchema = z.object({ + /** Set when the call is in a cauldron: its realm. */ + realmId: z.string().nullable(), + /** Who is in it, first to join first. Never empty. */ + userIds: z.array(z.string()), + startedAt: z.string(), +}); +/** What the API remembers about a call that is going on. */ +export type CallState = z.infer; + +// One hash for all calls: conversation id -> state as JSON. +const KEY = 'calls'; + +/** + * The calls that are going on, as last heard from the media server. Kept in + * Redis so that every instance of the API answers the same; the media + * server stays the one that knows. + */ +@Injectable() +export class CallsStore { + constructor(@Inject(REDIS) private readonly redis: Redis) {} + + async get(conversationId: string): Promise { + return parse(await this.redis.hget(KEY, conversationId)); + } + + /** The calls among these conversations, by conversation id. */ + async getMany(conversationIds: string[]): Promise> { + const calls = new Map(); + if (conversationIds.length === 0) return calls; + const values = await this.redis.hmget(KEY, ...conversationIds); + conversationIds.forEach((id, index) => { + const state = parse(values[index]); + if (state) calls.set(id, state); + }); + return calls; + } + + /** The ids of every conversation with a call. */ + ids(): Promise { + return this.redis.hkeys(KEY); + } + + async set(conversationId: string, state: CallState): Promise { + await this.redis.hset(KEY, conversationId, JSON.stringify(state)); + } + + async delete(conversationId: string): Promise { + await this.redis.hdel(KEY, conversationId); + } +} + +function parse(value: string | null | undefined): CallState | undefined { + if (!value) return undefined; + try { + return callStateSchema.parse(JSON.parse(value)); + } catch { + // Written by a version of the API that kept something else here. + return undefined; + } +} diff --git a/apps/api/src/config/env.ts b/apps/api/src/config/env.ts new file mode 100644 index 0000000..915c8ee --- /dev/null +++ b/apps/api/src/config/env.ts @@ -0,0 +1,94 @@ +import { z } from 'zod'; + +const variables = z.object({ + PORT: z.coerce.number().int().positive().default(3000), + /** + * How many reverse proxies stand between the internet and this API (a + * load balancer, Caddy, nginx): that many `X-Forwarded-For` entries are + * believed when working out a caller's address. 0 when browsers reach + * the API directly, as in development. + */ + TRUST_PROXY: z.coerce.number().int().min(0).default(0), + /** "false" lifts the limits on how often routes may be called. */ + RATE_LIMIT: z.stringbool().default(true), + DATABASE_URL: z.url(), + REDIS_URL: z.url(), + BETTER_AUTH_SECRET: z.string().min(32), + BETTER_AUTH_URL: z.url(), + /** Comma-separated front-end origins; served as a list. */ + TRUSTED_ORIGINS: z + .string() + .default('') + .transform((origins) => + origins + .split(',') + .map((origin) => origin.trim()) + .filter(Boolean), + ), + /** + * Where uploaded files are kept: a folder ("local", for development), an + * S3 bucket or anything that speaks S3 ("s3"), or nowhere lasting + * ("memory", for tests). + */ + STORAGE_DRIVER: z.enum(['local', 's3', 'memory']).default('local'), + /** The folder for "local", relative to where the API is started. */ + STORAGE_LOCAL_ROOT: z.string().min(1).default('.storage'), + S3_BUCKET: z.string().min(1).optional(), + /** Defaults to AWS_REGION, then us-east-1; Cloudflare R2 uses "auto". */ + S3_REGION: z.string().min(1).optional(), + /** For S3-compatible stores; leave out for AWS. */ + S3_ENDPOINT: z.url().optional(), + /** "true" for most self-hosted stores: https://endpoint/bucket/key. */ + S3_FORCE_PATH_STYLE: z.stringbool().optional(), + /** Default to AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. */ + S3_ACCESS_KEY_ID: z.string().min(1).optional(), + S3_SECRET_ACCESS_KEY: z.string().min(1).optional(), + /** + * The LiveKit server that carries voice and video, as browsers reach it + * (ws:// or wss://). Calls are switched off while it is left out. + */ + LIVEKIT_URL: z.url({ protocol: /^wss?$/ }).optional(), + /** + * Where the API itself reaches that server, when that isn't the address + * browsers use: its name on a private network, say (http:// or https://). + */ + LIVEKIT_INTERNAL_URL: z.url({ protocol: /^https?$/ }).optional(), + /** A key pair from that server's settings. */ + LIVEKIT_API_KEY: z.string().min(1).optional(), + LIVEKIT_API_SECRET: z.string().min(32).optional(), +}); + +/** + * Checked when the app starts, so a missing or malformed variable stops the + * boot with a clear message instead of failing on the first request. + */ +export const envSchema = z + // A variable set to nothing counts as left out: a compose file passes + // every name along, filled in or not. + .preprocess( + (env) => + typeof env === 'object' && env !== null + ? Object.fromEntries( + Object.entries(env).filter(([, value]) => value !== ''), + ) + : env, + variables, + ) + .refine((env) => env.STORAGE_DRIVER !== 's3' || env.S3_BUCKET !== undefined, { + path: ['S3_BUCKET'], + message: 'Required when STORAGE_DRIVER is "s3".', + }) + .refine( + (env) => + env.LIVEKIT_URL === undefined || + (env.LIVEKIT_API_KEY !== undefined && + env.LIVEKIT_API_SECRET !== undefined), + { + path: ['LIVEKIT_API_KEY'], + message: + 'LIVEKIT_API_KEY and LIVEKIT_API_SECRET are required with LIVEKIT_URL.', + }, + ); + +/** What ConfigService serves: `config.getOrThrow('PORT', { infer: true })`. */ +export type Env = z.infer; diff --git a/apps/api/src/conversations/conversation-access.ts b/apps/api/src/conversations/conversation-access.ts new file mode 100644 index 0000000..6568381 --- /dev/null +++ b/apps/api/src/conversations/conversation-access.ts @@ -0,0 +1,76 @@ +import { + ForbiddenException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import { FriendsRepository } from '../friends/friends.repository'; +import type { RealmMembership } from '../realms/realm-permissions'; +import { RealmsRepository } from '../realms/realms.repository'; +import { ConversationsRepository } from './conversations.repository'; + +export type ConversationRow = NonNullable< + Awaited> +>; + +/** + * Where messages (and a call) live, for someone who can read them: one of + * their own chats, or a cauldron of a realm they are in. + */ +export type Place = + | { kind: 'chat'; row: ConversationRow; memberIds: string[] } + | { kind: 'cauldron'; realmId: string; membership: RealmMembership }; + +export const CONVERSATION_NOT_FOUND = 'Conversation not found.'; + +/** + * Who may read a conversation or cauldron and who may add to it. It only + * runs queries, so any module that needs the answer lists it as a provider + * (with the three repositories it uses). + */ +@Injectable() +export class ConversationAccess { + constructor( + private readonly conversations: ConversationsRepository, + private readonly friends: FriendsRepository, + private readonly realms: RealmsRepository, + ) {} + + /** + * Finds a conversation or cauldron the user can read. Answers 404 for + * one they can't as well, so ids can't be probed for existence. + */ + async locate(userId: string, conversationId: string): Promise { + const row = await this.conversations.findForMember(conversationId, userId); + if (row) return { kind: 'chat', row, memberIds: memberIdsOf(row) }; + // Not one of the user's chats: a cauldron, or nothing they can see. + const realmId = + await this.conversations.findCauldronRealmId(conversationId); + const membership = + realmId && (await this.realms.findMembership(realmId, userId)); + if (!realmId || !membership) { + throw new NotFoundException(CONVERSATION_NOT_FOUND); + } + return { kind: 'cauldron', realmId, membership }; + } + + /** + * The history of a direct chat stays readable after unfriending, but + * adding to it needs the friendship. Groups and cauldrons only need + * membership, which finding the place has checked. + */ + async assertCanTakePart(place: Place, userId: string) { + if (place.kind !== 'chat' || place.row.type !== 'direct') return; + const otherUserId = place.memberIds.find((id) => id !== userId); + if (otherUserId) await this.assertFriends(userId, otherUserId); + } + + async assertFriends(userId: string, otherUserId: string) { + if (!(await this.friends.areFriends(userId, otherUserId))) { + throw new ForbiddenException('You can only message your friends.'); + } + } +} + +export function memberIdsOf(row: ConversationRow): string[] { + return row.members.map((member) => member.userId); +} diff --git a/apps/api/src/conversations/conversations.controller.ts b/apps/api/src/conversations/conversations.controller.ts new file mode 100644 index 0000000..f229786 --- /dev/null +++ b/apps/api/src/conversations/conversations.controller.ts @@ -0,0 +1,188 @@ +import { + Body, + Controller, + Delete, + Get, + HttpCode, + Param, + Patch, + Post, + Put, + Query, +} from '@nestjs/common'; +import { + addGroupMembersSchema, + conversationIdSchema, + createGroupSchema, + listMessagesQuerySchema, + markReadSchema, + messageIdSchema, + openDirectConversationSchema, + reactionEmojiSchema, + sendMessageSchema, + updateGroupSchema, + userIdSchema, + type AddGroupMembers, + type CreateGroup, + type ListMessagesQuery, + type MarkRead, + type OpenDirectConversation, + type SendMessage, + type UpdateGroup, +} from '@repo/contracts'; +import { Session, type UserSession } from '@thallesp/nestjs-better-auth'; +import type { Auth } from '../auth/auth'; +import { ConversationsService } from './conversations.service'; +import { AtMost } from '../rate-limit/at-most'; + +@Controller('conversations') +export class ConversationsController { + constructor(private readonly conversations: ConversationsService) {} + + /** The signed-in user's conversations, most recently active first. */ + @Get() + list(@Session() session: UserSession) { + return this.conversations.list(session.user.id); + } + + /** Opens the chat with a friend; creates it the first time. */ + @Post('direct') + @HttpCode(200) + openDirect( + @Session() session: UserSession, + @Body({ schema: openDirectConversationSchema }) + body: OpenDirectConversation, + ) { + return this.conversations.openDirect(session.user.id, body.userId); + } + + /** Starts a group chat with some of the user's friends. */ + @Post('group') + @AtMost(10, { seconds: 60 }) + createGroup( + @Session() session: UserSession, + @Body({ schema: createGroupSchema }) body: CreateGroup, + ) { + return this.conversations.createGroup(session.user.id, body); + } + + @Get(':id') + get( + @Session() session: UserSession, + @Param('id', { schema: conversationIdSchema }) id: string, + ) { + return this.conversations.get(session.user.id, id); + } + + /** Renames a group chat. */ + @Patch(':id') + renameGroup( + @Session() session: UserSession, + @Param('id', { schema: conversationIdSchema }) id: string, + @Body({ schema: updateGroupSchema }) body: UpdateGroup, + ) { + return this.conversations.renameGroup(session.user.id, id, body.name); + } + + /** Adds friends to a group chat; answers with the group as it is now. */ + @Post(':id/members') + @HttpCode(200) + addGroupMembers( + @Session() session: UserSession, + @Param('id', { schema: conversationIdSchema }) id: string, + @Body({ schema: addGroupMembersSchema }) body: AddGroupMembers, + ) { + return this.conversations.addGroupMembers( + session.user.id, + id, + body.userIds, + ); + } + + /** Leaves a group chat (your own id) or, as its owner, removes someone. */ + @Delete(':id/members/:userId') + @HttpCode(204) + removeGroupMember( + @Session() session: UserSession, + @Param('id', { schema: conversationIdSchema }) id: string, + @Param('userId', { schema: userIdSchema }) userId: string, + ) { + return this.conversations.removeGroupMember(session.user.id, id, userId); + } + + /** History, newest first: ?before=&limit=50 */ + @Get(':id/messages') + listMessages( + @Session() session: UserSession, + @Param('id', { schema: conversationIdSchema }) id: string, + @Query({ schema: listMessagesQuerySchema }) query: ListMessagesQuery, + ) { + return this.conversations.listMessages(session.user.id, id, query); + } + + // Room for a burst of quick lines, not for a flood. + @Post(':id/messages') + @AtMost(20, { seconds: 10 }) + sendMessage( + @Session() session: UserSession, + @Param('id', { schema: conversationIdSchema }) id: string, + @Body({ schema: sendMessageSchema }) body: SendMessage, + ) { + return this.conversations.sendMessage(session.user.id, id, body); + } + + /** Notes how far the user has read: { messageId } of the newest one seen. */ + @Put(':id/read') + markRead( + @Session() session: UserSession, + @Param('id', { schema: conversationIdSchema }) id: string, + @Body({ schema: markReadSchema }) body: MarkRead, + ) { + return this.conversations.markRead(session.user.id, id, body.messageId); + } + + /** Puts the user's emoji on a message; fine if it is there already. */ + @Put(':id/messages/:messageId/reactions/:emoji') + @HttpCode(204) + addReaction( + @Session() session: UserSession, + @Param('id', { schema: conversationIdSchema }) id: string, + @Param('messageId', { schema: messageIdSchema }) messageId: string, + @Param('emoji', { schema: reactionEmojiSchema }) emoji: string, + ) { + return this.conversations.addReaction( + session.user.id, + id, + messageId, + emoji, + ); + } + + /** Deletes a message of the user's own, or one they may moderate. */ + @Delete(':id/messages/:messageId') + @HttpCode(204) + deleteMessage( + @Session() session: UserSession, + @Param('id', { schema: conversationIdSchema }) id: string, + @Param('messageId', { schema: messageIdSchema }) messageId: string, + ) { + return this.conversations.deleteMessage(session.user.id, id, messageId); + } + + /** Takes the user's emoji off a message; fine if it wasn't there. */ + @Delete(':id/messages/:messageId/reactions/:emoji') + @HttpCode(204) + removeReaction( + @Session() session: UserSession, + @Param('id', { schema: conversationIdSchema }) id: string, + @Param('messageId', { schema: messageIdSchema }) messageId: string, + @Param('emoji', { schema: reactionEmojiSchema }) emoji: string, + ) { + return this.conversations.removeReaction( + session.user.id, + id, + messageId, + emoji, + ); + } +} diff --git a/apps/api/src/conversations/conversations.module.ts b/apps/api/src/conversations/conversations.module.ts new file mode 100644 index 0000000..fd7dd24 --- /dev/null +++ b/apps/api/src/conversations/conversations.module.ts @@ -0,0 +1,29 @@ +import { Module } from '@nestjs/common'; +import { AttachmentsModule } from '../attachments/attachments.module'; +import { CallsModule } from '../calls/calls.module'; +import { FriendsRepository } from '../friends/friends.repository'; +import { RealmsRepository } from '../realms/realms.repository'; +import { RealtimeModule } from '../realtime/realtime.module'; +import { UsersRepository } from '../users/users.repository'; +import { ConversationAccess } from './conversation-access'; +import { ConversationsController } from './conversations.controller'; +import { ConversationsRepository } from './conversations.repository'; +import { ConversationsService } from './conversations.service'; +import { ReadsRepository } from './reads.repository'; + +@Module({ + imports: [RealtimeModule, AttachmentsModule, CallsModule], + controllers: [ConversationsController], + // The other features' repositories are listed here rather than importing + // their modules; see the note in friends.module.ts. + providers: [ + ConversationsService, + ConversationsRepository, + ConversationAccess, + ReadsRepository, + FriendsRepository, + RealmsRepository, + UsersRepository, + ], +}) +export class ConversationsModule {} diff --git a/apps/api/src/conversations/conversations.repository.ts b/apps/api/src/conversations/conversations.repository.ts new file mode 100644 index 0000000..9b374d8 --- /dev/null +++ b/apps/api/src/conversations/conversations.repository.ts @@ -0,0 +1,490 @@ +import { Injectable } from '@nestjs/common'; +import { InjectDrizzle } from '@nestjs/drizzle'; +import { and, asc, eq, exists, inArray, isNull, or, sql } from 'drizzle-orm'; +import type { Database } from '../db/database'; +import { + attachment, + conversation, + conversationMember, + conversationRead, + directConversationKey, + message, + messageReaction, + realmMember, + type user, +} from '../db/schema'; + +export type MessageRow = typeof message.$inferSelect; +type AttachmentRow = typeof attachment.$inferSelect; +type ReactionRow = typeof messageReaction.$inferSelect; +/** A message with what is shown along with it. */ +export type MessageDetailsRow = MessageRow & { + author: typeof user.$inferSelect; + attachments: AttachmentRow[]; + reactions: ReactionRow[]; +}; + +// What a message is always loaded with: its author, its files in the order +// they were uploaded and its reactions, earliest first. +const withMessageDetails = { + author: true, + attachments: { orderBy: { id: 'asc' } }, + reactions: { orderBy: { createdAt: 'asc' } }, +} as const; + +// What a conversation is always loaded with: who is in it, longest-standing +// first, and its newest message (`messages` holds at most that one). +const withDetails = { + members: { + with: { user: true }, + orderBy: { joinedAt: 'asc', userId: 'asc' }, + }, + messages: { orderBy: { id: 'desc' }, limit: 1, with: withMessageDetails }, +} as const; + +/** Thrown inside the transaction that posts a message, to undo it. */ +class AttachmentsTakenError extends Error {} + +@Injectable() +export class ConversationsRepository { + constructor(@InjectDrizzle() private readonly db: Database) {} + + /** + * The direct and group chats a user is in, most recently active first. + * Cauldrons have no members of their own, so they never show up here. + */ + listForMember(userId: string) { + return this.db.query.conversation.findMany({ + where: { members: { userId } }, + with: withDetails, + orderBy: { lastActivityAt: 'desc' }, + }); + } + + /** Nothing when the conversation doesn't exist or the user isn't in it. */ + findForMember(conversationId: string, userId: string) { + return this.db.query.conversation.findFirst({ + where: { id: conversationId, members: { userId } }, + with: withDetails, + }); + } + + /** + * Whether the user may read what is posted here: they are in the + * conversation, or it is a cauldron of a realm they are in. + */ + async canRead(conversationId: string, userId: string): Promise { + const inConversation = this.db + .select({ one: sql`1` }) + .from(conversationMember) + .where( + and( + eq(conversationMember.conversationId, conversation.id), + eq(conversationMember.userId, userId), + ), + ); + const inRealm = this.db + .select({ one: sql`1` }) + .from(realmMember) + .where( + and( + eq(realmMember.realmId, conversation.realmId), + eq(realmMember.userId, userId), + ), + ); + const rows = await this.db + .select({ id: conversation.id }) + .from(conversation) + .where( + and( + eq(conversation.id, conversationId), + or(exists(inConversation), exists(inRealm)), + ), + ); + return rows.length > 0; + } + + /** The realm a cauldron belongs to; nothing for any other conversation. */ + async findCauldronRealmId( + conversationId: string, + ): Promise { + const rows = await this.db + .select({ realmId: conversation.realmId }) + .from(conversation) + .where(eq(conversation.id, conversationId)); + return rows.at(0)?.realmId ?? undefined; + } + + /** + * Who is told about what happens in a conversation: everyone in the realm + * for a cauldron, its members otherwise. Nothing when it doesn't exist. + */ + async findAudience( + conversationId: string, + ): Promise<{ realmId: string } | { userIds: string[] } | undefined> { + const rows = await this.db + .select({ + realmId: conversation.realmId, + userId: conversationMember.userId, + }) + .from(conversation) + .leftJoin( + conversationMember, + eq(conversationMember.conversationId, conversation.id), + ) + .where(eq(conversation.id, conversationId)); + const first = rows.at(0); + if (!first) return undefined; + if (first.realmId) return { realmId: first.realmId }; + return { userIds: rows.flatMap((row) => (row.userId ? [row.userId] : [])) }; + } + + /** + * The ids of every conversation the user can read: their chats and the + * cauldrons of the realms they are in. + */ + async listReadableIds(userId: string): Promise { + const [chats, cauldrons] = await Promise.all([ + this.db + .select({ id: conversationMember.conversationId }) + .from(conversationMember) + .where(eq(conversationMember.userId, userId)), + this.db + .select({ id: conversation.id }) + .from(conversation) + .innerJoin(realmMember, eq(realmMember.realmId, conversation.realmId)) + .where(eq(realmMember.userId, userId)), + ]); + return [...chats, ...cauldrons].map((row) => row.id); + } + + async findDirectId( + userId: string, + otherUserId: string, + ): Promise { + const rows = await this.db + .select({ id: conversation.id }) + .from(conversation) + .where( + eq(conversation.directKey, directConversationKey(userId, otherUserId)), + ); + return rows.at(0)?.id; + } + + /** Creates the chat between two users, or returns the one they have. */ + createDirect(userId: string, otherUserId: string): Promise { + const directKey = directConversationKey(userId, otherUserId); + return this.db.transaction(async (tx) => { + const inserted = await tx + .insert(conversation) + .values({ type: 'direct', directKey }) + .onConflictDoNothing() + .returning({ id: conversation.id }); + const created = inserted.at(0); + if (!created) { + // Both people opened it at once; the other request won. + const [existing] = await tx + .select({ id: conversation.id }) + .from(conversation) + .where(eq(conversation.directKey, directKey)); + return existing.id; + } + await tx.insert(conversationMember).values([ + { conversationId: created.id, userId }, + { conversationId: created.id, userId: otherUserId }, + ]); + return created.id; + }); + } + + /** Creates a group owned by `ownerId` with `otherUserIds` in it too. */ + createGroup( + ownerId: string, + otherUserIds: string[], + name: string | null, + ): Promise { + return this.db.transaction(async (tx) => { + const [created] = await tx + .insert(conversation) + .values({ type: 'group', name, ownerId }) + .returning({ id: conversation.id }); + await tx.insert(conversationMember).values( + [ownerId, ...otherUserIds].map((userId) => ({ + conversationId: created.id, + userId, + })), + ); + return created.id; + }); + } + + async rename(conversationId: string, name: string | null): Promise { + await this.db + .update(conversation) + .set({ name }) + .where(eq(conversation.id, conversationId)); + } + + /** + * Adds people who aren't in the conversation yet. Adds no one and answers + * "full" when that would take it past `maxMembers`. + */ + addMembers( + conversationId: string, + userIds: string[], + maxMembers: number, + ): Promise<'added' | 'full'> { + return this.db.transaction(async (tx) => { + // Locking the conversation makes membership changes take turns, so two + // people adding at once can't both fit under the limit. + await tx + .select({ id: conversation.id }) + .from(conversation) + .where(eq(conversation.id, conversationId)) + .for('update'); + const current = await tx + .select({ userId: conversationMember.userId }) + .from(conversationMember) + .where(eq(conversationMember.conversationId, conversationId)); + const currentIds = new Set(current.map((member) => member.userId)); + const newIds = userIds.filter((userId) => !currentIds.has(userId)); + if (newIds.length === 0) return 'added'; + if (currentIds.size + newIds.length > maxMembers) return 'full'; + await tx + .insert(conversationMember) + .values(newIds.map((userId) => ({ conversationId, userId }))); + return 'added'; + }); + } + + /** + * Takes someone out of a group. If they owned it, the longest-standing + * member left becomes the owner; if no one is left, the group is deleted. + * Answers false when they weren't in it. + */ + removeMember(conversationId: string, userId: string): Promise { + return this.db.transaction(async (tx) => { + const locked = await tx + .select({ ownerId: conversation.ownerId }) + .from(conversation) + .where(eq(conversation.id, conversationId)) + .for('update'); + const removed = await tx + .delete(conversationMember) + .where( + and( + eq(conversationMember.conversationId, conversationId), + eq(conversationMember.userId, userId), + ), + ) + .returning({ userId: conversationMember.userId }); + if (removed.length === 0) return false; + + const remaining = await tx + .select({ userId: conversationMember.userId }) + .from(conversationMember) + .where(eq(conversationMember.conversationId, conversationId)) + .orderBy( + asc(conversationMember.joinedAt), + asc(conversationMember.userId), + ) + .limit(1); + const successor = remaining.at(0); + if (!successor) { + await tx + .delete(conversation) + .where(eq(conversation.id, conversationId)); + } else if (locked.at(0)?.ownerId === userId) { + await tx + .update(conversation) + .set({ ownerId: successor.userId }) + .where(eq(conversation.id, conversationId)); + } + return true; + }); + } + + /** Newest first; `before` is the id of the oldest message already shown. */ + listMessages( + conversationId: string, + before: string | undefined, + limit: number, + ): Promise { + return this.db.query.message.findMany({ + where: { conversationId, ...(before ? { id: { lt: before } } : {}) }, + with: withMessageDetails, + orderBy: { id: 'desc' }, + limit, + }); + } + + /** Who wrote a message of this conversation; nothing if there is none. */ + async findMessageAuthorId( + conversationId: string, + messageId: string, + ): Promise { + const rows = await this.db + .select({ authorId: message.authorId }) + .from(message) + .where( + and( + eq(message.id, messageId), + eq(message.conversationId, conversationId), + ), + ); + return rows.at(0)?.authorId; + } + + /** + * Its reactions go with it. Its files are left without a message, which + * hides them from everyone else at once; the clean-up removes them once + * they are a day old. + */ + async deleteMessage(messageId: string): Promise { + const removed = await this.db + .delete(message) + .where(eq(message.id, messageId)) + .returning({ id: message.id }); + return removed.length > 0; + } + + /** Whether a message is one of this conversation's. */ + async hasMessage(conversationId: string, messageId: string) { + const rows = await this.db + .select({ id: message.id }) + .from(message) + .where( + and( + eq(message.id, messageId), + eq(message.conversationId, conversationId), + ), + ); + return rows.length > 0; + } + + /** + * Posts a message with the author's uploaded files on it, and moves the + * author's read marker to it. Posts nothing and answers undefined when + * one of the files isn't theirs or went onto another message meanwhile. + */ + async createMessage( + conversationId: string, + authorId: string, + content: string, + attachmentIds: string[], + ): Promise<{ row: MessageRow; attachments: AttachmentRow[] } | undefined> { + try { + return await this.db.transaction(async (tx) => { + const [row] = await tx + .insert(message) + .values({ conversationId, authorId, content }) + .returning(); + const attachments = + attachmentIds.length === 0 + ? [] + : await tx + .update(attachment) + .set({ messageId: row.id }) + .where( + and( + inArray(attachment.id, attachmentIds), + eq(attachment.uploaderId, authorId), + isNull(attachment.messageId), + ), + ) + .returning(); + if (attachments.length !== attachmentIds.length) { + throw new AttachmentsTakenError(); + } + await tx + .update(conversation) + .set({ lastActivityAt: row.createdAt }) + .where(eq(conversation.id, conversationId)); + // Whoever posts has seen what came before. + await tx + .insert(conversationRead) + .values({ + userId: authorId, + conversationId, + lastReadMessageId: row.id, + }) + .onConflictDoUpdate({ + target: [conversationRead.userId, conversationRead.conversationId], + set: { lastReadMessageId: row.id, updatedAt: row.createdAt }, + }); + return { + row, + attachments: attachments.toSorted((a, b) => (a.id < b.id ? -1 : 1)), + }; + }); + } catch (error) { + if (error instanceof AttachmentsTakenError) return undefined; + throw error; + } + } + + /** + * Adds someone's emoji to a message. `changed` is false when they had + * chosen it already; `count` is how many people have chosen it now. + * Answers "full" when the message has `maxEmoji` different ones and this + * would be another. + */ + addReaction( + messageId: string, + userId: string, + emoji: string, + maxEmoji: number, + ): Promise<{ changed: boolean; count: number } | 'full'> { + return this.db.transaction(async (tx) => { + // Locking the message makes reactions to it take turns, so two new + // emoji at once can't both fit under the limit. + await tx + .select({ id: message.id }) + .from(message) + .where(eq(message.id, messageId)) + .for('update'); + const used = await tx + .selectDistinct({ emoji: messageReaction.emoji }) + .from(messageReaction) + .where(eq(messageReaction.messageId, messageId)); + const isNew = !used.some((reaction) => reaction.emoji === emoji); + if (isNew && used.length >= maxEmoji) return 'full'; + const inserted = await tx + .insert(messageReaction) + .values({ messageId, userId, emoji }) + .onConflictDoNothing() + .returning({ emoji: messageReaction.emoji }); + const [{ count }] = await tx + .select({ count: sql`count(*)::int` }) + .from(messageReaction) + .where(reactionOf(messageId, emoji)); + return { changed: inserted.length > 0, count }; + }); + } + + /** Takes someone's emoji off a message; see `addReaction` for the answer. */ + async removeReaction( + messageId: string, + userId: string, + emoji: string, + ): Promise<{ changed: boolean; count: number }> { + const removed = await this.db + .delete(messageReaction) + .where( + and(reactionOf(messageId, emoji), eq(messageReaction.userId, userId)), + ) + .returning({ emoji: messageReaction.emoji }); + const [{ count }] = await this.db + .select({ count: sql`count(*)::int` }) + .from(messageReaction) + .where(reactionOf(messageId, emoji)); + return { changed: removed.length > 0, count }; + } +} + +function reactionOf(messageId: string, emoji: string) { + return and( + eq(messageReaction.messageId, messageId), + eq(messageReaction.emoji, emoji), + ); +} diff --git a/apps/api/src/conversations/conversations.service.ts b/apps/api/src/conversations/conversations.service.ts new file mode 100644 index 0000000..4087bda --- /dev/null +++ b/apps/api/src/conversations/conversations.service.ts @@ -0,0 +1,484 @@ +import { + BadRequestException, + ConflictException, + ForbiddenException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import { + GROUP_MAX_MEMBERS, + MESSAGE_MAX_REACTIONS, + type Conversation, + type ConversationRead, + type CreateGroup, + type ListMessagesQuery, + type Message, + type MessagePage, + type Reaction, + type SendMessage, + type ServerToClientEvents, +} from '@repo/contracts'; +import { + AttachmentsService, + toAttachment, +} from '../attachments/attachments.service'; +import { CallsService } from '../calls/calls.service'; +import { FriendsRepository } from '../friends/friends.repository'; +import { permissionsOf } from '../realms/realm-permissions'; +import { RealtimeService } from '../realtime/realtime.service'; +import { toUserSummary } from '../users/user-summary'; +import { UsersRepository } from '../users/users.repository'; +import { + CONVERSATION_NOT_FOUND as NOT_FOUND, + ConversationAccess, + memberIdsOf, + type ConversationRow, + type Place, +} from './conversation-access'; +import { + ConversationsRepository, + type MessageDetailsRow, +} from './conversations.repository'; +import { ReadsRepository } from './reads.repository'; + +type AuthorRow = ConversationRow['members'][number]['user']; + +@Injectable() +export class ConversationsService { + constructor( + private readonly conversations: ConversationsRepository, + private readonly access: ConversationAccess, + private readonly friends: FriendsRepository, + private readonly users: UsersRepository, + private readonly reads: ReadsRepository, + private readonly attachments: AttachmentsService, + private readonly calls: CallsService, + private readonly realtime: RealtimeService, + ) {} + + async list(userId: string): Promise { + const [rows, unread] = await Promise.all([ + this.conversations.listForMember(userId), + this.reads.countsForChats(userId), + ]); + return rows.map((row) => + toConversation(row, userId, unread.get(row.id) ?? 0), + ); + } + + async get(userId: string, conversationId: string): Promise { + const [row, unread] = await Promise.all([ + this.findForMember(userId, conversationId), + this.reads.countsForChats(userId), + ]); + return toConversation(row, userId, unread.get(row.id) ?? 0); + } + + /** The chat with a friend, created on first use. */ + async openDirect(userId: string, otherUserId: string): Promise { + if (otherUserId === userId) { + throw new BadRequestException("You can't message yourself."); + } + let conversationId = await this.conversations.findDirectId( + userId, + otherUserId, + ); + if (!conversationId) { + await this.access.assertFriends(userId, otherUserId); + conversationId = await this.conversations.createDirect( + userId, + otherUserId, + ); + } + return this.get(userId, conversationId); + } + + /** A new group with the user as its owner and some of their friends. */ + async createGroup( + userId: string, + { name, memberIds }: CreateGroup, + ): Promise { + await this.assertCanAdd(userId, memberIds); + const conversationId = await this.conversations.createGroup( + userId, + memberIds, + name ?? null, + ); + const conversation = await this.get(userId, conversationId); + this.announceChange(conversation.members.map((member) => member.id)); + return conversation; + } + + /** Any member may rename a group; null goes back to showing who is in it. */ + async renameGroup( + userId: string, + conversationId: string, + name: string | null, + ): Promise { + const row = await this.findGroupForMember(userId, conversationId); + await this.conversations.rename(conversationId, name); + this.announceChange(memberIdsOf(row)); + return this.get(userId, conversationId); + } + + /** Any member may bring their own friends into a group. */ + async addGroupMembers( + userId: string, + conversationId: string, + userIds: string[], + ): Promise { + const row = await this.findGroupForMember(userId, conversationId); + const memberIds = memberIdsOf(row); + // People who are in it already are skipped rather than refused. + const newIds = userIds.filter((id) => !memberIds.includes(id)); + await this.assertCanAdd(userId, newIds); + + const outcome = await this.conversations.addMembers( + conversationId, + newIds, + GROUP_MAX_MEMBERS, + ); + if (outcome === 'full') { + throw new ConflictException( + `A group can have at most ${GROUP_MAX_MEMBERS} people.`, + ); + } + this.announceChange([...memberIds, ...newIds]); + return this.get(userId, conversationId); + } + + /** Leaving (removing yourself) is open to everyone; removing others is the owner's. */ + async removeGroupMember( + userId: string, + conversationId: string, + targetUserId: string, + ): Promise { + const row = await this.findGroupForMember(userId, conversationId); + const memberIds = memberIdsOf(row); + if (targetUserId !== userId) { + if (groupOwnerId(row) !== userId) { + throw new ForbiddenException( + "Only the group's owner can remove people.", + ); + } + if (!memberIds.includes(targetUserId)) { + throw new NotFoundException("That person isn't in this group."); + } + } + await this.conversations.removeMember(conversationId, targetUserId); + // The person taken out is told as well, so the group leaves their list. + this.announceChange(memberIds); + await this.calls.removeParticipant(conversationId, targetUserId); + } + + async listMessages( + userId: string, + conversationId: string, + { before, limit }: ListMessagesQuery, + ): Promise { + if (!(await this.conversations.canRead(conversationId, userId))) { + throw new NotFoundException(NOT_FOUND); + } + // One more than asked for tells whether an older page exists. + const rows = await this.conversations.listMessages( + conversationId, + before, + limit + 1, + ); + const items = rows.slice(0, limit).map((row) => toMessage(row, userId)); + return { + items, + nextCursor: rows.length > limit ? (items.at(-1)?.id ?? null) : null, + }; + } + + async sendMessage( + userId: string, + conversationId: string, + { content, attachmentIds }: SendMessage, + ): Promise { + const place = await this.access.locate(userId, conversationId); + await this.access.assertCanTakePart(place, userId); + if ( + place.kind === 'cauldron' && + !permissionsOf(place.membership, userId).includes('sendMessages') + ) { + throw new ForbiddenException( + "You don't have permission to post in this realm.", + ); + } + const author = + place.kind === 'chat' + ? place.row.members.find((member) => member.userId === userId)?.user + : await this.users.findById(userId); + if (!author) throw new NotFoundException(NOT_FOUND); + + await this.attachments.assertReady(userId, attachmentIds); + const created = await this.conversations.createMessage( + conversationId, + userId, + content, + attachmentIds, + ); + if (!created) { + throw new BadRequestException( + 'A file is missing or was already sent. Attach it again.', + ); + } + const message = toMessage( + { + ...created.row, + author, + attachments: created.attachments, + reactions: [], + }, + userId, + ); + // The author is included, so their other tabs and devices get it too. + this.emit(place, 'message:created', message, { + realmId: place.kind === 'cauldron' ? place.realmId : null, + }); + return message; + } + + /** + * Deletes a message. Its author always may; so may whoever looks after + * the place: a group's owner, or a realm member with "manageMessages". + */ + async deleteMessage( + userId: string, + conversationId: string, + messageId: string, + ): Promise { + const place = await this.access.locate(userId, conversationId); + const authorId = await this.conversations.findMessageAuthorId( + conversationId, + messageId, + ); + if (!authorId) throw new NotFoundException('Message not found.'); + const looksAfter = + place.kind === 'cauldron' + ? permissionsOf(place.membership, userId).includes('manageMessages') + : groupOwnerId(place.row) === userId; + if (authorId !== userId && !looksAfter) { + throw new ForbiddenException("You can't delete this message."); + } + if (await this.conversations.deleteMessage(messageId)) { + this.emit(place, 'message:deleted', { + conversationId, + messageId, + realmId: place.kind === 'cauldron' ? place.realmId : null, + }); + } + } + + /** + * Puts the user's emoji on a message. Open to whoever could post a reply + * (though in a realm it doesn't take the permission to post). + */ + async addReaction( + userId: string, + conversationId: string, + messageId: string, + emoji: string, + ): Promise { + const place = await this.access.locate(userId, conversationId); + await this.access.assertCanTakePart(place, userId); + await this.assertHasMessage(conversationId, messageId); + const outcome = await this.conversations.addReaction( + messageId, + userId, + emoji, + MESSAGE_MAX_REACTIONS, + ); + if (outcome === 'full') { + throw new ConflictException( + `A message can have at most ${MESSAGE_MAX_REACTIONS} different reactions.`, + ); + } + if (outcome.changed) { + this.emit(place, 'reaction:changed', { + conversationId, + messageId, + emoji, + count: outcome.count, + userId, + added: true, + }); + } + } + + /** Takes the user's emoji back; fine if it wasn't there. */ + async removeReaction( + userId: string, + conversationId: string, + messageId: string, + emoji: string, + ): Promise { + const place = await this.access.locate(userId, conversationId); + await this.assertHasMessage(conversationId, messageId); + const outcome = await this.conversations.removeReaction( + messageId, + userId, + emoji, + ); + if (outcome.changed) { + this.emit(place, 'reaction:changed', { + conversationId, + messageId, + emoji, + count: outcome.count, + userId, + added: false, + }); + } + } + + /** + * Notes that the user has read up to a message. The marker never moves + * back, so marking an older message changes nothing. + */ + async markRead( + userId: string, + conversationId: string, + messageId: string, + ): Promise { + const place = await this.access.locate(userId, conversationId); + await this.assertHasMessage(conversationId, messageId); + const read: ConversationRead = { + conversationId, + realmId: place.kind === 'cauldron' ? place.realmId : null, + unreadCount: await this.reads.mark(userId, conversationId, messageId), + }; + // Their other tabs and devices drop the badge too. + this.realtime.emitToUsers([userId], 'conversation:read', read); + return read; + } + + private async assertHasMessage(conversationId: string, messageId: string) { + if (!(await this.conversations.hasMessage(conversationId, messageId))) { + throw new NotFoundException('Message not found.'); + } + } + + /** Sends an event to everyone who can read a place. */ + private emit( + place: Place, + event: Event, + ...args: Parameters + ) { + if (place.kind === 'chat') { + this.realtime.emitToUsers(place.memberIds, event, ...args); + } else { + this.realtime.emitToRealm(place.realmId, event, ...args); + } + } + + // Answers 404 for someone else's conversation as well, so ids can't be + // probed for existence. + private async findForMember( + userId: string, + conversationId: string, + ): Promise { + const row = await this.conversations.findForMember(conversationId, userId); + if (!row) throw new NotFoundException(NOT_FOUND); + return row; + } + + private async findGroupForMember( + userId: string, + conversationId: string, + ): Promise { + const row = await this.findForMember(userId, conversationId); + if (row.type !== 'group') { + throw new BadRequestException("This isn't a group chat."); + } + return row; + } + + // An id that belongs to no one fails the same way as a stranger's, so ids + // can't be probed here either. + private async assertCanAdd(userId: string, otherUserIds: string[]) { + if (otherUserIds.includes(userId)) { + throw new BadRequestException("You're already in the group."); + } + if (!(await this.friends.areAllFriends(userId, otherUserIds))) { + throw new ForbiddenException('You can only add your friends to a group.'); + } + } + + private announceChange(userIds: string[]) { + this.realtime.emitToUsers(userIds, 'conversations:changed'); + } +} + +/** + * Who may remove people from a group. Normally the stored owner; if that + * account was deleted, the longest-standing member (members come sorted). + */ +function groupOwnerId(row: ConversationRow): string | null { + if (row.type !== 'group') return null; + return row.ownerId ?? row.members.at(0)?.userId ?? null; +} + +/** A message as `viewerId` sees it: reactions say which are their own. */ +function toMessage( + row: Omit & { author: AuthorRow }, + viewerId: string, +): Message { + return { + id: row.id, + conversationId: row.conversationId, + author: toUserSummary(row.author), + content: row.content, + attachments: row.attachments.map(toAttachment), + reactions: toReactions(row.reactions, viewerId), + createdAt: row.createdAt.toISOString(), + }; +} + +/** One entry per emoji, in the order the rows (earliest first) bring them. */ +function toReactions( + rows: MessageDetailsRow['reactions'], + viewerId: string, +): Reaction[] { + const byEmoji = new Map(); + for (const row of rows) { + const reaction = byEmoji.get(row.emoji) ?? { + emoji: row.emoji, + count: 0, + mine: false, + }; + reaction.count += 1; + reaction.mine ||= row.userId === viewerId; + byEmoji.set(row.emoji, reaction); + } + return [...byEmoji.values()]; +} + +function toConversation( + row: ConversationRow, + viewerId: string, + unreadCount: number, +): Conversation { + // Cauldrons are part of their realm and never loaded as a member's chat. + if (row.type === 'cauldron') { + throw new Error(`Cauldron ${row.id} was loaded as a conversation.`); + } + const lastMessage = row.messages.at(0); + const ownerId = groupOwnerId(row); + // The owner heads the list; the sort keeps everyone else in joining order. + const members = row.members.toSorted( + (a, b) => Number(b.userId === ownerId) - Number(a.userId === ownerId), + ); + return { + id: row.id, + type: row.type, + name: row.name, + ownerId, + members: members.map((member) => toUserSummary(member.user)), + lastMessage: lastMessage ? toMessage(lastMessage, viewerId) : null, + lastActivityAt: row.lastActivityAt.toISOString(), + unreadCount, + }; +} diff --git a/apps/api/src/conversations/reads.repository.ts b/apps/api/src/conversations/reads.repository.ts new file mode 100644 index 0000000..5bf2f2b --- /dev/null +++ b/apps/api/src/conversations/reads.repository.ts @@ -0,0 +1,158 @@ +import { Injectable } from '@nestjs/common'; +import { InjectDrizzle } from '@nestjs/drizzle'; +import { UNREAD_COUNT_MAX } from '@repo/contracts'; +import { and, eq, exists, gt, ne, sql, type SQL } from 'drizzle-orm'; +import type { Database } from '../db/database'; +import { + conversation, + conversationMember, + conversationRead, + message, + realmMember, +} from '../db/schema'; + +/** + * How far people have read, and what that leaves unread. Unread means + * messages from other people that are newer than the reader's marker or, + * for someone who has no marker yet, that came after they joined. + */ +@Injectable() +export class ReadsRepository { + constructor(@InjectDrizzle() private readonly db: Database) {} + + /** Unread counts of the direct and group chats a user is in, by chat id. */ + async countsForChats(userId: string): Promise> { + const rows = await this.db + .select({ + conversationId: conversationMember.conversationId, + unread: unreadCount( + userId, + conversationMember.conversationId, + conversationMember.joinedAt, + ), + }) + .from(conversationMember) + .leftJoin( + conversationRead, + and( + eq( + conversationRead.conversationId, + conversationMember.conversationId, + ), + eq(conversationRead.userId, conversationMember.userId), + ), + ) + .where(eq(conversationMember.userId, userId)); + return new Map(rows.map((row) => [row.conversationId, row.unread])); + } + + /** Unread counts of a realm's cauldrons for one of its members, by id. */ + async countsForCauldrons( + userId: string, + realmId: string, + ): Promise> { + const rows = await this.db + .select({ + conversationId: conversation.id, + unread: unreadCount(userId, conversation.id, realmMember.joinedAt), + }) + .from(conversation) + .innerJoin( + realmMember, + and( + eq(realmMember.realmId, conversation.realmId), + eq(realmMember.userId, userId), + ), + ) + .leftJoin( + conversationRead, + and( + eq(conversationRead.conversationId, conversation.id), + eq(conversationRead.userId, userId), + ), + ) + .where(eq(conversation.realmId, realmId)); + return new Map(rows.map((row) => [row.conversationId, row.unread])); + } + + /** The realms a user is in that have something unread in any cauldron. */ + async realmsWithUnread(userId: string): Promise> { + const unreadMessage = this.db + .select({ one: sql`1` }) + .from(conversation) + .innerJoin(message, eq(message.conversationId, conversation.id)) + .leftJoin( + conversationRead, + and( + eq(conversationRead.conversationId, conversation.id), + eq(conversationRead.userId, userId), + ), + ) + .where( + and( + eq(conversation.realmId, realmMember.realmId), + isUnread(userId, realmMember.joinedAt), + ), + ); + const rows = await this.db + .select({ realmId: realmMember.realmId }) + .from(realmMember) + .where(and(eq(realmMember.userId, userId), exists(unreadMessage))); + return new Set(rows.map((row) => row.realmId)); + } + + /** + * Moves a reader's marker to a message, never backwards, and answers with + * how many messages from other people came after where it now stands. + */ + async mark( + userId: string, + conversationId: string, + messageId: string, + ): Promise { + const [marker] = await this.db + .insert(conversationRead) + .values({ userId, conversationId, lastReadMessageId: messageId }) + .onConflictDoUpdate({ + target: [conversationRead.userId, conversationRead.conversationId], + set: { + lastReadMessageId: sql`greatest(${conversationRead.lastReadMessageId}, excluded.last_read_message_id)`, + updatedAt: sql`now()`, + }, + }) + .returning({ messageId: conversationRead.lastReadMessageId }); + const newer = await this.db + .select({ id: message.id }) + .from(message) + .where( + and( + eq(message.conversationId, conversationId), + ne(message.authorId, userId), + gt(message.id, marker.messageId), + ), + ) + .limit(UNREAD_COUNT_MAX); + return newer.length; + } +} + +/** + * Whether a message row is unread by the user. For queries that join + * `conversation_read` (the user's marker, if any) next to `message`. + */ +function isUnread(userId: string, joinedAt: SQL | typeof realmMember.joinedAt) { + return sql`${message.authorId} <> ${userId} and case when ${conversationRead.lastReadMessageId} is not null then ${message.id} > ${conversationRead.lastReadMessageId} else ${message.createdAt} > ${joinedAt} end`; +} + +/** + * A column counting a conversation's unread messages, up to the limit. For + * queries that join `conversation_read`, so they name every column in full. + */ +function unreadCount( + userId: string, + conversationId: + typeof conversation.id | typeof conversationMember.conversationId, + joinedAt: typeof realmMember.joinedAt | typeof conversationMember.joinedAt, +) { + return sql`(select count(*)::int from (select 1 from ${message} where ${message.conversationId} = ${conversationId} and ${isUnread(userId, joinedAt as typeof realmMember.joinedAt)} limit ${UNREAD_COUNT_MAX}) as unread)`; +} diff --git a/apps/api/src/db/migrate.ts b/apps/api/src/db/migrate.ts new file mode 100644 index 0000000..af25c5c --- /dev/null +++ b/apps/api/src/db/migrate.ts @@ -0,0 +1,30 @@ +import { join } from 'node:path'; +import { drizzle } from 'drizzle-orm/node-postgres'; +import { migrate } from 'drizzle-orm/node-postgres/migrator'; + +/** + * Applies the migrations in `drizzle/` that the database doesn't have yet, + * then exits. For production, where Drizzle Kit (a development tool) isn't + * installed: run `node dist/db/migrate.js` once per release, before the new + * API starts, never from every instance as it boots. Development keeps + * using `pnpm db:migrate`; both keep the same record of what was applied. + */ +const url = process.env.DATABASE_URL; +if (!url) { + console.error('DATABASE_URL is not set.'); + process.exit(1); +} + +const db = drizzle(url); +try { + // Beside `dist/` in the package, wherever the process was started from. + await migrate(db, { + migrationsFolder: join(import.meta.dirname, '../../drizzle'), + }); + console.log('Migrations are up to date.'); +} catch (error) { + console.error('Could not apply migrations.', error); + process.exitCode = 1; +} finally { + await db.$client.end(); +} diff --git a/apps/api/src/db/relations.ts b/apps/api/src/db/relations.ts index 5e75406..a5fd58a 100644 --- a/apps/api/src/db/relations.ts +++ b/apps/api/src/db/relations.ts @@ -2,8 +2,83 @@ import { defineRelations } from 'drizzle-orm'; import { authRelations } from './schema/auth'; import * as schema from './schema'; -// Relations between the app's own tables (used by db.query...). -const appRelations = defineRelations(schema, () => ({})); +// Relations between the app's own tables (used by db.query...). Don't add +// relations that start from `user` here: Better Auth's part below replaces +// that entry. +const appRelations = defineRelations(schema, (r) => ({ + conversation: { + members: r.many.conversationMember({ + from: r.conversation.id, + to: r.conversationMember.conversationId, + }), + messages: r.many.message({ + from: r.conversation.id, + to: r.message.conversationId, + }), + }, + message: { + author: r.one.user({ + from: r.message.authorId, + to: r.user.id, + optional: false, + }), + attachments: r.many.attachment({ + from: r.message.id, + to: r.attachment.messageId, + }), + reactions: r.many.messageReaction({ + from: r.message.id, + to: r.messageReaction.messageId, + }), + }, + attachment: { + message: r.one.message({ + from: r.attachment.messageId, + to: r.message.id, + }), + }, + realm: { + cauldrons: r.many.conversation({ + from: r.realm.id, + to: r.conversation.realmId, + }), + roles: r.many.realmRole({ + from: r.realm.id, + to: r.realmRole.realmId, + }), + }, + realmMember: { + user: r.one.user({ + from: r.realmMember.userId, + to: r.user.id, + optional: false, + }), + // Roles given to the member; the "Everyone" role has no rows. + roles: r.many.realmMemberRole({ + from: [r.realmMember.realmId, r.realmMember.userId], + to: [r.realmMemberRole.realmId, r.realmMemberRole.userId], + }), + }, + realmInvite: { + realm: r.one.realm({ + from: r.realmInvite.realmId, + to: r.realm.id, + optional: false, + }), + createdBy: r.one.user({ + from: r.realmInvite.createdById, + to: r.user.id, + optional: false, + }), + }, + conversationMember: { + user: r.one.user({ + from: r.conversationMember.userId, + to: r.user.id, + optional: false, + }), + }, +})); // Better Auth's generated relations are a partial, so they go last. export const relations = { ...appRelations, ...authRelations }; diff --git a/apps/api/src/db/schema/auth.ts b/apps/api/src/db/schema/auth.ts index 9d31456..43bfb57 100644 --- a/apps/api/src/db/schema/auth.ts +++ b/apps/api/src/db/schema/auth.ts @@ -12,6 +12,8 @@ export const user = pgTable('user', { .defaultNow() .$onUpdate(() => /* @__PURE__ */ new Date()) .notNull(), + username: text('username').unique(), + bio: text('bio'), }); export const session = pgTable( diff --git a/apps/api/src/db/schema/conversations.ts b/apps/api/src/db/schema/conversations.ts new file mode 100644 index 0000000..5651723 --- /dev/null +++ b/apps/api/src/db/schema/conversations.ts @@ -0,0 +1,195 @@ +import { sql } from 'drizzle-orm'; +import { + index, + integer, + pgEnum, + pgTable, + primaryKey, + text, + timestamp, + uuid, +} from 'drizzle-orm/pg-core'; +import { user } from './auth'; +import { realm } from './realms'; + +/** + * "direct" is a one-to-one chat between friends; "group" is a named chat that + * people are added to; "cauldron" is a room of a realm, open to everyone in + * that realm (it has no rows in `conversation_member`). + */ +export const conversationType = pgEnum('conversation_type', [ + 'direct', + 'group', + 'cauldron', +]); + +/** Anything people post messages in, whatever its kind. */ +export const conversation = pgTable( + 'conversation', + { + id: uuid('id') + .primaryKey() + .default(sql`uuidv7()`), + type: conversationType('type').notNull(), + /** + * Direct conversations only: the two user ids, lower one first, joined by + * ":". Being unique, it keeps a pair of users to a single chat. + */ + directKey: text('direct_key').unique(), + /** Optional for groups, always set for cauldrons, empty otherwise. */ + name: text('name'), + /** Cauldrons only: the realm it belongs to. */ + realmId: uuid('realm_id').references(() => realm.id, { + onDelete: 'cascade', + }), + /** + * Groups only: the member who may remove others. Passed on when the owner + * leaves. Empty only if their account was deleted: the longest-standing + * member then acts as owner (`groupOwnerId` in the conversations service). + */ + ownerId: text('owner_id').references(() => user.id, { + onDelete: 'set null', + }), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + /** When it was created or last posted in; orders the conversation list. */ + lastActivityAt: timestamp('last_activity_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [index('conversation_realm_id_idx').on(table.realmId)], +); + +export const conversationMember = pgTable( + 'conversation_member', + { + conversationId: uuid('conversation_id') + .notNull() + .references(() => conversation.id, { onDelete: 'cascade' }), + userId: text('user_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), + joinedAt: timestamp('joined_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [ + primaryKey({ columns: [table.conversationId, table.userId] }), + index('conversation_member_user_id_idx').on(table.userId), + ], +); + +export const message = pgTable( + 'message', + { + // UUIDv7 starts with the time, so ids sort in the order messages were + // posted and history pages by id alone. + id: uuid('id') + .primaryKey() + .default(sql`uuidv7()`), + conversationId: uuid('conversation_id') + .notNull() + .references(() => conversation.id, { onDelete: 'cascade' }), + authorId: text('author_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), + content: text('content').notNull(), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [ + index('message_conversation_id_id_idx').on(table.conversationId, table.id), + ], +); + +/** + * A file posted with a message. The row is made when the upload is asked + * for, before the bytes arrive, and the file itself is kept in storage under + * `attachmentKey(id)`. Without a message it is either not sent yet or left + * behind by a message that was deleted; both are cleared out after a day. + */ +export const attachment = pgTable( + 'attachment', + { + id: uuid('id') + .primaryKey() + .default(sql`uuidv7()`), + uploaderId: text('uploader_id').references(() => user.id, { + onDelete: 'set null', + }), + messageId: uuid('message_id').references(() => message.id, { + onDelete: 'set null', + }), + filename: text('filename').notNull(), + contentType: text('content_type').notNull(), + /** Bytes. */ + size: integer('size').notNull(), + /** Pixels, for pictures shown in the chat. */ + width: integer('width'), + height: integer('height'), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [ + index('attachment_message_id_idx').on(table.messageId), + index('attachment_uploader_id_idx').on(table.uploaderId), + ], +); + +/** One person's emoji on a message. */ +export const messageReaction = pgTable( + 'message_reaction', + { + messageId: uuid('message_id') + .notNull() + .references(() => message.id, { onDelete: 'cascade' }), + userId: text('user_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), + emoji: text('emoji').notNull(), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [ + primaryKey({ columns: [table.messageId, table.userId, table.emoji] }), + ], +); + +/** + * How far someone has read a conversation or cauldron. No row means they + * have read nothing since they joined. + */ +export const conversationRead = pgTable( + 'conversation_read', + { + userId: text('user_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), + conversationId: uuid('conversation_id') + .notNull() + .references(() => conversation.id, { onDelete: 'cascade' }), + /** + * The newest message they have seen. Not a foreign key: the marker + * still says where they were if that message goes. + */ + lastReadMessageId: uuid('last_read_message_id').notNull(), + updatedAt: timestamp('updated_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [primaryKey({ columns: [table.userId, table.conversationId] })], +); + +/** The `directKey` for a chat between two users. */ +export function directConversationKey( + userId: string, + otherUserId: string, +): string { + return userId < otherUserId + ? `${userId}:${otherUserId}` + : `${otherUserId}:${userId}`; +} diff --git a/apps/api/src/db/schema/friends.ts b/apps/api/src/db/schema/friends.ts new file mode 100644 index 0000000..96570b3 --- /dev/null +++ b/apps/api/src/db/schema/friends.ts @@ -0,0 +1,84 @@ +import { sql } from 'drizzle-orm'; +import { + check, + index, + pgEnum, + pgTable, + primaryKey, + text, + timestamp, +} from 'drizzle-orm/pg-core'; +import { user } from './auth'; + +export const friendshipStatus = pgEnum('friendship_status', [ + 'pending', + 'accepted', +]); + +/** + * One row per pair of users, whichever of them asked. The pair is stored in + * a fixed order (see `friendPair`), so two people can never have two rows. + */ +export const friendship = pgTable( + 'friendship', + { + userLowId: text('user_low_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), + userHighId: text('user_high_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), + /** Who sent the request; the other one is who may accept it. */ + requestedById: text('requested_by_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), + status: friendshipStatus('status').notNull().default('pending'), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + acceptedAt: timestamp('accepted_at', { withTimezone: true }), + }, + (table) => [ + primaryKey({ columns: [table.userLowId, table.userHighId] }), + index('friendship_user_high_id_idx').on(table.userHighId), + // Byte order ("C"), the same order JavaScript's < gives for these ids. + check( + 'friendship_ordered_pair', + sql`${table.userLowId} < ${table.userHighId} COLLATE "C"`, + ), + ], +); + +/** + * One person shutting another out: while the row is there, neither can send + * the other a friend request, so they can't become friends, message each + * other directly or call. Only the blocker can lift it. + */ +export const userBlock = pgTable( + 'user_block', + { + blockerId: text('blocker_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), + blockedId: text('blocked_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [ + primaryKey({ columns: [table.blockerId, table.blockedId] }), + index('user_block_blocked_id_idx').on(table.blockedId), + ], +); + +/** The two ids in the order the table stores them. */ +export function friendPair( + userId: string, + otherUserId: string, +): { userLowId: string; userHighId: string } { + return userId < otherUserId + ? { userLowId: userId, userHighId: otherUserId } + : { userLowId: otherUserId, userHighId: userId }; +} diff --git a/apps/api/src/db/schema/index.ts b/apps/api/src/db/schema/index.ts index 404d570..64e6f43 100644 --- a/apps/api/src/db/schema/index.ts +++ b/apps/api/src/db/schema/index.ts @@ -1,6 +1,4 @@ -// Every table the app owns is exported from here: Drizzle Kit reads this -// file to build migrations, and Better Auth looks its tables up by name. -// -// auth.ts is generated by `pnpm auth:generate`; put your own tables in -// separate files next to it and re-export them below. export * from './auth'; +export * from './conversations'; +export * from './friends'; +export * from './realms'; diff --git a/apps/api/src/db/schema/realms.ts b/apps/api/src/db/schema/realms.ts new file mode 100644 index 0000000..1f59130 --- /dev/null +++ b/apps/api/src/db/schema/realms.ts @@ -0,0 +1,148 @@ +import { sql } from 'drizzle-orm'; +import { + boolean, + foreignKey, + index, + integer, + pgTable, + primaryKey, + text, + timestamp, + uniqueIndex, + uuid, +} from 'drizzle-orm/pg-core'; +import type { RealmPermission } from '@repo/contracts'; +import { user } from './auth'; + +/** + * A community with its own members, roles and cauldrons. The cauldrons are + * rows of `conversation` (type "cauldron") that point here. + */ +export const realm = pgTable('realm', { + id: uuid('id') + .primaryKey() + .default(sql`uuidv7()`), + name: text('name').notNull(), + /** May do everything, whatever roles say. Their account going takes the realm with it. */ + ownerId: text('owner_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), +}); + +export const realmMember = pgTable( + 'realm_member', + { + realmId: uuid('realm_id') + .notNull() + .references(() => realm.id, { onDelete: 'cascade' }), + userId: text('user_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), + joinedAt: timestamp('joined_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [ + primaryKey({ columns: [table.realmId, table.userId] }), + index('realm_member_user_id_idx').on(table.userId), + ], +); + +export const realmRole = pgTable( + 'realm_role', + { + // UUIDv7, so ordering by id lists roles oldest first. + id: uuid('id') + .primaryKey() + .default(sql`uuidv7()`), + realmId: uuid('realm_id') + .notNull() + .references(() => realm.id, { onDelete: 'cascade' }), + name: text('name').notNull(), + permissions: text('permissions').$type().array().notNull(), + /** + * The "Everyone" role, which all members have without a row in + * `realm_member_role`. Each realm has exactly one. + */ + isDefault: boolean('is_default').notNull().default(false), + }, + (table) => [ + index('realm_role_realm_id_idx').on(table.realmId), + uniqueIndex('realm_role_one_default_idx') + .on(table.realmId) + .where(sql`${table.isDefault}`), + ], +); + +/** A role given to a member. Goes away with the member or the role. */ +export const realmMemberRole = pgTable( + 'realm_member_role', + { + realmId: uuid('realm_id').notNull(), + userId: text('user_id').notNull(), + roleId: uuid('role_id') + .notNull() + .references(() => realmRole.id, { onDelete: 'cascade' }), + }, + (table) => [ + primaryKey({ columns: [table.realmId, table.userId, table.roleId] }), + foreignKey({ + name: 'realm_member_role_member_fk', + columns: [table.realmId, table.userId], + foreignColumns: [realmMember.realmId, realmMember.userId], + }).onDelete('cascade'), + index('realm_member_role_role_id_idx').on(table.roleId), + ], +); + +/** A link that lets whoever holds it join a realm. */ +export const realmInvite = pgTable( + 'realm_invite', + { + /** Random and unguessable: it is the whole secret. */ + code: text('code').primaryKey(), + realmId: uuid('realm_id') + .notNull() + .references(() => realm.id, { onDelete: 'cascade' }), + createdById: text('created_by_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + /** Null for a link that doesn't expire. */ + expiresAt: timestamp('expires_at', { withTimezone: true }), + /** Null for no limit. */ + maxUses: integer('max_uses'), + /** How many people joined with it. */ + uses: integer('uses').notNull().default(0), + }, + (table) => [index('realm_invite_realm_id_idx').on(table.realmId)], +); + +/** + * Someone put out of a realm for good: an invite no longer lets them in. + * Lifting the ban deletes the row. + */ +export const realmBan = pgTable( + 'realm_ban', + { + realmId: uuid('realm_id') + .notNull() + .references(() => realm.id, { onDelete: 'cascade' }), + userId: text('user_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), + bannedById: text('banned_by_id').references(() => user.id, { + onDelete: 'set null', + }), + reason: text('reason'), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [primaryKey({ columns: [table.realmId, table.userId] })], +); diff --git a/apps/api/src/files/files.controller.ts b/apps/api/src/files/files.controller.ts new file mode 100644 index 0000000..65e7f60 --- /dev/null +++ b/apps/api/src/files/files.controller.ts @@ -0,0 +1,48 @@ +import { + Controller, + Get, + NotFoundException, + Put, + Req, + Res, +} from '@nestjs/common'; +import { + receiveSignedUpload, + S3Disk, + serveSignedUrl, + StorageDisk, +} from '@nestjs/storage'; +import { AllowAnonymous } from '@thallesp/nestjs-better-auth'; +import type { Request, Response } from 'express'; +import { FILES_ROUTE } from './files.disk'; +import { SkipThrottle } from '@nestjs/throttler'; + +/** + * Stands in for S3 when files are kept on the local disk (or in memory): + * the signed URLs the disk hands out lead here. The signature in the URL is + * what lets a request in, as with S3, so no session is asked for; it says + * which file, for how long and, for an upload, its exact type and size. + */ +@Controller(FILES_ROUTE) +@AllowAnonymous() +// Each signed URL was handed out by a route with a limit of its own. +@SkipThrottle() +export class FilesController { + constructor(private readonly disk: StorageDisk) {} + + @Get() + download(@Req() req: Request, @Res({ passthrough: true }) res: Response) { + this.assertServedHere(); + return serveSignedUrl(this.disk, { req, res }); + } + + @Put() + async upload(@Req() req: Request, @Res({ passthrough: true }) res: Response) { + this.assertServedHere(); + await receiveSignedUpload(this.disk, { req, res }); + } + + private assertServedHere() { + if (this.disk instanceof S3Disk) throw new NotFoundException(); + } +} diff --git a/apps/api/src/files/files.disk.ts b/apps/api/src/files/files.disk.ts new file mode 100644 index 0000000..21f263c --- /dev/null +++ b/apps/api/src/files/files.disk.ts @@ -0,0 +1,60 @@ +import { createHmac } from 'node:crypto'; +import { resolve } from 'node:path'; +import type { ConfigService } from '@nestjs/config'; +import { + InMemoryDisk, + LocalDisk, + S3Disk, + type StorageDisk, +} from '@nestjs/storage'; +import type { Env } from '../config/env'; + +/** The route that serves and receives files for disks that can't presign. */ +export const FILES_ROUTE = 'files'; + +/** + * Where uploaded files are kept, chosen with STORAGE_DRIVER. Whatever the + * disk, browsers send and fetch files with signed URLs: S3 signs its own, + * and for the others the URLs lead to FilesController. + */ +export function createFilesDisk(config: ConfigService): StorageDisk { + const driver = config.getOrThrow('STORAGE_DRIVER', { infer: true }); + if (driver === 's3') { + const accessKeyId = config.get('S3_ACCESS_KEY_ID', { infer: true }); + const secretAccessKey = config.get('S3_SECRET_ACCESS_KEY', { infer: true }); + return new S3Disk({ + // The env schema refuses "s3" without a bucket. + bucket: config.getOrThrow('S3_BUCKET', { infer: true }), + region: config.get('S3_REGION', { infer: true }), + endpoint: config.get('S3_ENDPOINT', { infer: true }), + forcePathStyle: config.get('S3_FORCE_PATH_STYLE', { infer: true }), + // Without keys here, the disk reads the usual AWS_* variables. + credentials: + accessKeyId && secretAccessKey + ? { accessKeyId, secretAccessKey } + : undefined, + }); + } + + const signedUrls = { + baseUrl: new URL( + FILES_ROUTE, + `${config.getOrThrow('BETTER_AUTH_URL', { infer: true })}/`, + ), + // A key of its own, derived from the app's secret, so a signed file URL + // and a session token can never stand in for one another. + keys: [ + createHmac( + 'sha256', + config.getOrThrow('BETTER_AUTH_SECRET', { infer: true }), + ) + .update('file-urls') + .digest(), + ], + }; + if (driver === 'memory') return new InMemoryDisk({ signedUrls }); + return new LocalDisk({ + root: resolve(config.getOrThrow('STORAGE_LOCAL_ROOT', { infer: true })), + signedUrls, + }); +} diff --git a/apps/api/src/files/files.module.ts b/apps/api/src/files/files.module.ts new file mode 100644 index 0000000..22f531f --- /dev/null +++ b/apps/api/src/files/files.module.ts @@ -0,0 +1,24 @@ +import { Module } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { StorageModule } from '@nestjs/storage'; +import type { Env } from '../config/env'; +import { FilesController } from './files.controller'; +import { createFilesDisk } from './files.disk'; + +/** + * File storage for the whole app: inject `StorageDisk` anywhere (the storage + * module is global) and keep files under a prefix of your own. + */ +@Module({ + imports: [ + StorageModule.forRootAsync({ + useFactory: (config: ConfigService) => ({ + default: 'files', + disks: { files: createFilesDisk(config) }, + }), + inject: [ConfigService], + }), + ], + controllers: [FilesController], +}) +export class FilesModule {} diff --git a/apps/api/src/friends/friends.controller.ts b/apps/api/src/friends/friends.controller.ts new file mode 100644 index 0000000..26de525 --- /dev/null +++ b/apps/api/src/friends/friends.controller.ts @@ -0,0 +1,78 @@ +import { + Body, + Controller, + Delete, + Get, + HttpCode, + Param, + Post, + Put, +} from '@nestjs/common'; +import { + sendFriendRequestSchema, + userIdSchema, + type SendFriendRequest, +} from '@repo/contracts'; +import { Session, type UserSession } from '@thallesp/nestjs-better-auth'; +import type { Auth } from '../auth/auth'; +import { FriendsService } from './friends.service'; +import { AtMost } from '../rate-limit/at-most'; + +@Controller('friends') +export class FriendsController { + constructor(private readonly friends: FriendsService) {} + + /** Friends plus the requests waiting in either direction. */ + @Get() + getOverview(@Session() session: UserSession) { + return this.friends.getOverview(session.user.id); + } + + // Also keeps it from being used to find out which usernames exist. + @Post('requests') + @AtMost(10, { seconds: 60 }) + sendRequest( + @Session() session: UserSession, + @Body({ schema: sendFriendRequestSchema }) body: SendFriendRequest, + ) { + return this.friends.sendRequest(session.user.id, body.username); + } + + @Post('requests/:userId/accept') + @HttpCode(204) + acceptRequest( + @Session() session: UserSession, + @Param('userId', { schema: userIdSchema }) userId: string, + ) { + return this.friends.acceptRequest(session.user.id, userId); + } + + /** Blocks someone; fine if they were blocked already. */ + @Put('blocks/:userId') + @HttpCode(204) + block( + @Session() session: UserSession, + @Param('userId', { schema: userIdSchema }) userId: string, + ) { + return this.friends.block(session.user.id, userId); + } + + @Delete('blocks/:userId') + @HttpCode(204) + unblock( + @Session() session: UserSession, + @Param('userId', { schema: userIdSchema }) userId: string, + ) { + return this.friends.unblock(session.user.id, userId); + } + + /** Unfriends, declines an incoming request or cancels an outgoing one. */ + @Delete(':userId') + @HttpCode(204) + remove( + @Session() session: UserSession, + @Param('userId', { schema: userIdSchema }) userId: string, + ) { + return this.friends.remove(session.user.id, userId); + } +} diff --git a/apps/api/src/friends/friends.module.ts b/apps/api/src/friends/friends.module.ts new file mode 100644 index 0000000..24c88a3 --- /dev/null +++ b/apps/api/src/friends/friends.module.ts @@ -0,0 +1,16 @@ +import { Module } from '@nestjs/common'; +import { CallsModule } from '../calls/calls.module'; +import { RealtimeModule } from '../realtime/realtime.module'; +import { UsersRepository } from '../users/users.repository'; +import { FriendsController } from './friends.controller'; +import { FriendsRepository } from './friends.repository'; +import { FriendsService } from './friends.service'; + +@Module({ + imports: [RealtimeModule, CallsModule], + controllers: [FriendsController], + // UsersRepository is listed here rather than importing UsersModule: it has + // no state, and feature modules that import each other end up in cycles. + providers: [FriendsService, FriendsRepository, UsersRepository], +}) +export class FriendsModule {} diff --git a/apps/api/src/friends/friends.repository.ts b/apps/api/src/friends/friends.repository.ts new file mode 100644 index 0000000..abb52f9 --- /dev/null +++ b/apps/api/src/friends/friends.repository.ts @@ -0,0 +1,193 @@ +import { Injectable } from '@nestjs/common'; +import { InjectDrizzle } from '@nestjs/drizzle'; +import { and, eq, inArray, ne, or, sql } from 'drizzle-orm'; +import type { Database } from '../db/database'; +import { friendPair, friendship, user, userBlock } from '../db/schema'; + +export type FriendshipRow = typeof friendship.$inferSelect; +type UserRow = typeof user.$inferSelect; + +@Injectable() +export class FriendsRepository { + constructor(@InjectDrizzle() private readonly db: Database) {} + + /** The row between two users, pending or accepted. */ + async find( + userId: string, + otherUserId: string, + ): Promise { + const [row] = await this.db + .select() + .from(friendship) + .where(pairIs(userId, otherUserId)); + return row; + } + + async areFriends(userId: string, otherUserId: string): Promise { + const row = await this.find(userId, otherUserId); + return row?.status === 'accepted'; + } + + /** Whether every one of `otherUserIds` is a friend of the user. */ + async areAllFriends( + userId: string, + otherUserIds: string[], + ): Promise { + if (otherUserIds.length === 0) return true; + const rows = await this.db + .select({ low: friendship.userLowId }) + .from(friendship) + .where( + and( + eq(friendship.status, 'accepted'), + or( + and( + eq(friendship.userLowId, userId), + inArray(friendship.userHighId, otherUserIds), + ), + and( + eq(friendship.userHighId, userId), + inArray(friendship.userLowId, otherUserIds), + ), + ), + ), + ); + return rows.length === new Set(otherUserIds).size; + } + + /** Every friendship and request of a user, each with the other person. */ + listFor( + userId: string, + ): Promise<{ friendship: FriendshipRow; other: UserRow }[]> { + return this.db + .select({ friendship, other: user }) + .from(friendship) + .innerJoin( + user, + sql`${user.id} = case when ${friendship.userLowId} = ${userId} then ${friendship.userHighId} else ${friendship.userLowId} end`, + ) + .where( + or(eq(friendship.userLowId, userId), eq(friendship.userHighId, userId)), + ) + .orderBy(user.name); + } + + /** Returns nothing when the pair already has a row. */ + async createRequest( + requestedById: string, + otherUserId: string, + ): Promise { + const [row] = await this.db + .insert(friendship) + .values({ ...friendPair(requestedById, otherUserId), requestedById }) + .onConflictDoNothing() + .returning(); + return row; + } + + /** Accepts the request `requestedById` sent to `userId`, if there is one. */ + async accept( + userId: string, + requestedById: string, + ): Promise { + const [row] = await this.db + .update(friendship) + .set({ status: 'accepted', acceptedAt: new Date() }) + .where( + and( + pairIs(userId, requestedById), + eq(friendship.status, 'pending'), + eq(friendship.requestedById, requestedById), + ne(friendship.requestedById, userId), + ), + ) + .returning(); + return row; + } + + /** The people a user blocked, by name. */ + async listBlocked(userId: string): Promise { + const rows = await this.db + .select({ blocked: user }) + .from(userBlock) + .innerJoin(user, eq(user.id, userBlock.blockedId)) + .where(eq(userBlock.blockerId, userId)) + .orderBy(user.name); + return rows.map((row) => row.blocked); + } + + /** + * Whether a block stands between two users, and whose it is. When each + * blocked the other, the user's own is the one reported. + */ + async findBlock( + userId: string, + otherUserId: string, + ): Promise<'mine' | 'theirs' | undefined> { + const rows = await this.db + .select({ blockerId: userBlock.blockerId }) + .from(userBlock) + .where( + or( + and( + eq(userBlock.blockerId, userId), + eq(userBlock.blockedId, otherUserId), + ), + and( + eq(userBlock.blockerId, otherUserId), + eq(userBlock.blockedId, userId), + ), + ), + ); + if (rows.some((row) => row.blockerId === userId)) return 'mine'; + return rows.length > 0 ? 'theirs' : undefined; + } + + /** + * Blocks someone and, in the same step, ends the friendship or request + * between the two. Fine if they were blocked already. + */ + async block(blockerId: string, blockedId: string): Promise { + await this.db.transaction(async (tx) => { + await tx + .insert(userBlock) + .values({ blockerId, blockedId }) + .onConflictDoNothing(); + await tx.delete(friendship).where(pairIs(blockerId, blockedId)); + }); + } + + /** Answers false when there was no block to lift. */ + async unblock(blockerId: string, blockedId: string): Promise { + const removed = await this.db + .delete(userBlock) + .where( + and( + eq(userBlock.blockerId, blockerId), + eq(userBlock.blockedId, blockedId), + ), + ) + .returning({ blockedId: userBlock.blockedId }); + return removed.length > 0; + } + + /** Removes a friendship or a request in either direction. */ + async remove( + userId: string, + otherUserId: string, + ): Promise { + const [row] = await this.db + .delete(friendship) + .where(pairIs(userId, otherUserId)) + .returning(); + return row; + } +} + +function pairIs(userId: string, otherUserId: string) { + const pair = friendPair(userId, otherUserId); + return and( + eq(friendship.userLowId, pair.userLowId), + eq(friendship.userHighId, pair.userHighId), + ); +} diff --git a/apps/api/src/friends/friends.service.ts b/apps/api/src/friends/friends.service.ts new file mode 100644 index 0000000..ac918fc --- /dev/null +++ b/apps/api/src/friends/friends.service.ts @@ -0,0 +1,144 @@ +import { + BadRequestException, + ConflictException, + ForbiddenException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import type { FriendRequestResult, FriendsOverview } from '@repo/contracts'; +import { CallsService } from '../calls/calls.service'; +import { RealtimeService } from '../realtime/realtime.service'; +import { toUserSummary } from '../users/user-summary'; +import { UsersRepository } from '../users/users.repository'; +import { FriendsRepository } from './friends.repository'; + +@Injectable() +export class FriendsService { + constructor( + private readonly friends: FriendsRepository, + private readonly users: UsersRepository, + private readonly calls: CallsService, + private readonly realtime: RealtimeService, + ) {} + + async getOverview(userId: string): Promise { + const [rows, blocked] = await Promise.all([ + this.friends.listFor(userId), + this.friends.listBlocked(userId), + ]); + const overview: FriendsOverview = { + friends: [], + incoming: [], + outgoing: [], + blocked: blocked.map(toUserSummary), + }; + for (const { friendship, other } of rows) { + const user = toUserSummary(other); + if (friendship.status === 'accepted') { + overview.friends.push(user); + continue; + } + const request = { user, createdAt: friendship.createdAt.toISOString() }; + if (friendship.requestedById === userId) { + overview.outgoing.push(request); + } else { + overview.incoming.push(request); + } + } + return overview; + } + + async sendRequest( + userId: string, + username: string, + ): Promise { + const target = await this.users.findByUsername(username); + if (!target) { + throw new NotFoundException('No one has that username.'); + } + if (target.id === userId) { + throw new BadRequestException("You can't add yourself."); + } + const user = toUserSummary(target); + + const block = await this.friends.findBlock(userId, target.id); + if (block === 'mine') { + throw new ConflictException( + 'You blocked this person. Unblock them first.', + ); + } + if (block === 'theirs') { + // Doesn't say why: being blocked isn't the asker's to find out. + throw new ForbiddenException("You can't send this person a request."); + } + + const existing = await this.friends.find(userId, target.id); + if (existing?.status === 'accepted') { + throw new ConflictException("You're already friends."); + } + if (existing?.requestedById === userId) { + throw new ConflictException('You already sent them a request.'); + } + if (existing) { + // They asked first, so asking back is the same as accepting. + await this.acceptRequest(userId, target.id); + return { status: 'accepted', user }; + } + + const created = await this.friends.createRequest(userId, target.id); + if (!created) { + // The other person sent a request in the same instant. + throw new ConflictException('A request between you already exists.'); + } + this.notify(userId, target.id); + return { status: 'pending', user }; + } + + async acceptRequest(userId: string, requestedById: string): Promise { + const accepted = await this.friends.accept(userId, requestedById); + if (!accepted) { + throw new NotFoundException('No request from this user.'); + } + this.notify(userId, requestedById); + } + + /** Unfriends, declines an incoming request or cancels an outgoing one. */ + async remove(userId: string, otherUserId: string): Promise { + const removed = await this.friends.remove(userId, otherUserId); + if (!removed) { + throw new NotFoundException('No friendship or request with this user.'); + } + this.notify(userId, otherUserId); + // A direct chat takes friendship to add to, and so does its call. + await this.calls.endDirect(userId, otherUserId); + } + + /** + * Shuts someone out: ends the friendship or request between the two and + * refuses new requests either way until the user unblocks them. + */ + async block(userId: string, otherUserId: string): Promise { + if (otherUserId === userId) { + throw new BadRequestException("You can't block yourself."); + } + if (!(await this.users.findById(otherUserId))) { + throw new NotFoundException('User not found.'); + } + await this.friends.block(userId, otherUserId); + // Both lists change if they were friends; the blocked person isn't + // told anything beyond that. + this.notify(userId, otherUserId); + await this.calls.endDirect(userId, otherUserId); + } + + async unblock(userId: string, otherUserId: string): Promise { + if (!(await this.friends.unblock(userId, otherUserId))) { + throw new NotFoundException("You haven't blocked this user."); + } + this.notify(userId); + } + + private notify(...userIds: string[]) { + this.realtime.emitToUsers(userIds, 'friends:changed'); + } +} diff --git a/apps/api/src/health/health.controller.ts b/apps/api/src/health/health.controller.ts new file mode 100644 index 0000000..74a809a --- /dev/null +++ b/apps/api/src/health/health.controller.ts @@ -0,0 +1,36 @@ +import { Controller, Get } from '@nestjs/common'; +import { HealthCheck, HealthCheckService } from '@nestjs/terminus'; +import { AllowAnonymous } from '@thallesp/nestjs-better-auth'; +import { + DatabaseHealthIndicator, + RedisHealthIndicator, +} from './health.indicators'; +import { SkipThrottle } from '@nestjs/throttler'; + +@AllowAnonymous() +// Asked every few seconds by whatever runs the app. +@SkipThrottle() +@Controller() +export class HealthController { + constructor( + private readonly health: HealthCheckService, + private readonly database: DatabaseHealthIndicator, + private readonly redis: RedisHealthIndicator, + ) {} + + /** Liveness: the process is up. Touches nothing else. */ + @Get('health') + live() { + return { status: 'ok' }; + } + + /** Readiness: 503 unless the database and Redis both answer. */ + @Get('ready') + @HealthCheck() + ready() { + return this.health.check([ + () => this.database.isHealthy('database'), + () => this.redis.isHealthy('redis'), + ]); + } +} diff --git a/apps/api/src/health/health.indicators.ts b/apps/api/src/health/health.indicators.ts new file mode 100644 index 0000000..db794b6 --- /dev/null +++ b/apps/api/src/health/health.indicators.ts @@ -0,0 +1,41 @@ +import { Inject, Injectable } from '@nestjs/common'; +import { InjectDrizzle } from '@nestjs/drizzle'; +import { HealthIndicatorService } from '@nestjs/terminus'; +import { sql } from 'drizzle-orm'; +import { Redis } from 'ioredis'; +import type { Database } from '../db/database'; +import { REDIS } from '../redis/redis.module'; + +@Injectable() +export class DatabaseHealthIndicator { + constructor( + private readonly indicators: HealthIndicatorService, + @InjectDrizzle() private readonly db: Database, + ) {} + + isHealthy(key: string) { + return this.indicators + .check(key) + .attempt(async () => { + await this.db.execute(sql`select 1`); + }) + .withTimeout('1s'); + } +} + +@Injectable() +export class RedisHealthIndicator { + constructor( + private readonly indicators: HealthIndicatorService, + @Inject(REDIS) private readonly redis: Redis, + ) {} + + isHealthy(key: string) { + return this.indicators + .check(key) + .attempt(async () => { + await this.redis.ping(); + }) + .withTimeout('1s'); + } +} diff --git a/apps/api/src/health/health.module.ts b/apps/api/src/health/health.module.ts new file mode 100644 index 0000000..68000e4 --- /dev/null +++ b/apps/api/src/health/health.module.ts @@ -0,0 +1,15 @@ +import { Module } from '@nestjs/common'; +import { TerminusModule } from '@nestjs/terminus'; +import { RedisModule } from '../redis/redis.module'; +import { HealthController } from './health.controller'; +import { + DatabaseHealthIndicator, + RedisHealthIndicator, +} from './health.indicators'; + +@Module({ + imports: [TerminusModule, RedisModule], + controllers: [HealthController], + providers: [DatabaseHealthIndicator, RedisHealthIndicator], +}) +export class HealthModule {} diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index 6363900..3efc776 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -1,13 +1,40 @@ +import { ConsoleLogger } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; import { NestFactory } from '@nestjs/core'; +import type { Server } from 'node:http'; import { AppModule } from './app.module'; +import type { Env } from './config/env'; +import { RedisIoAdapter } from './realtime/redis-io.adapter'; +import { REDIS, REDIS_SUBSCRIBER } from './redis/redis.module'; +import { setUpHttp } from './setup'; async function bootstrap() { const app = await NestFactory.create(AppModule, { // Better Auth reads the raw request body; AuthModule parses JSON and // form bodies for every other route. bodyParser: false, + // One JSON object per line in production, for whatever collects stdout. + logger: new ConsoleLogger({ + json: process.env.NODE_ENV === 'production', + redact: ['password', 'authorization', 'cookie', 'token'], + }), }); - app.enableShutdownHooks(); // closes the database pool on SIGTERM/SIGINT - await app.listen(process.env.PORT ?? 3000); + const config = app.get>(ConfigService); + + setUpHttp(app); + // Socket events go through Redis, so they reach clients on any instance. + app.useWebSocketAdapter( + new RedisIoAdapter(app, app.get(REDIS), app.get(REDIS_SUBSCRIBER)), + ); + app.enableShutdownHooks(); // closes the database pool and Redis on SIGTERM/SIGINT + + // A proxy or load balancer keeps idle connections to reuse them, usually + // for a minute. Node closes them after 5 seconds by default, and a request + // sent down one it just closed comes back to the browser as a 502. + const server: Server = app.getHttpServer(); + server.keepAliveTimeout = 65_000; + server.headersTimeout = 66_000; + + await app.listen(config.getOrThrow('PORT', { infer: true })); } await bootstrap(); diff --git a/apps/api/src/rate-limit/at-most.ts b/apps/api/src/rate-limit/at-most.ts new file mode 100644 index 0000000..0bd8f9a --- /dev/null +++ b/apps/api/src/rate-limit/at-most.ts @@ -0,0 +1,10 @@ +import { Throttle } from '@nestjs/throttler'; + +/** + * Tightens a route's limit below the default in RateLimitModule: one person + * may call it this many times in a window this long, then gets 429 until + * the window ends. For routes that cost something each time or reach other + * people: posting, inviting, anything that could be used to flood or guess. + */ +export const AtMost = (times: number, { seconds }: { seconds: number }) => + Throttle({ default: { limit: times, ttl: seconds * 1000 } }); diff --git a/apps/api/src/rate-limit/fixed-window.ts b/apps/api/src/rate-limit/fixed-window.ts new file mode 100644 index 0000000..3cecac1 --- /dev/null +++ b/apps/api/src/rate-limit/fixed-window.ts @@ -0,0 +1,38 @@ +import type { Redis } from 'ioredis'; + +// Counts one more for the key and starts its window on the first count, in +// one step: two API instances counting at once can't both be the first. +const HIT = ` +local hits = redis.call('INCR', KEYS[1]) +local left = redis.call('PTTL', KEYS[1]) +if left < 0 then + redis.call('PEXPIRE', KEYS[1], ARGV[1]) + left = tonumber(ARGV[1]) +end +return { hits, left } +`; + +export interface WindowCount { + /** How often the key was counted in its current window, this time included. */ + hits: number; + /** Until the window ends and counting starts over, in milliseconds. */ + remainingMs: number; +} + +/** + * Counts an attempt against a key in Redis, in windows of a fixed length + * that start with the first attempt. Shared by every API instance. + */ +export async function countInWindow( + redis: Redis, + key: string, + windowMs: number, +): Promise { + const [hits, remainingMs] = (await redis.eval( + HIT, + 1, + `rate:${key}`, + Math.ceil(windowMs), + )) as [number, number]; + return { hits, remainingMs }; +} diff --git a/apps/api/src/rate-limit/rate-limit.module.ts b/apps/api/src/rate-limit/rate-limit.module.ts new file mode 100644 index 0000000..281624a --- /dev/null +++ b/apps/api/src/rate-limit/rate-limit.module.ts @@ -0,0 +1,50 @@ +import { Module } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { APP_GUARD } from '@nestjs/core'; +import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler'; +import type { Request } from 'express'; +import type { Redis } from 'ioredis'; +import type { Env } from '../config/env'; +import { REDIS, RedisModule } from '../redis/redis.module'; +import { RedisThrottlerStorage } from './redis-throttler.storage'; + +/** What every route allows one person unless it says otherwise. */ +export const DEFAULT_LIMIT = { ttl: 60_000, limit: 240 }; + +/** + * Limits how often one person may call each route: 429 with Retry-After + * beyond that. A route tightens its own limit with @Throttle() or opts out + * with @SkipThrottle(). + * + * AppModule imports this after AuthModule: global guards run in the order + * their modules are imported, and the limit is per user, so the session has + * to be known by the time this guard runs. A request without one is refused + * by the auth guard before it is counted; routes open to anyone count per + * address. The sign-in routes under /api/auth have limits of their own, set + * in src/auth/auth.ts. + */ +@Module({ + imports: [ + ThrottlerModule.forRootAsync({ + imports: [RedisModule], + inject: [ConfigService, REDIS], + useFactory: (config: ConfigService, redis: Redis) => { + const isOn = config.getOrThrow('RATE_LIMIT', { infer: true }); + return { + throttlers: [DEFAULT_LIMIT], + storage: new RedisThrottlerStorage(redis), + skipIf: () => !isOn, + errorMessage: 'Too many requests. Wait a moment and try again.', + getTracker: (req) => { + const { user, ip } = req as Request & { + user?: { id: string } | null; + }; + return user ? `user:${user.id}` : `ip:${ip}`; + }, + }; + }, + }), + ], + providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }], +}) +export class RateLimitModule {} diff --git a/apps/api/src/rate-limit/redis-throttler.storage.ts b/apps/api/src/rate-limit/redis-throttler.storage.ts new file mode 100644 index 0000000..af8b6ca --- /dev/null +++ b/apps/api/src/rate-limit/redis-throttler.storage.ts @@ -0,0 +1,23 @@ +import type { ThrottlerStorage } from '@nestjs/throttler'; +import type { Redis } from 'ioredis'; +import { countInWindow } from './fixed-window'; + +/** + * Keeps the throttler's counts in Redis instead of the process's memory, so + * a limit holds across every API instance and survives a restart. + */ +export class RedisThrottlerStorage implements ThrottlerStorage { + constructor(private readonly redis: Redis) {} + + async increment(key: string, ttl: number, limit: number) { + const { hits, remainingMs } = await countInWindow(this.redis, key, ttl); + const seconds = Math.ceil(remainingMs / 1000); + return { + totalHits: hits, + timeToExpire: seconds, + // Over the limit means waiting for the window to end, no longer. + isBlocked: hits > limit, + timeToBlockExpire: seconds, + }; + } +} diff --git a/apps/api/src/realms/realm-permissions.spec.ts b/apps/api/src/realms/realm-permissions.spec.ts new file mode 100644 index 0000000..e4788f9 --- /dev/null +++ b/apps/api/src/realms/realm-permissions.spec.ts @@ -0,0 +1,46 @@ +import { REALM_PERMISSIONS } from '@repo/contracts'; +import { describe, expect, it } from 'vitest'; +import { permissionsOf, type RealmMembership } from './realm-permissions'; + +const realm = { + id: 'realm-1', + name: 'Coven', + ownerId: 'owner', + createdAt: new Date(), +}; + +function role( + permissions: RealmMembership['roles'][number]['permissions'], +): RealmMembership['roles'][number] { + return { + id: crypto.randomUUID(), + realmId: realm.id, + name: 'Role', + permissions, + isDefault: false, + }; +} + +describe('permissionsOf', () => { + it('gives the owner everything, whatever the roles say', () => { + expect(permissionsOf({ realm, roles: [] }, 'owner')).toEqual([ + ...REALM_PERMISSIONS, + ]); + }); + + it('adds up what the roles of a member allow, each permission once', () => { + const roles = [ + role(['sendMessages', 'createInvites']), + role(['kickMembers', 'sendMessages']), + ]; + expect(permissionsOf({ realm, roles }, 'member')).toEqual([ + 'kickMembers', + 'createInvites', + 'sendMessages', + ]); + }); + + it('allows nothing without roles', () => { + expect(permissionsOf({ realm, roles: [] }, 'member')).toEqual([]); + }); +}); diff --git a/apps/api/src/realms/realm-permissions.ts b/apps/api/src/realms/realm-permissions.ts new file mode 100644 index 0000000..6750fd3 --- /dev/null +++ b/apps/api/src/realms/realm-permissions.ts @@ -0,0 +1,22 @@ +import { REALM_PERMISSIONS, type RealmPermission } from '@repo/contracts'; +import type { RealmRoleRow, RealmRow } from './realms.repository'; + +/** A realm together with the roles that count for one of its members. */ +export interface RealmMembership { + realm: RealmRow; + /** The "Everyone" role and the roles the member was given. */ + roles: RealmRoleRow[]; +} + +/** + * What a member may do: everything for the owner, otherwise whatever any of + * their roles allows. In the order of REALM_PERMISSIONS, each one once. + */ +export function permissionsOf( + membership: RealmMembership, + userId: string, +): RealmPermission[] { + if (membership.realm.ownerId === userId) return [...REALM_PERMISSIONS]; + const granted = new Set(membership.roles.flatMap((role) => role.permissions)); + return REALM_PERMISSIONS.filter((permission) => granted.has(permission)); +} diff --git a/apps/api/src/realms/realms.controller.ts b/apps/api/src/realms/realms.controller.ts new file mode 100644 index 0000000..0256e44 --- /dev/null +++ b/apps/api/src/realms/realms.controller.ts @@ -0,0 +1,276 @@ +import { + Body, + Controller, + Delete, + Get, + HttpCode, + Param, + Patch, + Post, + Put, +} from '@nestjs/common'; +import { + banMemberSchema, + cauldronInputSchema, + conversationIdSchema, + createInviteSchema, + createRealmSchema, + createRoleSchema, + inviteCodeSchema, + realmIdSchema, + roleIdSchema, + setMemberRolesSchema, + updateRealmSchema, + updateRoleSchema, + userIdSchema, + type BanMember, + type CauldronInput, + type CreateInvite, + type CreateRealm, + type CreateRole, + type SetMemberRoles, + type UpdateRealm, + type UpdateRole, +} from '@repo/contracts'; +import { Session, type UserSession } from '@thallesp/nestjs-better-auth'; +import type { Auth } from '../auth/auth'; +import { RealmsService } from './realms.service'; +import { AtMost } from '../rate-limit/at-most'; + +/** + * Realms and what belongs to them. Messages of a cauldron go through the + * conversations routes, with the cauldron's id as the conversation id. + */ +@Controller('realms') +export class RealmsController { + constructor(private readonly realms: RealmsService) {} + + /** The realms the signed-in user is in. */ + @Get() + list(@Session() session: UserSession) { + return this.realms.list(session.user.id); + } + + @Post() + @AtMost(5, { seconds: 60 }) + create( + @Session() session: UserSession, + @Body({ schema: createRealmSchema }) body: CreateRealm, + ) { + return this.realms.create(session.user.id, body.name); + } + + /** A realm with its cauldrons, its roles and what the user may do in it. */ + @Get(':id') + get( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + ) { + return this.realms.get(session.user.id, id); + } + + @Patch(':id') + rename( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + @Body({ schema: updateRealmSchema }) body: UpdateRealm, + ) { + return this.realms.rename(session.user.id, id, body.name); + } + + @Delete(':id') + @HttpCode(204) + delete( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + ) { + return this.realms.delete(session.user.id, id); + } + + @Get(':id/members') + listMembers( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + ) { + return this.realms.listMembers(session.user.id, id); + } + + /** Leaves the realm (your own id) or removes someone from it. */ + @Delete(':id/members/:userId') + @HttpCode(204) + removeMember( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + @Param('userId', { schema: userIdSchema }) userId: string, + ) { + return this.realms.removeMember(session.user.id, id, userId); + } + + /** The people banned from the realm, most recent first. */ + @Get(':id/bans') + listBans( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + ) { + return this.realms.listBans(session.user.id, id); + } + + /** Removes a member and keeps them from joining again. */ + @Put(':id/bans/:userId') + @HttpCode(204) + banMember( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + @Param('userId', { schema: userIdSchema }) userId: string, + @Body({ schema: banMemberSchema }) body: BanMember, + ) { + return this.realms.banMember(session.user.id, id, userId, body.reason); + } + + /** Lifts a ban; the person still needs an invite to come back. */ + @Delete(':id/bans/:userId') + @HttpCode(204) + unbanMember( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + @Param('userId', { schema: userIdSchema }) userId: string, + ) { + return this.realms.unbanMember(session.user.id, id, userId); + } + + /** Sets the roles a member holds; answers with the member as they are now. */ + @Put(':id/members/:userId/roles') + setMemberRoles( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + @Param('userId', { schema: userIdSchema }) userId: string, + @Body({ schema: setMemberRolesSchema }) body: SetMemberRoles, + ) { + return this.realms.setMemberRoles( + session.user.id, + id, + userId, + body.roleIds, + ); + } + + @Post(':id/roles') + createRole( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + @Body({ schema: createRoleSchema }) body: CreateRole, + ) { + return this.realms.createRole(session.user.id, id, body); + } + + @Patch(':id/roles/:roleId') + updateRole( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + @Param('roleId', { schema: roleIdSchema }) roleId: string, + @Body({ schema: updateRoleSchema }) body: UpdateRole, + ) { + return this.realms.updateRole(session.user.id, id, roleId, body); + } + + @Delete(':id/roles/:roleId') + @HttpCode(204) + deleteRole( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + @Param('roleId', { schema: roleIdSchema }) roleId: string, + ) { + return this.realms.deleteRole(session.user.id, id, roleId); + } + + @Post(':id/cauldrons') + createCauldron( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + @Body({ schema: cauldronInputSchema }) body: CauldronInput, + ) { + return this.realms.createCauldron(session.user.id, id, body.name); + } + + @Patch(':id/cauldrons/:cauldronId') + renameCauldron( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + @Param('cauldronId', { schema: conversationIdSchema }) cauldronId: string, + @Body({ schema: cauldronInputSchema }) body: CauldronInput, + ) { + return this.realms.renameCauldron( + session.user.id, + id, + cauldronId, + body.name, + ); + } + + @Delete(':id/cauldrons/:cauldronId') + @HttpCode(204) + deleteCauldron( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + @Param('cauldronId', { schema: conversationIdSchema }) cauldronId: string, + ) { + return this.realms.deleteCauldron(session.user.id, id, cauldronId); + } + + /** Makes an invite link: { expiresInDays, maxUses }, both optional. */ + @Post(':id/invites') + @AtMost(20, { seconds: 60 }) + createInvite( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + @Body({ schema: createInviteSchema }) body: CreateInvite, + ) { + return this.realms.createInvite(session.user.id, id, body); + } + + /** The invites that still work, as far as the user may see them. */ + @Get(':id/invites') + listInvites( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + ) { + return this.realms.listInvites(session.user.id, id); + } + + @Delete(':id/invites/:code') + @HttpCode(204) + revokeInvite( + @Session() session: UserSession, + @Param('id', { schema: realmIdSchema }) id: string, + @Param('code', { schema: inviteCodeSchema }) code: string, + ) { + return this.realms.revokeInvite(session.user.id, id, code); + } +} + +/** What someone holding an invite link does with it. */ +@Controller('invites') +export class InvitesController { + constructor(private readonly realms: RealmsService) {} + + /** Which realm an invite leads to. Limited, so codes can't be guessed at. */ + @Get(':code') + @AtMost(30, { seconds: 60 }) + preview( + @Session() session: UserSession, + @Param('code', { schema: inviteCodeSchema }) code: string, + ) { + return this.realms.previewInvite(session.user.id, code); + } + + /** Joins the realm; answers with it. */ + @Post(':code/accept') + @AtMost(30, { seconds: 60 }) + @HttpCode(200) + accept( + @Session() session: UserSession, + @Param('code', { schema: inviteCodeSchema }) code: string, + ) { + return this.realms.acceptInvite(session.user.id, code); + } +} diff --git a/apps/api/src/realms/realms.module.ts b/apps/api/src/realms/realms.module.ts new file mode 100644 index 0000000..3cef0f7 --- /dev/null +++ b/apps/api/src/realms/realms.module.ts @@ -0,0 +1,16 @@ +import { Module } from '@nestjs/common'; +import { CallsModule } from '../calls/calls.module'; +import { ReadsRepository } from '../conversations/reads.repository'; +import { RealtimeModule } from '../realtime/realtime.module'; +import { InvitesController, RealmsController } from './realms.controller'; +import { RealmsRepository } from './realms.repository'; +import { RealmsService } from './realms.service'; + +@Module({ + imports: [RealtimeModule, CallsModule], + controllers: [RealmsController, InvitesController], + // ReadsRepository has no state; it is listed here rather than importing + // the conversations module for it. + providers: [RealmsService, RealmsRepository, ReadsRepository], +}) +export class RealmsModule {} diff --git a/apps/api/src/realms/realms.repository.spec.ts b/apps/api/src/realms/realms.repository.spec.ts new file mode 100644 index 0000000..3d847c3 --- /dev/null +++ b/apps/api/src/realms/realms.repository.spec.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest'; +import { isInviteUsable } from './realms.repository'; + +describe('isInviteUsable', () => { + const now = new Date('2026-12-02T12:00:00Z'); + const later = new Date('2026-12-03T12:00:00Z'); + const earlier = new Date('2026-12-01T12:00:00Z'); + + it('accepts an invite with no limits', () => { + expect( + isInviteUsable({ expiresAt: null, maxUses: null, uses: 999 }, now), + ).toBe(true); + }); + + it('refuses an invite from its expiry time on', () => { + const invite = { maxUses: null, uses: 0 }; + expect(isInviteUsable({ ...invite, expiresAt: later }, now)).toBe(true); + expect(isInviteUsable({ ...invite, expiresAt: now }, now)).toBe(false); + expect(isInviteUsable({ ...invite, expiresAt: earlier }, now)).toBe(false); + }); + + it('refuses an invite that has been used as often as allowed', () => { + const invite = { expiresAt: later, maxUses: 2 }; + expect(isInviteUsable({ ...invite, uses: 1 }, now)).toBe(true); + expect(isInviteUsable({ ...invite, uses: 2 }, now)).toBe(false); + }); +}); diff --git a/apps/api/src/realms/realms.repository.ts b/apps/api/src/realms/realms.repository.ts new file mode 100644 index 0000000..fe250bf --- /dev/null +++ b/apps/api/src/realms/realms.repository.ts @@ -0,0 +1,490 @@ +import { Injectable } from '@nestjs/common'; +import { InjectDrizzle } from '@nestjs/drizzle'; +import { + DEFAULT_CAULDRON_NAME, + DEFAULT_MEMBER_PERMISSIONS, + DEFAULT_ROLE_NAME, + type RealmPermission, +} from '@repo/contracts'; +import { + and, + asc, + count, + desc, + eq, + gt, + inArray, + isNull, + lt, + or, + sql, +} from 'drizzle-orm'; +import { alias } from 'drizzle-orm/pg-core'; +import type { Database } from '../db/database'; +import { + conversation, + realm, + realmBan, + realmInvite, + realmMember, + realmMemberRole, + realmRole, + user, +} from '../db/schema'; +import type { RealmMembership } from './realm-permissions'; + +export type RealmRow = typeof realm.$inferSelect; +export type RealmRoleRow = typeof realmRole.$inferSelect; +export type RealmInviteRow = typeof realmInvite.$inferSelect; +export interface CauldronRow { + id: string; + name: string | null; +} + +type Transaction = Parameters[0]>[0]; + +const cauldronColumns = { id: conversation.id, name: conversation.name }; + +@Injectable() +export class RealmsRepository { + constructor(@InjectDrizzle() private readonly db: Database) {} + + /** The realms a user is in, in the order they joined them. */ + listForMember(userId: string): Promise { + return this.db + .select({ + id: realm.id, + name: realm.name, + ownerId: realm.ownerId, + createdAt: realm.createdAt, + }) + .from(realm) + .innerJoin(realmMember, eq(realmMember.realmId, realm.id)) + .where(eq(realmMember.userId, userId)) + .orderBy(asc(realmMember.joinedAt), asc(realm.id)); + } + + async listIdsForMember(userId: string): Promise { + const rows = await this.db + .select({ realmId: realmMember.realmId }) + .from(realmMember) + .where(eq(realmMember.userId, userId)); + return rows.map((row) => row.realmId); + } + + /** + * The realm and the roles that count for one member of it. Nothing when + * the realm doesn't exist or the user isn't in it. + */ + async findMembership( + realmId: string, + userId: string, + ): Promise { + const rows = await this.db + .select({ realm }) + .from(realm) + .innerJoin(realmMember, eq(realmMember.realmId, realm.id)) + .where(and(eq(realm.id, realmId), eq(realmMember.userId, userId))); + const found = rows.at(0); + if (!found) return undefined; + + const given = this.db + .select({ roleId: realmMemberRole.roleId }) + .from(realmMemberRole) + .where( + and( + eq(realmMemberRole.realmId, realmId), + eq(realmMemberRole.userId, userId), + ), + ); + const roles = await this.db + .select() + .from(realmRole) + .where( + and( + eq(realmRole.realmId, realmId), + or(eq(realmRole.isDefault, true), inArray(realmRole.id, given)), + ), + ) + .orderBy(asc(realmRole.id)); + return { realm: found.realm, roles }; + } + + /** Oldest first. */ + listCauldrons(realmId: string): Promise { + return this.db + .select(cauldronColumns) + .from(conversation) + .where(eq(conversation.realmId, realmId)) + .orderBy(asc(conversation.id)); + } + + /** The "Everyone" role first, then oldest first. */ + listRoles(realmId: string): Promise { + return this.db + .select() + .from(realmRole) + .where(eq(realmRole.realmId, realmId)) + .orderBy(desc(realmRole.isDefault), asc(realmRole.id)); + } + + async countMembers(realmId: string): Promise { + const [row] = await this.db + .select({ total: count() }) + .from(realmMember) + .where(eq(realmMember.realmId, realmId)); + return row.total; + } + + /** A realm with its owner in it, an "Everyone" role and a first cauldron. */ + create(ownerId: string, name: string): Promise { + return this.db.transaction(async (tx) => { + const [created] = await tx + .insert(realm) + .values({ name, ownerId }) + .returning({ id: realm.id }); + await tx + .insert(realmMember) + .values({ realmId: created.id, userId: ownerId }); + await tx.insert(realmRole).values({ + realmId: created.id, + name: DEFAULT_ROLE_NAME, + permissions: DEFAULT_MEMBER_PERMISSIONS, + isDefault: true, + }); + await tx.insert(conversation).values({ + type: 'cauldron', + realmId: created.id, + name: DEFAULT_CAULDRON_NAME, + }); + return created.id; + }); + } + + async rename(realmId: string, name: string): Promise { + await this.db.update(realm).set({ name }).where(eq(realm.id, realmId)); + } + + /** Takes its cauldrons, their messages, its roles and invites with it. */ + async delete(realmId: string): Promise { + await this.db.delete(realm).where(eq(realm.id, realmId)); + } + + /** Longest-standing first, each with the ids of the roles they were given. */ + listMembers(realmId: string) { + return this.db.query.realmMember.findMany({ + where: { realmId }, + with: { user: true, roles: true }, + orderBy: { joinedAt: 'asc', userId: 'asc' }, + }); + } + + findMember(realmId: string, userId: string) { + return this.db.query.realmMember.findFirst({ + where: { realmId, userId }, + with: { user: true, roles: true }, + }); + } + + /** Answers false when they weren't in it. Their roles go with them. */ + async removeMember(realmId: string, userId: string): Promise { + const removed = await this.db + .delete(realmMember) + .where( + and(eq(realmMember.realmId, realmId), eq(realmMember.userId, userId)), + ) + .returning({ userId: realmMember.userId }); + return removed.length > 0; + } + + async isBanned(realmId: string, userId: string): Promise { + const rows = await this.db + .select({ userId: realmBan.userId }) + .from(realmBan) + .where(and(eq(realmBan.realmId, realmId), eq(realmBan.userId, userId))); + return rows.length > 0; + } + + /** Most recent first, each with the person banned and who banned them. */ + listBans(realmId: string) { + const bannedBy = alias(user, 'banned_by'); + return this.db + .select({ ban: realmBan, user, bannedBy }) + .from(realmBan) + .innerJoin(user, eq(user.id, realmBan.userId)) + .leftJoin(bannedBy, eq(bannedBy.id, realmBan.bannedById)) + .where(eq(realmBan.realmId, realmId)) + .orderBy(desc(realmBan.createdAt), asc(realmBan.userId)); + } + + /** + * Takes a member out of the realm and notes that they may not come back, + * in one step. Answers false when they weren't a member. + */ + ban( + realmId: string, + userId: string, + bannedById: string, + reason: string | null, + ): Promise { + return this.db.transaction(async (tx) => { + const removed = await tx + .delete(realmMember) + .where( + and(eq(realmMember.realmId, realmId), eq(realmMember.userId, userId)), + ) + .returning({ userId: realmMember.userId }); + if (removed.length === 0) return false; + await tx + .insert(realmBan) + .values({ realmId, userId, bannedById, reason }) + .onConflictDoNothing(); + return true; + }); + } + + /** Answers false when there was no ban to lift. */ + async unban(realmId: string, userId: string): Promise { + const removed = await this.db + .delete(realmBan) + .where(and(eq(realmBan.realmId, realmId), eq(realmBan.userId, userId))) + .returning({ userId: realmBan.userId }); + return removed.length > 0; + } + + /** Replaces the roles a member was given with exactly these. */ + setMemberRoles( + realmId: string, + userId: string, + roleIds: string[], + ): Promise { + return this.db.transaction(async (tx) => { + await tx + .delete(realmMemberRole) + .where( + and( + eq(realmMemberRole.realmId, realmId), + eq(realmMemberRole.userId, userId), + ), + ); + if (roleIds.length === 0) return; + await tx + .insert(realmMemberRole) + .values(roleIds.map((roleId) => ({ realmId, userId, roleId }))); + }); + } + + async findRole( + realmId: string, + roleId: string, + ): Promise { + const rows = await this.db + .select() + .from(realmRole) + .where(and(eq(realmRole.realmId, realmId), eq(realmRole.id, roleId))); + return rows.at(0); + } + + /** Answers "full" instead when the realm already has `maxRoles` roles. */ + createRole( + realmId: string, + name: string, + permissions: RealmPermission[], + maxRoles: number, + ): Promise { + return this.db.transaction(async (tx) => { + await lockRealm(tx, realmId); + const [existing] = await tx + .select({ total: count() }) + .from(realmRole) + .where(eq(realmRole.realmId, realmId)); + if (existing.total >= maxRoles) return 'full'; + const [row] = await tx + .insert(realmRole) + .values({ realmId, name, permissions }) + .returning(); + return row; + }); + } + + async updateRole( + roleId: string, + changes: { name?: string; permissions?: RealmPermission[] }, + ): Promise { + const rows = await this.db + .update(realmRole) + .set(changes) + .where(eq(realmRole.id, roleId)) + .returning(); + return rows.at(0); + } + + /** Whoever had the role loses it. */ + async deleteRole(roleId: string): Promise { + await this.db.delete(realmRole).where(eq(realmRole.id, roleId)); + } + + /** Answers "full" instead when the realm already has `maxCauldrons`. */ + createCauldron( + realmId: string, + name: string, + maxCauldrons: number, + ): Promise { + return this.db.transaction(async (tx) => { + await lockRealm(tx, realmId); + const [existing] = await tx + .select({ total: count() }) + .from(conversation) + .where(eq(conversation.realmId, realmId)); + if (existing.total >= maxCauldrons) return 'full'; + const [row] = await tx + .insert(conversation) + .values({ type: 'cauldron', realmId, name }) + .returning(cauldronColumns); + return row; + }); + } + + async renameCauldron( + realmId: string, + cauldronId: string, + name: string, + ): Promise { + const rows = await this.db + .update(conversation) + .set({ name }) + .where( + and(eq(conversation.realmId, realmId), eq(conversation.id, cauldronId)), + ) + .returning(cauldronColumns); + return rows.at(0); + } + + /** Its messages go with it. Answers false when the realm has no such cauldron. */ + async deleteCauldron(realmId: string, cauldronId: string): Promise { + const removed = await this.db + .delete(conversation) + .where( + and(eq(conversation.realmId, realmId), eq(conversation.id, cauldronId)), + ) + .returning({ id: conversation.id }); + return removed.length > 0; + } + + async createInvite( + values: Pick< + RealmInviteRow, + 'code' | 'realmId' | 'createdById' | 'expiresAt' | 'maxUses' + >, + ): Promise { + await this.db.insert(realmInvite).values(values); + } + + /** With its realm and who made it, whether it still works or not. */ + findInvite(code: string) { + return this.db.query.realmInvite.findFirst({ + where: { code }, + with: { realm: true, createdBy: true }, + }); + } + + /** + * A realm's invites that still work, newest first; only those made by + * `createdById` when that is given. + */ + listUsableInvites(realmId: string, now: Date, createdById?: string) { + return this.db + .select({ invite: realmInvite, createdBy: user }) + .from(realmInvite) + .innerJoin(user, eq(user.id, realmInvite.createdById)) + .where( + and( + eq(realmInvite.realmId, realmId), + or(isNull(realmInvite.expiresAt), gt(realmInvite.expiresAt, now)), + or( + isNull(realmInvite.maxUses), + lt(realmInvite.uses, realmInvite.maxUses), + ), + createdById ? eq(realmInvite.createdById, createdById) : undefined, + ), + ) + .orderBy(desc(realmInvite.createdAt), asc(realmInvite.code)); + } + + async deleteInvite(code: string): Promise { + await this.db.delete(realmInvite).where(eq(realmInvite.code, code)); + } + + /** + * Puts the user in the invite's realm and counts the use. Answers + * "member" when they were in it already (whatever state the invite is in), + * "banned" when they may not join, and nothing when the invite doesn't + * exist or no longer works. + */ + acceptInvite( + code: string, + userId: string, + now: Date, + ): Promise< + { realmId: string; outcome: 'joined' | 'member' | 'banned' } | undefined + > { + return this.db.transaction(async (tx) => { + // The lock makes people using one link take turns, so a link good for + // one more use can't let two people in. + const invites = await tx + .select() + .from(realmInvite) + .where(eq(realmInvite.code, code)) + .for('update'); + const invite = invites.at(0); + if (!invite) return undefined; + const { realmId } = invite; + + const memberships = await tx + .select({ userId: realmMember.userId }) + .from(realmMember) + .where( + and(eq(realmMember.realmId, realmId), eq(realmMember.userId, userId)), + ); + if (memberships.length > 0) return { realmId, outcome: 'member' }; + if (!isInviteUsable(invite, now)) return undefined; + const bans = await tx + .select({ userId: realmBan.userId }) + .from(realmBan) + .where(and(eq(realmBan.realmId, realmId), eq(realmBan.userId, userId))); + if (bans.length > 0) return { realmId, outcome: 'banned' }; + + const added = await tx + .insert(realmMember) + .values({ realmId, userId }) + // Two requests from the same person, with two different links. + .onConflictDoNothing() + .returning({ userId: realmMember.userId }); + if (added.length === 0) return { realmId, outcome: 'member' }; + await tx + .update(realmInvite) + .set({ uses: sql`${realmInvite.uses} + 1` }) + .where(eq(realmInvite.code, code)); + return { realmId, outcome: 'joined' }; + }); + } +} + +/** True while an invite has neither run out of time nor of uses. */ +export function isInviteUsable( + invite: Pick, + now: Date, +): boolean { + if (invite.expiresAt && invite.expiresAt <= now) return false; + return invite.maxUses === null || invite.uses < invite.maxUses; +} + +// Makes changes that count a realm's rows take turns, so two requests at +// once can't both fit under a limit. +async function lockRealm(tx: Transaction, realmId: string) { + await tx + .select({ id: realm.id }) + .from(realm) + .where(eq(realm.id, realmId)) + .for('update'); +} diff --git a/apps/api/src/realms/realms.service.ts b/apps/api/src/realms/realms.service.ts new file mode 100644 index 0000000..4c10c8f --- /dev/null +++ b/apps/api/src/realms/realms.service.ts @@ -0,0 +1,604 @@ +import { randomBytes } from 'node:crypto'; +import { + BadRequestException, + ConflictException, + ForbiddenException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import { + hasPermissions, + REALM_MAX_CAULDRONS, + REALM_MAX_ROLES, + type Cauldron, + type CreateInvite, + type CreateRole, + type InvitePreview, + type Realm, + type RealmBan, + type RealmInvite, + type RealmListItem, + type RealmMember, + type RealmPermission, + type RealmRole, + type RealmSummary, + type UpdateRole, +} from '@repo/contracts'; +import { CallsService } from '../calls/calls.service'; +import { ReadsRepository } from '../conversations/reads.repository'; +import { RealtimeService } from '../realtime/realtime.service'; +import { toUserSummary } from '../users/user-summary'; +import type { UserRow } from '../users/users.repository'; +import { permissionsOf, type RealmMembership } from './realm-permissions'; +import { + isInviteUsable, + RealmsRepository, + type CauldronRow, + type RealmInviteRow, + type RealmRoleRow, + type RealmRow, +} from './realms.repository'; + +const DAY_MS = 24 * 60 * 60 * 1000; + +/** A member's place in a realm, worked out once per request. */ +interface Access extends RealmMembership { + userId: string; + isOwner: boolean; + permissions: RealmPermission[]; +} + +type MemberRow = Awaited>[number]; + +@Injectable() +export class RealmsService { + constructor( + private readonly realms: RealmsRepository, + private readonly reads: ReadsRepository, + private readonly calls: CallsService, + private readonly realtime: RealtimeService, + ) {} + + async list(userId: string): Promise { + const [rows, unread] = await Promise.all([ + this.realms.listForMember(userId), + this.reads.realmsWithUnread(userId), + ]); + return rows.map((row) => ({ + ...toSummary(row), + hasUnread: unread.has(row.id), + })); + } + + async get(userId: string, realmId: string): Promise { + return this.toRealm(await this.access(userId, realmId)); + } + + async create(userId: string, name: string): Promise { + const realmId = await this.realms.create(userId, name); + this.realtime.joinRealm(userId, realmId); + // For the creator's other tabs and devices. + this.realtime.emitToUsers([userId], 'realm:changed', realmId, 'details'); + return this.get(userId, realmId); + } + + async rename(userId: string, realmId: string, name: string): Promise { + await this.access(userId, realmId, 'manageRealm'); + await this.realms.rename(realmId, name); + this.announce(realmId, 'details'); + return this.get(userId, realmId); + } + + /** Only the owner may; everything in the realm goes with it. */ + async delete(userId: string, realmId: string): Promise { + const access = await this.access(userId, realmId); + if (!access.isOwner) { + throw new ForbiddenException("Only the realm's owner can delete it."); + } + const cauldrons = await this.realms.listCauldrons(realmId); + await this.realms.delete(realmId); + this.announce(realmId, 'details'); + this.realtime.closeRealm(realmId); + await this.calls.end(cauldrons.map((cauldron) => cauldron.id)); + } + + async listMembers(userId: string, realmId: string): Promise { + await this.access(userId, realmId); + const rows = await this.realms.listMembers(realmId); + return rows.map(toMember); + } + + /** + * Leaving (your own id) is open to everyone but the owner. Removing + * someone else needs "kickMembers" and never reaches the owner or anyone + * who can do more than the person removing them. + */ + async removeMember( + userId: string, + realmId: string, + targetUserId: string, + ): Promise { + const access = await this.access(userId, realmId); + if (targetUserId === userId) { + if (access.isOwner) { + throw new BadRequestException( + "The owner can't leave a realm. Delete it instead.", + ); + } + } else { + this.assertAllowed(access, 'kickMembers'); + await this.assertOutranks(access, realmId, targetUserId); + } + + await this.realms.removeMember(realmId, targetUserId); + await this.afterLeaving(realmId, targetUserId); + } + + /** + * Removes a member for good: no invite lets them back in until the ban + * is lifted. Needs "banMembers", under the same limits as removing. + */ + async banMember( + userId: string, + realmId: string, + targetUserId: string, + reason: string | null, + ): Promise { + const access = await this.access(userId, realmId, 'banMembers'); + if (targetUserId === userId) { + throw new BadRequestException("You can't ban yourself."); + } + await this.assertOutranks(access, realmId, targetUserId); + if (!(await this.realms.ban(realmId, targetUserId, userId, reason))) { + throw new NotFoundException(NOT_A_MEMBER); + } + await this.afterLeaving(realmId, targetUserId); + } + + async unbanMember( + userId: string, + realmId: string, + targetUserId: string, + ): Promise { + await this.access(userId, realmId, 'banMembers'); + if (!(await this.realms.unban(realmId, targetUserId))) { + throw new NotFoundException("That person isn't banned from this realm."); + } + } + + async listBans(userId: string, realmId: string): Promise { + await this.access(userId, realmId, 'banMembers'); + const rows = await this.realms.listBans(realmId); + return rows.map(({ ban, user, bannedBy }) => ({ + user: toUserSummary(user), + bannedBy: bannedBy ? toUserSummary(bannedBy) : null, + reason: ban.reason, + createdAt: ban.createdAt.toISOString(), + })); + } + + /** + * Sets which roles a member holds. Needs "manageRoles", and each role + * given or taken away must allow nothing the person doing it can't do. + */ + async setMemberRoles( + userId: string, + realmId: string, + targetUserId: string, + roleIds: string[], + ): Promise { + const access = await this.access(userId, realmId, 'manageRoles'); + const target = await this.memberAccess(realmId, targetUserId); + if (target.isOwner && !access.isOwner) { + throw new ForbiddenException("The owner's roles can't be changed."); + } + + const roles = await this.realms.listRoles(realmId); + const wanted = new Set(roleIds); + for (const roleId of wanted) { + const role = roles.find((candidate) => candidate.id === roleId); + if (!role) throw new BadRequestException('Unknown role.'); + if (role.isDefault) { + throw new BadRequestException('Everyone has that role already.'); + } + } + const held = new Set( + target.roles.filter((role) => !role.isDefault).map((role) => role.id), + ); + const changed = roles.filter( + (role) => wanted.has(role.id) !== held.has(role.id) && !role.isDefault, + ); + for (const role of changed) { + if (!hasPermissions(access.permissions, role.permissions)) { + throw new ForbiddenException( + `You can't give or take away "${role.name}": it allows more than you can do.`, + ); + } + } + + if (changed.length > 0) { + await this.realms.setMemberRoles(realmId, targetUserId, roleIds); + this.announce(realmId, 'members'); + // What they may do changed, which their realm details carry. + this.realtime.emitToUsers( + [targetUserId], + 'realm:changed', + realmId, + 'details', + ); + } + const member = await this.realms.findMember(realmId, targetUserId); + if (!member) throw new NotFoundException(NOT_A_MEMBER); + return toMember(member); + } + + async createRole( + userId: string, + realmId: string, + { name, permissions }: CreateRole, + ): Promise { + const access = await this.access(userId, realmId, 'manageRoles'); + assertWithinOwn(access, permissions); + const row = await this.realms.createRole( + realmId, + name, + permissions, + REALM_MAX_ROLES, + ); + if (row === 'full') { + throw new ConflictException( + `A realm can have at most ${REALM_MAX_ROLES} roles.`, + ); + } + this.announce(realmId, 'details'); + return toRole(row); + } + + /** + * Changes a role's name or what it allows. A role can only be changed by + * someone who can do everything it allows, before and after the change. + */ + async updateRole( + userId: string, + realmId: string, + roleId: string, + changes: UpdateRole, + ): Promise { + const access = await this.access(userId, realmId, 'manageRoles'); + const role = await this.findRole(realmId, roleId); + if ( + role.isDefault && + changes.name !== undefined && + changes.name !== role.name + ) { + throw new BadRequestException( + `The "${role.name}" role can't be renamed.`, + ); + } + assertWithinOwn(access, role.permissions); + if (changes.permissions) assertWithinOwn(access, changes.permissions); + + const updated = await this.realms.updateRole(roleId, { + ...(changes.name === undefined ? {} : { name: changes.name }), + ...(changes.permissions ? { permissions: changes.permissions } : {}), + }); + if (!updated) throw new NotFoundException('Role not found.'); + // Everyone holding the role may do something else now. + this.announce(realmId, 'details'); + return toRole(updated); + } + + async deleteRole( + userId: string, + realmId: string, + roleId: string, + ): Promise { + const access = await this.access(userId, realmId, 'manageRoles'); + const role = await this.findRole(realmId, roleId); + if (role.isDefault) { + throw new BadRequestException( + `The "${role.name}" role can't be deleted.`, + ); + } + assertWithinOwn(access, role.permissions); + await this.realms.deleteRole(roleId); + this.announce(realmId, 'details'); + this.announce(realmId, 'members'); + } + + async createCauldron( + userId: string, + realmId: string, + name: string, + ): Promise { + await this.access(userId, realmId, 'manageCauldrons'); + const row = await this.realms.createCauldron( + realmId, + name, + REALM_MAX_CAULDRONS, + ); + if (row === 'full') { + throw new ConflictException( + `A realm can have at most ${REALM_MAX_CAULDRONS} cauldrons.`, + ); + } + this.announce(realmId, 'details'); + return toCauldron(row); + } + + async renameCauldron( + userId: string, + realmId: string, + cauldronId: string, + name: string, + ): Promise { + await this.access(userId, realmId, 'manageCauldrons'); + const row = await this.realms.renameCauldron(realmId, cauldronId, name); + if (!row) throw new NotFoundException('Cauldron not found.'); + this.announce(realmId, 'details'); + return toCauldron(row); + } + + /** Its messages are deleted with it. */ + async deleteCauldron( + userId: string, + realmId: string, + cauldronId: string, + ): Promise { + await this.access(userId, realmId, 'manageCauldrons'); + if (!(await this.realms.deleteCauldron(realmId, cauldronId))) { + throw new NotFoundException('Cauldron not found.'); + } + this.announce(realmId, 'details'); + await this.calls.end([cauldronId]); + } + + async createInvite( + userId: string, + realmId: string, + { expiresInDays, maxUses }: CreateInvite, + ): Promise { + await this.access(userId, realmId, 'createInvites'); + // 72 random bits: far too many to guess, short enough to paste. + const code = randomBytes(9).toString('base64url'); + await this.realms.createInvite({ + code, + realmId, + createdById: userId, + expiresAt: + expiresInDays === null + ? null + : new Date(Date.now() + expiresInDays * DAY_MS), + maxUses, + }); + const invite = await this.realms.findInvite(code); + if (!invite) throw new NotFoundException(INVALID_INVITE); + return toInvite(invite, invite.createdBy); + } + + /** + * The invites that still work: all of them for whoever manages the realm, + * their own for anyone else who may make invites. + */ + async listInvites(userId: string, realmId: string): Promise { + const access = await this.access(userId, realmId); + const seesAll = access.permissions.includes('manageRealm'); + if (!seesAll) this.assertAllowed(access, 'createInvites'); + const rows = await this.realms.listUsableInvites( + realmId, + new Date(), + seesAll ? undefined : userId, + ); + return rows.map((row) => toInvite(row.invite, row.createdBy)); + } + + /** Your own invite, or anyone's if you manage the realm. */ + async revokeInvite( + userId: string, + realmId: string, + code: string, + ): Promise { + const access = await this.access(userId, realmId); + const invite = await this.realms.findInvite(code); + if (!invite || invite.realmId !== realmId) { + throw new NotFoundException('Invite not found.'); + } + if (invite.createdById !== userId) { + this.assertAllowed(access, 'manageRealm'); + } + await this.realms.deleteInvite(code); + } + + /** What an invite link leads to, for someone deciding whether to join. */ + async previewInvite(userId: string, code: string): Promise { + const invite = await this.realms.findInvite(code); + if (!invite) throw new NotFoundException(INVALID_INVITE); + const membership = await this.realms.findMembership(invite.realmId, userId); + // A member following an old link is shown their realm, not an error. + if (!membership && !isInviteUsable(invite, new Date())) { + throw new NotFoundException(INVALID_INVITE); + } + return { + code, + realm: { + id: invite.realm.id, + name: invite.realm.name, + memberCount: await this.realms.countMembers(invite.realmId), + }, + isMember: membership !== undefined, + isBanned: + !membership && (await this.realms.isBanned(invite.realmId, userId)), + }; + } + + /** Joins the invite's realm; answers with it either way if already in. */ + async acceptInvite(userId: string, code: string): Promise { + const accepted = await this.realms.acceptInvite(code, userId, new Date()); + if (!accepted) throw new NotFoundException(INVALID_INVITE); + const { realmId, outcome } = accepted; + if (outcome === 'banned') { + throw new ForbiddenException('You were banned from this realm.'); + } + if (outcome === 'joined') { + this.realtime.joinRealm(userId, realmId); + // Their own connections are told directly: they may not be in the + // realm's room yet when the next event goes out. + this.realtime.emitToUsers([userId], 'realm:changed', realmId, 'details'); + this.announce(realmId, 'members'); + } + return this.get(userId, realmId); + } + + /** + * The user's place in a realm. Answers 404 for a realm they aren't in as + * well, so ids can't be probed for existence, and 403 when they are in it + * but lack `needed`. + */ + private async access( + userId: string, + realmId: string, + needed?: RealmPermission, + ): Promise { + const membership = await this.realms.findMembership(realmId, userId); + if (!membership) throw new NotFoundException('Realm not found.'); + const access = toAccess(membership, userId); + if (needed) this.assertAllowed(access, needed); + return access; + } + + /** The place of someone else, who is expected to be in the realm. */ + private async memberAccess(realmId: string, userId: string): Promise { + const membership = await this.realms.findMembership(realmId, userId); + if (!membership) throw new NotFoundException(NOT_A_MEMBER); + return toAccess(membership, userId); + } + + /** + * Checks that the member may put this other member out: never the owner, + * and nobody who can do more than they can. + */ + private async assertOutranks( + access: Access, + realmId: string, + targetUserId: string, + ) { + const target = await this.memberAccess(realmId, targetUserId); + if (target.isOwner) { + throw new ForbiddenException("The realm's owner can't be removed."); + } + if (!hasPermissions(access.permissions, target.permissions)) { + throw new ForbiddenException( + "You can't remove someone who can do more than you here.", + ); + } + } + + /** Tells everyone, the person themself included, that a member is gone. */ + private async afterLeaving(realmId: string, userId: string) { + // Told first, while their connections are still in the realm's room, so + // the realm leaves their list. + this.realtime.emitToUsers([userId], 'realm:changed', realmId, 'details'); + this.realtime.leaveRealm(userId, realmId); + this.announce(realmId, 'members'); + await this.calls.removeFromRealm(realmId, userId); + } + + private assertAllowed(access: Access, needed: RealmPermission) { + if (!access.permissions.includes(needed)) { + throw new ForbiddenException( + "You don't have permission to do that in this realm.", + ); + } + } + + private async findRole( + realmId: string, + roleId: string, + ): Promise { + const role = await this.realms.findRole(realmId, roleId); + if (!role) throw new NotFoundException('Role not found.'); + return role; + } + + private announce(realmId: string, what: 'details' | 'members') { + this.realtime.emitToRealm(realmId, 'realm:changed', realmId, what); + } + + private async toRealm(access: Access): Promise { + const { realm } = access; + const [cauldrons, roles, memberCount, unread] = await Promise.all([ + this.realms.listCauldrons(realm.id), + this.realms.listRoles(realm.id), + this.realms.countMembers(realm.id), + this.reads.countsForCauldrons(access.userId, realm.id), + ]); + return { + ...toSummary(realm), + cauldrons: cauldrons.map((row) => ({ + ...toCauldron(row), + unreadCount: unread.get(row.id) ?? 0, + })), + roles: roles.map(toRole), + memberCount, + permissions: access.permissions, + }; + } +} + +const NOT_A_MEMBER = "That person isn't in this realm."; +const INVALID_INVITE = "This invite isn't valid any more."; + +function toAccess(membership: RealmMembership, userId: string): Access { + return { + ...membership, + userId, + isOwner: membership.realm.ownerId === userId, + permissions: permissionsOf(membership, userId), + }; +} + +// Stops people handing out, through a role, what they can't do themselves. +function assertWithinOwn(access: Access, permissions: RealmPermission[]) { + if (!hasPermissions(access.permissions, permissions)) { + throw new ForbiddenException( + "A role you manage can't allow more than you can do yourself.", + ); + } +} + +function toSummary(row: RealmRow): RealmSummary { + return { id: row.id, name: row.name, ownerId: row.ownerId }; +} + +function toCauldron(row: CauldronRow): Cauldron { + return { id: row.id, name: row.name ?? '' }; +} + +function toRole(row: RealmRoleRow): RealmRole { + return { + id: row.id, + name: row.name, + permissions: row.permissions, + isDefault: row.isDefault, + }; +} + +function toMember(row: MemberRow): RealmMember { + return { + user: toUserSummary(row.user), + roleIds: row.roles.map((role) => role.roleId), + joinedAt: row.joinedAt.toISOString(), + }; +} + +function toInvite(row: RealmInviteRow, createdBy: UserRow): RealmInvite { + return { + code: row.code, + realmId: row.realmId, + createdBy: toUserSummary(createdBy), + createdAt: row.createdAt.toISOString(), + expiresAt: row.expiresAt?.toISOString() ?? null, + maxUses: row.maxUses, + uses: row.uses, + }; +} diff --git a/apps/api/src/realtime/realtime-gateway.module.ts b/apps/api/src/realtime/realtime-gateway.module.ts new file mode 100644 index 0000000..a66a209 --- /dev/null +++ b/apps/api/src/realtime/realtime-gateway.module.ts @@ -0,0 +1,17 @@ +import { Module } from '@nestjs/common'; +import { RealmsRepository } from '../realms/realms.repository'; +import { RealtimeGateway } from './realtime.gateway'; +import { RealtimeModule } from './realtime.module'; + +/** + * Kept apart from RealtimeModule: the gateway needs the auth service, and the + * auth setup needs RealtimeService (to close sockets on sign-out), which one + * module holding both would turn into a cycle. + */ +@Module({ + imports: [RealtimeModule], + // RealmsRepository is listed here rather than importing RealmsModule: it + // has no state, and the gateway only asks it which realms a user is in. + providers: [RealtimeGateway, RealmsRepository], +}) +export class RealtimeGatewayModule {} diff --git a/apps/api/src/realtime/realtime.gateway.ts b/apps/api/src/realtime/realtime.gateway.ts new file mode 100644 index 0000000..aa8a180 --- /dev/null +++ b/apps/api/src/realtime/realtime.gateway.ts @@ -0,0 +1,101 @@ +import { Logger } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { WebSocketGateway, type OnGatewayInit } from '@nestjs/websockets'; +import { AuthService } from '@thallesp/nestjs-better-auth'; +import { fromNodeHeaders } from 'better-auth/node'; +import type { Auth } from '../auth/auth'; +import type { Env } from '../config/env'; +import { RealmsRepository } from '../realms/realms.repository'; +import { + RealtimeService, + realmRoom, + sessionRoom, + userRoom, + type RealtimeServer, + type RealtimeSocket, +} from './realtime.service'; + +// setTimeout can't wait longer than this (about 24.8 days). +const MAX_TIMER_MS = 2 ** 31 - 1; + +/** + * The Socket.IO endpoint, on the same port as the HTTP API. Clients only + * listen: every change goes through an HTTP route, which then pushes events + * through RealtimeService. + * + * WebSocket transport only, so several API instances work behind a load + * balancer without sticky sessions. + */ +@WebSocketGateway({ + transports: ['websocket'], + // Clients have nothing to say, so nothing long is read from them. + maxHttpBufferSize: 16 * 1024, +}) +export class RealtimeGateway implements OnGatewayInit { + private readonly logger = new Logger(RealtimeGateway.name); + + constructor( + private readonly auth: AuthService, + private readonly config: ConfigService, + private readonly realtime: RealtimeService, + private readonly realms: RealmsRepository, + ) {} + + afterInit(server: RealtimeServer) { + // Middleware, not handleConnection(): it runs before the connection is + // accepted, so a refused client never becomes a connected socket. + server.use((socket, next) => { + this.authenticate(socket).then( + () => next(), + (error: unknown) => { + // A refusal is routine; anything else (database down) is not. + if (!(error instanceof UnauthorizedSocketError)) { + this.logger.error('Could not check a socket session', error); + } + next(new Error('Unauthorized')); + }, + ); + }); + this.realtime.attach(server); + } + + private async authenticate(socket: RealtimeSocket) { + // Browsers always send Origin, and CORS doesn't cover WebSockets, so + // another site could otherwise open a socket with the visitor's cookie. + const { origin } = socket.handshake.headers; + const trustedOrigins = this.config.get('TRUSTED_ORIGINS', { infer: true }); + if (origin && !trustedOrigins.includes(origin)) { + throw new UnauthorizedSocketError(); + } + + const session = await this.auth.api.getSession({ + headers: fromNodeHeaders(socket.handshake.headers), + }); + if (!session) throw new UnauthorizedSocketError(); + + socket.data.userId = session.user.id; + // The user's own room first: joining or leaving a realm from here on + // moves this socket along with the user's others. + await socket.join([ + userRoom(session.user.id), + sessionRoom(session.session.id), + ]); + const realmIds = await this.realms.listIdsForMember(session.user.id); + await socket.join(realmIds.map(realmRoom)); + + // Signing out closes the socket through the session room; this covers a + // session that simply runs out while the socket is open. + const msUntilExpiry = session.session.expiresAt.getTime() - Date.now(); + const timer = setTimeout( + () => socket.disconnect(true), + Math.min(Math.max(msUntilExpiry, 0), MAX_TIMER_MS), + ); + socket.once('disconnect', () => clearTimeout(timer)); + } +} + +class UnauthorizedSocketError extends Error { + constructor() { + super('Unauthorized'); + } +} diff --git a/apps/api/src/realtime/realtime.module.ts b/apps/api/src/realtime/realtime.module.ts new file mode 100644 index 0000000..9fcccc1 --- /dev/null +++ b/apps/api/src/realtime/realtime.module.ts @@ -0,0 +1,8 @@ +import { Module } from '@nestjs/common'; +import { RealtimeService } from './realtime.service'; + +@Module({ + providers: [RealtimeService], + exports: [RealtimeService], +}) +export class RealtimeModule {} diff --git a/apps/api/src/realtime/realtime.service.ts b/apps/api/src/realtime/realtime.service.ts new file mode 100644 index 0000000..387dd57 --- /dev/null +++ b/apps/api/src/realtime/realtime.service.ts @@ -0,0 +1,85 @@ +import { Injectable } from '@nestjs/common'; +import type { + ClientToServerEvents, + ServerToClientEvents, +} from '@repo/contracts'; +import type { Server, Socket } from 'socket.io'; + +/** What the gateway remembers about a connection. */ +export interface SocketData { + userId: string; +} + +export type RealtimeServer = Server< + ClientToServerEvents, + ServerToClientEvents, + Record, + SocketData +>; +export type RealtimeSocket = Socket< + ClientToServerEvents, + ServerToClientEvents, + Record, + SocketData +>; + +/** Every connection of a user joins this room, whatever the device or tab. */ +export const userRoom = (userId: string) => `user:${userId}`; +/** Connections opened with one sign-in; emptied when that session ends. */ +export const sessionRoom = (sessionId: string) => `session:${sessionId}`; + +/** Every connection of every member of a realm. */ +export const realmRoom = (realmId: string) => `realm:${realmId}`; + +/** + * How the rest of the API pushes events to connected clients. It has no + * dependencies of its own, so any module can import RealtimeModule. + */ +@Injectable() +export class RealtimeService { + private server: RealtimeServer | undefined; + + /** Called by the gateway once the socket server exists. */ + attach(server: RealtimeServer) { + this.server = server; + } + + /** Sends an event to every connection of the given users. */ + emitToUsers( + userIds: string[], + event: Event, + ...args: Parameters + ) { + if (userIds.length === 0) return; + this.server?.to(userIds.map(userRoom)).emit(event, ...args); + } + + /** Sends an event to every connection of every member of a realm. */ + emitToRealm( + realmId: string, + event: Event, + ...args: Parameters + ) { + this.server?.to(realmRoom(realmId)).emit(event, ...args); + } + + /** Starts sending a realm's events to someone who just joined it. */ + joinRealm(userId: string, realmId: string) { + this.server?.in(userRoom(userId)).socketsJoin(realmRoom(realmId)); + } + + /** Stops sending a realm's events to someone who left or was removed. */ + leaveRealm(userId: string, realmId: string) { + this.server?.in(userRoom(userId)).socketsLeave(realmRoom(realmId)); + } + + /** Empties the room of a realm that was deleted. */ + closeRealm(realmId: string) { + this.server?.in(realmRoom(realmId)).socketsLeave(realmRoom(realmId)); + } + + /** Closes the connections that were opened with a session that has ended. */ + disconnectSession(sessionId: string) { + this.server?.in(sessionRoom(sessionId)).disconnectSockets(true); + } +} diff --git a/apps/api/src/realtime/redis-io.adapter.ts b/apps/api/src/realtime/redis-io.adapter.ts new file mode 100644 index 0000000..8962925 --- /dev/null +++ b/apps/api/src/realtime/redis-io.adapter.ts @@ -0,0 +1,28 @@ +import type { INestApplicationContext } from '@nestjs/common'; +import { IoAdapter } from '@nestjs/platform-socket.io'; +import { createAdapter } from '@socket.io/redis-adapter'; +import type { Redis } from 'ioredis'; +import type { Server, ServerOptions } from 'socket.io'; + +/** + * Relays Socket.IO events through Redis, so an event emitted on one API + * instance reaches the clients connected to the others. + */ +export class RedisIoAdapter extends IoAdapter { + constructor( + app: INestApplicationContext, + private readonly publisher: Redis, + private readonly subscriber: Redis, + ) { + super(app); + } + + override createIOServer( + port: number | undefined, + options?: ServerOptions, + ): Server { + const server = super.createIOServer(port, options); + server.adapter(createAdapter(this.publisher, this.subscriber)); + return server; + } +} diff --git a/apps/api/src/redis/redis.module.ts b/apps/api/src/redis/redis.module.ts new file mode 100644 index 0000000..49c5df1 --- /dev/null +++ b/apps/api/src/redis/redis.module.ts @@ -0,0 +1,74 @@ +import { + Inject, + Logger, + Module, + type OnApplicationShutdown, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { Redis } from 'ioredis'; +import type { Env } from '../config/env'; + +/** Injection token: `@Inject(REDIS) private readonly redis: Redis`. */ +export const REDIS = Symbol('REDIS'); +/** + * A second connection for subscribing: a Redis connection that listens for + * published messages can't run other commands. Used by the socket adapter. + */ +export const REDIS_SUBSCRIBER = Symbol('REDIS_SUBSCRIBER'); + +@Module({ + providers: [ + { + provide: REDIS, + inject: [ConfigService], + useFactory: (config: ConfigService) => { + const redis = new Redis( + config.getOrThrow('REDIS_URL', { infer: true }), + ); + logErrors(redis); + return redis; + }, + }, + { + provide: REDIS_SUBSCRIBER, + inject: [REDIS], + useFactory: (redis: Redis) => { + const subscriber = redis.duplicate(); + logErrors(subscriber); + return subscriber; + }, + }, + ], + exports: [REDIS, REDIS_SUBSCRIBER], +}) +export class RedisModule implements OnApplicationShutdown { + constructor( + @Inject(REDIS) private readonly redis: Redis, + @Inject(REDIS_SUBSCRIBER) private readonly subscriber: Redis, + ) {} + + async onApplicationShutdown() { + await Promise.all([close(this.redis), close(this.subscriber)]); + } +} + +const logger = new Logger('Redis'); + +// Without a listener ioredis prints "Unhandled error event" on every failed +// reconnect; it keeps retrying on its own either way. +function logErrors(redis: Redis) { + redis.on('error', (error) => logger.error(error.message)); +} + +async function close(redis: Redis) { + // From here on an error is the connection going away, as asked: one that + // is dropped while still being set up reports a failed write. + redis.removeAllListeners('error'); + redis.on('error', () => undefined); + // quit() waits for the server's reply, which never comes if it is down. + if (redis.status === 'ready') { + await redis.quit(); + } else { + redis.disconnect(); + } +} diff --git a/apps/api/src/setup.ts b/apps/api/src/setup.ts new file mode 100644 index 0000000..3845c5f --- /dev/null +++ b/apps/api/src/setup.ts @@ -0,0 +1,52 @@ +import type { INestApplication } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import type { Express, NextFunction, Request, Response } from 'express'; +import helmet from 'helmet'; +import { CLIENT_ADDRESS_HEADER } from './auth/auth'; +import type { Env } from './config/env'; + +/** + * What every request passes before any route: who is asking, which headers + * go back, which sites may call. Shared by main.ts and the e2e tests, so + * tests run against the app as it is deployed. Call it before the app + * starts: it has to come ahead of the middleware the modules add. + */ +export function setUpHttp(app: INestApplication) { + const config = app.get>(ConfigService); + const express: Express = app.getHttpAdapter().getInstance(); + + // Behind a reverse proxy every request arrives from the proxy's address; + // this many hops of X-Forwarded-For are believed to find the caller's. + express.set('trust proxy', config.getOrThrow('TRUST_PROXY', { infer: true })); + // Better Auth sees headers only. It is handed the address worked out + // above, in place of whatever the caller put in this header. + app.use((req: Request, _res: Response, next: NextFunction) => { + req.headers[CLIENT_ADDRESS_HEADER] = req.ip ?? ''; + next(); + }); + + express.disable('x-powered-by'); + app.use( + helmet({ + // Nothing here is a page. If a browser is talked into showing a + // response as one, an uploaded file say, it gets to run nothing. + contentSecurityPolicy: { + useDefaults: false, + directives: { + defaultSrc: ["'none'"], + frameAncestors: ["'none'"], + sandbox: [], + }, + }, + // The web app shows uploaded pictures from its own origin, which is + // another one than the API's but the same site; other sites may not. + crossOriginResourcePolicy: { policy: 'same-site' }, + }), + ); + + // The web app runs on another origin and sends the session cookie. + app.enableCors({ + origin: config.getOrThrow('TRUSTED_ORIGINS', { infer: true }), + credentials: true, + }); +} diff --git a/apps/api/src/users/user-summary.ts b/apps/api/src/users/user-summary.ts new file mode 100644 index 0000000..ef415b0 --- /dev/null +++ b/apps/api/src/users/user-summary.ts @@ -0,0 +1,17 @@ +import type { UserSummary } from '@repo/contracts'; +import type { user } from '../db/schema'; + +type SummaryRow = Pick< + typeof user.$inferSelect, + 'id' | 'username' | 'name' | 'image' +>; + +/** The few fields of a user that other people get to see in lists. */ +export function toUserSummary(row: SummaryRow): UserSummary { + return { + id: row.id, + username: row.username, + name: row.name, + image: row.image, + }; +} diff --git a/apps/api/src/users/users.controller.ts b/apps/api/src/users/users.controller.ts new file mode 100644 index 0000000..af5c2ca --- /dev/null +++ b/apps/api/src/users/users.controller.ts @@ -0,0 +1,37 @@ +import { Body, Controller, Get, Param, Patch } from '@nestjs/common'; +import { + updateProfileSchema, + usernameSchema, + type UpdateProfile, +} from '@repo/contracts'; +import { Session, type UserSession } from '@thallesp/nestjs-better-auth'; +import type { Auth } from '../auth/auth'; +import { UsersService } from './users.service'; +import { AtMost } from '../rate-limit/at-most'; + +@Controller('users') +export class UsersController { + constructor(private readonly users: UsersService) {} + + /** The signed-in user's own profile; 401 without a session. */ + @Get('me') + getMe(@Session() session: UserSession) { + return this.users.getOwnProfile(session.user.id); + } + + @Patch('me') + updateMe( + @Session() session: UserSession, + @Body({ schema: updateProfileSchema }) body: UpdateProfile, + ) { + return this.users.updateOwnProfile(session.user.id, body); + } + + @Get(':username') + @AtMost(60, { seconds: 60 }) + getByUsername( + @Param('username', { schema: usernameSchema }) username: string, + ) { + return this.users.getPublicProfile(username); + } +} diff --git a/apps/api/src/users/users.module.ts b/apps/api/src/users/users.module.ts new file mode 100644 index 0000000..a572fd6 --- /dev/null +++ b/apps/api/src/users/users.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { UsersController } from './users.controller'; +import { UsersRepository } from './users.repository'; +import { UsersService } from './users.service'; + +@Module({ + controllers: [UsersController], + providers: [UsersService, UsersRepository], +}) +export class UsersModule {} diff --git a/apps/api/src/users/users.repository.ts b/apps/api/src/users/users.repository.ts new file mode 100644 index 0000000..45c203b --- /dev/null +++ b/apps/api/src/users/users.repository.ts @@ -0,0 +1,47 @@ +import { Injectable } from '@nestjs/common'; +import { InjectDrizzle } from '@nestjs/drizzle'; +import { eq, inArray } from 'drizzle-orm'; +import type { Database } from '../db/database'; +import { user } from '../db/schema'; + +export type UserRow = typeof user.$inferSelect; +export type UserChanges = Partial>; + +@Injectable() +export class UsersRepository { + constructor(@InjectDrizzle() private readonly db: Database) {} + + findById(id: string): Promise { + return this.db.query.user.findFirst({ where: { id } }); + } + + /** In no particular order; ids that belong to no one are left out. */ + async findByIds(ids: string[]): Promise { + if (ids.length === 0) return []; + return this.db.select().from(user).where(inArray(user.id, ids)); + } + + findByUsername(username: string): Promise { + return this.db.query.user.findFirst({ where: { username } }); + } + + async update(id: string, changes: UserChanges): Promise { + const [row] = await this.db + .update(user) + .set(changes) + .where(eq(user.id, id)) + .returning(); + return row; + } +} + +/** True when a write broke a unique constraint (Postgres error 23505). */ +export function isUniqueViolation(error: unknown): boolean { + const cause = error instanceof Error ? (error.cause ?? error) : error; + return ( + typeof cause === 'object' && + cause !== null && + 'code' in cause && + cause.code === '23505' + ); +} diff --git a/apps/api/src/users/users.service.ts b/apps/api/src/users/users.service.ts new file mode 100644 index 0000000..57a21c9 --- /dev/null +++ b/apps/api/src/users/users.service.ts @@ -0,0 +1,68 @@ +import { + ConflictException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import type { OwnProfile, PublicProfile, UpdateProfile } from '@repo/contracts'; +import { + isUniqueViolation, + UsersRepository, + type UserRow, +} from './users.repository'; + +@Injectable() +export class UsersService { + constructor(private readonly users: UsersRepository) {} + + async getOwnProfile(userId: string): Promise { + const row = await this.users.findById(userId); + if (!row) throw new NotFoundException('User not found.'); + return toOwnProfile(row); + } + + async getPublicProfile(username: string): Promise { + const row = await this.users.findByUsername(username); + if (!row?.username) throw new NotFoundException('User not found.'); + return toPublicProfile(row, row.username); + } + + async updateOwnProfile( + userId: string, + changes: UpdateProfile, + ): Promise { + if (Object.keys(changes).length === 0) return this.getOwnProfile(userId); + + let row: UserRow | undefined; + try { + row = await this.users.update(userId, changes); + } catch (error) { + // The only unique column a profile update can touch is the username. + if (isUniqueViolation(error)) { + throw new ConflictException('Username is already taken.'); + } + throw error; + } + if (!row) throw new NotFoundException('User not found.'); + return toOwnProfile(row); + } +} + +// Rows carry more than a profile shows (timestamps, verification state), so +// every response is built field by field. +function sharedFields(row: UserRow) { + return { + id: row.id, + name: row.name, + bio: row.bio, + image: row.image, + createdAt: row.createdAt.toISOString(), + }; +} + +function toPublicProfile(row: UserRow, username: string): PublicProfile { + return { ...sharedFields(row), username }; +} + +function toOwnProfile(row: UserRow): OwnProfile { + return { ...sharedFields(row), username: row.username, email: row.email }; +} diff --git a/apps/api/test/app.e2e-spec.ts b/apps/api/test/app.e2e-spec.ts index 6c3385d..74de6aa 100644 --- a/apps/api/test/app.e2e-spec.ts +++ b/apps/api/test/app.e2e-spec.ts @@ -23,8 +23,21 @@ describe('AppController (e2e)', () => { .expect('Hello World!'); }); - it('/me (GET) requires a session', () => { - return request(app.getHttpServer()).get('/me').expect(401); + it('/health (GET)', () => { + return request(app.getHttpServer()) + .get('/health') + .expect(200) + .expect({ status: 'ok' }); + }); + + it('/ready (GET) reports the database and Redis', async () => { + const response = await request(app.getHttpServer()) + .get('/ready') + .expect(200); + expect(response.body.info).toMatchObject({ + database: { status: 'up' }, + redis: { status: 'up' }, + }); }); afterEach(async () => { diff --git a/apps/api/test/calls.e2e-spec.ts b/apps/api/test/calls.e2e-spec.ts new file mode 100644 index 0000000..51b6ce6 --- /dev/null +++ b/apps/api/test/calls.e2e-spec.ts @@ -0,0 +1,456 @@ +import { createHash, randomUUID } from 'node:crypto'; +import { ConfigService } from '@nestjs/config'; +import type { + Call, + CallAccess, + CallsOverview, + Conversation, + Realm, +} from '@repo/contracts'; +import { AccessToken, TokenVerifier } from 'livekit-server-sdk'; +import request from 'supertest'; +import { CallRooms } from '../src/calls/call-rooms'; +import { CallsStore } from '../src/calls/calls.store'; +import type { Env } from '../src/config/env'; +import { + befriend, + createTestApp, + listen, + nextEvent, + TestAccounts, + TestSockets, + type ClientSocket, + type TestApp, + type TestUser, +} from './helpers'; + +/** + * Stands in for the media server: who is in which room is whatever the + * test says, the way browsers joining and leaving would change it. + */ +class FakeCallRooms implements Pick< + CallRooms, + 'list' | 'participants' | 'remove' | 'close' +> { + private readonly rooms = new Map(); + + join(room: string, identity: string) { + this.rooms.set(room, [...(this.rooms.get(room) ?? []), identity]); + } + + leave(room: string, identity: string) { + const left = (this.rooms.get(room) ?? []).filter((id) => id !== identity); + if (left.length > 0) this.rooms.set(room, left); + else this.rooms.delete(room); + } + + list() { + return Promise.resolve([...this.rooms.keys()]); + } + + participants(room: string) { + return Promise.resolve(this.rooms.get(room) ?? []); + } + + remove(room: string, identity: string) { + this.leave(room, identity); + return Promise.resolve(); + } + + close(room: string) { + this.rooms.delete(room); + return Promise.resolve(); + } +} + +/** How a report is signed, when not the way the media server would. */ +interface Signing { + secret?: string; + /** Sign this instead of the body that is sent. */ + body?: string; + /** The answer to expect; 200 unless said. */ + status?: number; +} + +describe('Calls (e2e)', () => { + let app: TestApp; + let accounts: TestAccounts; + let sockets: TestSockets; + const rooms = new FakeCallRooms(); + let apiKey: string; + let apiSecret: string; + // Alice is friends with Bob and Carol, who are friends too. Dave is + // nobody's friend but joins Alice's realm. + let alice: TestUser; + let bob: TestUser; + let carol: TestUser; + let dave: TestUser; + let aliceSocket: ClientSocket; + let bobSocket: ClientSocket; + let carolSocket: ClientSocket; + let daveSocket: ClientSocket; + /** Alice and Bob. */ + let direct: Conversation; + /** Alice (owner), Bob and Carol. */ + let group: Conversation; + /** Alice's, with Dave in it. */ + let realm: Realm; + let cauldronId: string; + + async function callsOf(account: TestUser): Promise { + const overview: CallsOverview = ( + await account.agent.get('/calls').expect(200) + ).body; + expect(overview.enabled).toBe(true); + return overview.calls; + } + + const idsIn = (call: Call | undefined) => + call?.participants.map((participant) => participant.id); + + /** + * Sends what the media server would, signed the way it signs, and checks + * how the API answers. + */ + async function report( + event: string, + room: string, + { status = 200, ...sign }: Signing = {}, + ) { + const body = JSON.stringify({ + event, + room: { name: room }, + id: randomUUID(), + }); + const token = new AccessToken(apiKey, sign.secret ?? apiSecret); + token.sha256 = createHash('sha256') + .update(sign.body ?? body) + .digest('base64'); + return request(app.getHttpServer()) + .post('/livekit/webhook') + .set('Content-Type', 'application/webhook+json') + .set('Authorization', await token.toJwt()) + .send(body) + .expect(status); + } + + /** Someone's browser connects to a call, and the media server says so. */ + async function joins(account: TestUser, conversationId: string) { + rooms.join(conversationId, account.id); + await report('participant_joined', conversationId); + } + + async function leaves(account: TestUser, conversationId: string) { + rooms.leave(conversationId, account.id); + await report('participant_left', conversationId); + } + + beforeAll(async () => { + app = await createTestApp((builder) => + builder.overrideProvider(CallRooms).useValue(rooms), + ); + const config = app.get>(ConfigService); + apiKey = config.getOrThrow('LIVEKIT_API_KEY', { infer: true }); + apiSecret = config.getOrThrow('LIVEKIT_API_SECRET', { infer: true }); + sockets = new TestSockets(await listen(app)); + accounts = new TestAccounts(app, '@calls-e2e.test'); + await accounts.cleanup(); + [alice, bob, carol, dave] = await Promise.all( + ['Alice', 'Bob', 'Carol', 'Dave'].map((name) => accounts.signUp(name)), + ); + await befriend(alice, bob); + await befriend(alice, carol); + await befriend(bob, carol); + direct = ( + await alice.agent + .post('/conversations/direct') + .send({ userId: bob.id }) + .expect(200) + ).body; + group = ( + await alice.agent + .post('/conversations/group') + .send({ memberIds: [bob.id, carol.id] }) + .expect(201) + ).body; + realm = (await alice.agent.post('/realms').send({ name: 'Calls' })).body; + cauldronId = realm.cauldrons[0].id; + const invite = ( + await alice.agent.post(`/realms/${realm.id}/invites`).send({}).expect(201) + ).body; + await dave.agent.post(`/invites/${invite.code}/accept`).expect(200); + [aliceSocket, bobSocket, carolSocket, daveSocket] = await Promise.all( + [alice, bob, carol, dave].map((account) => sockets.connectAs(account)), + ); + }); + + afterAll(async () => { + sockets.closeAll(); + // Whatever a failed test left behind; the store is shared with the + // API in development. + const store = app.get(CallsStore); + await Promise.all( + [direct.id, group.id, cauldronId].map((id) => store.delete(id)), + ); + await accounts.cleanup(); + await app.close(); + }); + + describe('joining', () => { + it('hands out a token for this user and this call alone', async () => { + const access: CallAccess = ( + await alice.agent.post(`/conversations/${direct.id}/call`).expect(200) + ).body; + expect(access.url).toBe('ws://livekit.invalid'); + const claims = await new TokenVerifier(apiKey, apiSecret).verify( + access.token, + ); + expect(claims.sub).toBe(alice.id); + expect(claims.name).toBe('Alice'); + expect(claims.video).toMatchObject({ + room: direct.id, + roomJoin: true, + canPublish: true, + canSubscribe: true, + }); + expect(claims.video?.roomAdmin).toBeUndefined(); + // Good for minutes, not hours. + const lifetime = (claims.exp ?? 0) - Date.now() / 1000; + expect(lifetime).toBeGreaterThan(60); + expect(lifetime).toBeLessThanOrEqual(5 * 60); + }); + + it('lets in the members of a group and of a realm', async () => { + await carol.agent.post(`/conversations/${group.id}/call`).expect(200); + await dave.agent.post(`/conversations/${cauldronId}/call`).expect(200); + }); + + it("answers 404 for a place the user can't read", async () => { + await carol.agent.post(`/conversations/${direct.id}/call`).expect(404); + await dave.agent.post(`/conversations/${group.id}/call`).expect(404); + await bob.agent.post(`/conversations/${cauldronId}/call`).expect(404); + await alice.agent.post(`/conversations/${randomUUID()}/call`).expect(404); + await alice.agent.post('/conversations/nope/call').expect(400); + }); + + it('asks for a session', async () => { + await request(app.getHttpServer()) + .post(`/conversations/${direct.id}/call`) + .expect(401); + await request(app.getHttpServer()).get('/calls').expect(401); + }); + + it('takes the permission to post, in a realm', async () => { + const everyone = realm.roles.find((role) => role.isDefault); + const role = `/realms/${realm.id}/roles/${everyone?.id}`; + await alice.agent + .patch(role) + .send({ permissions: ['createInvites'] }) + .expect(200); + await dave.agent.post(`/conversations/${cauldronId}/call`).expect(403); + // The owner may do everything. + await alice.agent.post(`/conversations/${cauldronId}/call`).expect(200); + await alice.agent + .patch(role) + .send({ permissions: ['createInvites', 'sendMessages'] }) + .expect(200); + await dave.agent.post(`/conversations/${cauldronId}/call`).expect(200); + }); + }); + + describe('reports from the media server', () => { + it('refuses what the media server did not sign', async () => { + const unsigned = () => + request(app.getHttpServer()) + .post('/livekit/webhook') + .set('Content-Type', 'application/webhook+json'); + const body = JSON.stringify({ + event: 'participant_joined', + room: { name: direct.id }, + }); + rooms.join(direct.id, alice.id); + + await unsigned().send(body).expect(401); + await unsigned().set('Authorization', 'nonsense').send(body).expect(401); + await report('participant_joined', direct.id, { + secret: 'someone-elses-secret-0123456789-0123456789', + status: 401, + }); + // Signed, but for a different body. + await report('participant_joined', direct.id, { + body: '{}', + status: 401, + }); + + expect(await callsOf(alice)).toEqual([]); + rooms.leave(direct.id, alice.id); + }); + + it('takes no notice of rooms that are not calls of this app', async () => { + rooms.join('some-other-room', 'someone'); + await report('participant_joined', 'some-other-room'); + rooms.leave('some-other-room', 'someone'); + // A well-formed id of nothing: nobody to tell, so the room is closed. + const nothing = randomUUID(); + rooms.join(nothing, alice.id); + await report('participant_joined', nothing); + expect(await rooms.participants(nothing)).toEqual([]); + expect(await callsOf(alice)).toEqual([]); + }); + }); + + describe('a call in a direct chat', () => { + let startedAt: string; + + it('starts when the first person joins, and both are told', async () => { + const forAlice = nextEvent(aliceSocket, 'call:changed'); + const forBob = nextEvent(bobSocket, 'call:changed'); + await joins(alice, direct.id); + + const call = await forBob; + expect(call).toEqual({ + conversationId: direct.id, + realmId: null, + participants: [ + { + id: alice.id, + name: 'Alice', + username: alice.username, + image: null, + }, + ], + startedAt: expect.any(String), + }); + expect(await forAlice).toEqual(call); + startedAt = call.startedAt; + + expect(await callsOf(alice)).toEqual([call]); + expect(await callsOf(bob)).toEqual([call]); + // Nobody else hears of it. + expect(await callsOf(carol)).toEqual([]); + }); + + it('lists people in the order they joined', async () => { + const forAlice = nextEvent(aliceSocket, 'call:changed'); + await joins(bob, direct.id); + const call = await forAlice; + expect(idsIn(call)).toEqual([alice.id, bob.id]); + expect(call.startedAt).toBe(startedAt); + }); + + it('says nothing when a report changes nothing', async () => { + let events = 0; + const count = () => (events += 1); + aliceSocket.on('call:changed', count); + await report('participant_joined', direct.id); + await report('track_published', direct.id); + // An event that was sent would have arrived before this answer. + await callsOf(alice); + aliceSocket.off('call:changed', count); + expect(events).toBe(0); + }); + + it('is over when the last person leaves', async () => { + const afterAlice = nextEvent(bobSocket, 'call:changed'); + await leaves(alice, direct.id); + expect(idsIn(await afterAlice)).toEqual([bob.id]); + + const afterBob = nextEvent(aliceSocket, 'call:changed'); + await leaves(bob, direct.id); + expect(await afterBob).toEqual({ + conversationId: direct.id, + realmId: null, + participants: [], + startedAt, + }); + expect(await callsOf(alice)).toEqual([]); + }); + }); + + describe('a call in a group', () => { + it('reaches every member', async () => { + const forCarol = nextEvent(carolSocket, 'call:changed'); + await joins(alice, group.id); + await joins(bob, group.id); + expect((await forCarol).conversationId).toBe(group.id); + expect(idsIn((await callsOf(carol)).at(0))).toEqual([alice.id, bob.id]); + expect(await callsOf(dave)).toEqual([]); + }); + + it('drops someone who is removed from the group', async () => { + const forAlice = nextEvent(aliceSocket, 'call:changed'); + await alice.agent + .delete(`/conversations/${group.id}/members/${bob.id}`) + .expect(204); + expect(await rooms.participants(group.id)).toEqual([alice.id]); + expect(idsIn(await forAlice)).toEqual([alice.id]); + // And they can't get back in. + await bob.agent.post(`/conversations/${group.id}/call`).expect(404); + expect(await callsOf(bob)).toEqual([]); + await leaves(alice, group.id); + }); + }); + + describe('a call in a cauldron', () => { + it("reaches the realm's members", async () => { + const forDave = nextEvent(daveSocket, 'call:changed'); + await joins(alice, cauldronId); + await joins(dave, cauldronId); + expect(await forDave).toMatchObject({ + conversationId: cauldronId, + realmId: realm.id, + }); + expect(idsIn((await callsOf(dave)).at(0))).toEqual([alice.id, dave.id]); + expect(await callsOf(bob)).toEqual([]); + }); + + it('drops someone who leaves the realm', async () => { + const forAlice = nextEvent(aliceSocket, 'call:changed'); + await dave.agent + .delete(`/realms/${realm.id}/members/${dave.id}`) + .expect(204); + expect(await rooms.participants(cauldronId)).toEqual([alice.id]); + expect(idsIn(await forAlice)).toEqual([alice.id]); + expect(await callsOf(dave)).toEqual([]); + }); + + it('ends with the cauldron', async () => { + const second: { id: string } = ( + await alice.agent + .post(`/realms/${realm.id}/cauldrons`) + .send({ name: 'second' }) + .expect(201) + ).body; + await joins(alice, second.id); + expect((await callsOf(alice)).map((call) => call.conversationId)).toEqual( + expect.arrayContaining([cauldronId, second.id]), + ); + await alice.agent + .delete(`/realms/${realm.id}/cauldrons/${second.id}`) + .expect(204); + expect(await rooms.participants(second.id)).toEqual([]); + expect(await app.get(CallsStore).get(second.id)).toBeUndefined(); + }); + + it('ends with the realm', async () => { + await alice.agent.delete(`/realms/${realm.id}`).expect(204); + expect(await rooms.participants(cauldronId)).toEqual([]); + expect(await app.get(CallsStore).get(cauldronId)).toBeUndefined(); + expect(await callsOf(alice)).toEqual([]); + }); + }); + + describe('a friendship that ends', () => { + it('ends the call between the two', async () => { + await joins(alice, direct.id); + await joins(bob, direct.id); + const forBob = nextEvent(bobSocket, 'call:changed'); + await alice.agent.delete(`/friends/${bob.id}`).expect(204); + expect(await rooms.participants(direct.id)).toEqual([]); + expect(idsIn(await forBob)).toEqual([]); + expect(await callsOf(alice)).toEqual([]); + // The chat is still theirs to read, but not to call in. + await alice.agent.post(`/conversations/${direct.id}/call`).expect(403); + }); + }); +}); diff --git a/apps/api/test/chat.e2e-spec.ts b/apps/api/test/chat.e2e-spec.ts new file mode 100644 index 0000000..20f7e08 --- /dev/null +++ b/apps/api/test/chat.e2e-spec.ts @@ -0,0 +1,326 @@ +import type { + Conversation, + FriendsOverview, + Message, + MessagePage, +} from '@repo/contracts'; +import request from 'supertest'; +import { + befriend, + connected, + createTestApp, + listen, + nextEvent, + TestAccounts, + TestSockets, + type TestApp, + type TestUser, +} from './helpers'; + +describe('Friends, conversations and realtime (e2e)', () => { + let app: TestApp; + let accounts: TestAccounts; + let sockets: TestSockets; + let alice: TestUser; + let bob: TestUser; + let carol: TestUser; + + async function overviewOf(account: TestUser): Promise { + const response = await account.agent.get('/friends').expect(200); + return response.body; + } + + beforeAll(async () => { + app = await createTestApp(); + sockets = new TestSockets(await listen(app)); + accounts = new TestAccounts(app, '@chat-e2e.test'); + await accounts.cleanup(); + alice = await accounts.signUp('Alice'); + bob = await accounts.signUp('Bob'); + carol = await accounts.signUp('Carol'); + }); + + afterAll(async () => { + sockets.closeAll(); + await accounts.cleanup(); + await app.close(); + }); + + describe('friends', () => { + it('requires a session', () => { + return request(app.getHttpServer()).get('/friends').expect(401); + }); + + it('answers 404 for an unknown username and 400 for your own', async () => { + await alice.agent + .post('/friends/requests') + .send({ username: 'nobody_by_this_name' }) + .expect(404); + await alice.agent + .post('/friends/requests') + .send({ username: alice.username }) + .expect(400); + }); + + it('sends a request that shows up on both sides', async () => { + const response = await alice.agent + .post('/friends/requests') + .send({ username: bob.username }) + .expect(201); + expect(response.body).toMatchObject({ + status: 'pending', + user: { id: bob.id, username: bob.username, name: 'Bob' }, + }); + + const aliceSide = await overviewOf(alice); + expect(aliceSide.outgoing.map((pending) => pending.user.id)).toEqual([ + bob.id, + ]); + expect(aliceSide.incoming).toEqual([]); + + const bobSide = await overviewOf(bob); + expect(bobSide.incoming.map((pending) => pending.user.id)).toEqual([ + alice.id, + ]); + expect(bobSide.friends).toEqual([]); + }); + + it('answers 409 when the request was already sent', () => { + return alice.agent + .post('/friends/requests') + .send({ username: bob.username }) + .expect(409); + }); + + it("doesn't let the sender or a third person accept it", async () => { + await alice.agent.post(`/friends/requests/${bob.id}/accept`).expect(404); + await carol.agent + .post(`/friends/requests/${alice.id}/accept`) + .expect(404); + }); + + it('makes the two friends once it is accepted', async () => { + await bob.agent.post(`/friends/requests/${alice.id}/accept`).expect(204); + + const aliceSide = await overviewOf(alice); + expect(aliceSide.friends.map((friend) => friend.id)).toEqual([bob.id]); + expect(aliceSide.outgoing).toEqual([]); + const bobSide = await overviewOf(bob); + expect(bobSide.friends.map((friend) => friend.id)).toEqual([alice.id]); + expect(bobSide.incoming).toEqual([]); + + await alice.agent + .post('/friends/requests') + .send({ username: bob.username }) + .expect(409); + }); + + it('accepts straight away when both ask each other', async () => { + await carol.agent + .post('/friends/requests') + .send({ username: alice.username }) + .expect(201); + const response = await alice.agent + .post('/friends/requests') + .send({ username: carol.username }) + .expect(201); + expect(response.body.status).toBe('accepted'); + expect((await overviewOf(carol)).friends.map((f) => f.id)).toEqual([ + alice.id, + ]); + }); + + it('removes a friend for both', async () => { + await alice.agent.delete(`/friends/${carol.id}`).expect(204); + expect((await overviewOf(carol)).friends).toEqual([]); + expect((await overviewOf(alice)).friends.map((f) => f.id)).toEqual([ + bob.id, + ]); + await alice.agent.delete(`/friends/${carol.id}`).expect(404); + }); + }); + + describe('direct conversations', () => { + let conversation: Conversation; + + it("doesn't open a chat with someone who isn't a friend", async () => { + await carol.agent + .post('/conversations/direct') + .send({ userId: alice.id }) + .expect(403); + await alice.agent + .post('/conversations/direct') + .send({ userId: alice.id }) + .expect(400); + }); + + it('opens one chat per pair of friends', async () => { + const first = await alice.agent + .post('/conversations/direct') + .send({ userId: bob.id }) + .expect(200); + conversation = first.body; + expect(conversation.type).toBe('direct'); + expect(conversation.lastMessage).toBeNull(); + expect(conversation.members.map((member) => member.id).sort()).toEqual( + [alice.id, bob.id].sort(), + ); + + const again = await bob.agent + .post('/conversations/direct') + .send({ userId: alice.id }) + .expect(200); + expect(again.body.id).toBe(conversation.id); + }); + + it('posts messages and pages through them, newest first', async () => { + const sent: Message[] = []; + for (const content of ['one', ' two ', 'three']) { + const author = sent.length === 1 ? bob : alice; + const response = await author.agent + .post(`/conversations/${conversation.id}/messages`) + .send({ content }) + .expect(201); + sent.push(response.body); + } + expect(sent[1]).toMatchObject({ + content: 'two', + author: { id: bob.id, name: 'Bob' }, + }); + + const newest = await bob.agent + .get(`/conversations/${conversation.id}/messages?limit=2`) + .expect(200); + const firstPage: MessagePage = newest.body; + expect(firstPage.items.map((message) => message.content)).toEqual([ + 'three', + 'two', + ]); + expect(firstPage.nextCursor).toBe(sent[1].id); + + const older = await bob.agent + .get( + `/conversations/${conversation.id}/messages?limit=2&before=${firstPage.nextCursor}`, + ) + .expect(200); + expect(older.body).toEqual({ items: [sent[0]], nextCursor: null }); + }); + + it('lists the conversation with its latest message', async () => { + const response = await bob.agent.get('/conversations').expect(200); + expect(response.body).toHaveLength(1); + expect(response.body[0]).toMatchObject({ + id: conversation.id, + lastMessage: { content: 'three', author: { id: alice.id } }, + }); + }); + + it('rejects an empty or oversized message', async () => { + const path = `/conversations/${conversation.id}/messages`; + await alice.agent.post(path).send({ content: ' ' }).expect(400); + await alice.agent + .post(path) + .send({ content: 'x'.repeat(4001) }) + .expect(400); + await alice.agent.get(`${path}?limit=0`).expect(400); + await alice.agent.get(`${path}?before=not-an-id`).expect(400); + }); + + it('hides the conversation from people who are not in it', async () => { + await carol.agent.get(`/conversations/${conversation.id}`).expect(404); + await carol.agent + .get(`/conversations/${conversation.id}/messages`) + .expect(404); + await carol.agent + .post(`/conversations/${conversation.id}/messages`) + .send({ content: 'let me in' }) + .expect(404); + expect( + (await carol.agent.get('/conversations').expect(200)).body, + ).toEqual([]); + }); + + describe('realtime', () => { + it('refuses a socket without a session', async () => { + await expect(connected(sockets.connect())).rejects.toThrow( + 'Unauthorized', + ); + }); + + it('refuses a socket opened from another site', async () => { + const socket = sockets.connect(bob.cookie, { + origin: 'https://evil.example', + }); + await expect(connected(socket)).rejects.toThrow('Unauthorized'); + }); + + it('pushes a new message to both members, and only to them', async () => { + const aliceSocket = sockets.connect(alice.cookie); + const bobSocket = sockets.connect(bob.cookie); + const carolSocket = sockets.connect(carol.cookie); + await Promise.all([aliceSocket, bobSocket, carolSocket].map(connected)); + let carolGotIt = false; + carolSocket.on('message:created', () => { + carolGotIt = true; + }); + + const forAlice = nextEvent(aliceSocket, 'message:created'); + const forBob = nextEvent(bobSocket, 'message:created'); + const response = await alice.agent + .post(`/conversations/${conversation.id}/messages`) + .send({ content: 'live!' }) + .expect(201); + + expect(await forBob).toEqual(response.body); + expect(await forAlice).toEqual(response.body); + expect(carolGotIt).toBe(false); + }); + + it('tells both people when a friend request arrives', async () => { + const bobSocket = sockets.connect(bob.cookie); + const carolSocket = sockets.connect(carol.cookie); + await Promise.all([bobSocket, carolSocket].map(connected)); + + const forBob = nextEvent(bobSocket, 'friends:changed'); + const forCarol = nextEvent(carolSocket, 'friends:changed'); + await carol.agent + .post('/friends/requests') + .send({ username: bob.username }) + .expect(201); + await Promise.all([forBob, forCarol]); + }); + + it('closes the socket when its session signs out', async () => { + const dave = await accounts.signUp('Dave'); + const socket = sockets.connect(dave.cookie); + await connected(socket); + + const disconnected = new Promise((resolve) => { + socket.once('disconnect', resolve); + }); + await accounts.signOut(dave).expect(200); + expect(await disconnected).toBe('io server disconnect'); + }); + }); + + it('keeps the history but stops new messages after unfriending', async () => { + await bob.agent.delete(`/friends/${alice.id}`).expect(204); + + await alice.agent + .post(`/conversations/${conversation.id}/messages`) + .send({ content: 'still there?' }) + .expect(403); + const history = await alice.agent + .get(`/conversations/${conversation.id}/messages`) + .expect(200); + expect(history.body.items).toHaveLength(4); + + // Befriending again brings the same conversation back to life. + await befriend(alice, bob); + await alice.agent + .post(`/conversations/${conversation.id}/messages`) + .send({ content: 'back' }) + .expect(201); + }); + }); +}); diff --git a/apps/api/test/groups.e2e-spec.ts b/apps/api/test/groups.e2e-spec.ts new file mode 100644 index 0000000..63bcfcf --- /dev/null +++ b/apps/api/test/groups.e2e-spec.ts @@ -0,0 +1,305 @@ +import { + GROUP_MAX_MEMBERS, + type Conversation, + type MessagePage, +} from '@repo/contracts'; +import { + befriend, + createTestApp, + listen, + nextEvent, + TestAccounts, + TestSockets, + type TestApp, + type TestUser, +} from './helpers'; + +describe('Group chats (e2e)', () => { + let app: TestApp; + let accounts: TestAccounts; + let sockets: TestSockets; + // Alice is friends with Bob and Carol; Bob is also friends with Dave. + // Erin is nobody's friend. + let alice: TestUser; + let bob: TestUser; + let carol: TestUser; + let dave: TestUser; + let erin: TestUser; + let group: Conversation; + + const idsOf = (conversation: Conversation) => + conversation.members.map((member) => member.id).sort(); + + async function listOf(account: TestUser): Promise { + return (await account.agent.get('/conversations').expect(200)).body; + } + + beforeAll(async () => { + app = await createTestApp(); + sockets = new TestSockets(await listen(app)); + accounts = new TestAccounts(app, '@groups-e2e.test'); + await accounts.cleanup(); + [alice, bob, carol, dave, erin] = await Promise.all( + ['Alice', 'Bob', 'Carol', 'Dave', 'Erin'].map((name) => + accounts.signUp(name), + ), + ); + await befriend(alice, bob); + await befriend(alice, carol); + await befriend(bob, dave); + }); + + afterAll(async () => { + sockets.closeAll(); + await accounts.cleanup(); + await app.close(); + }); + + it('only starts a group with at least two friends', async () => { + const create = (memberIds: string[]) => + alice.agent.post('/conversations/group').send({ memberIds }); + + await create([bob.id]).expect(400); + await create([bob.id, bob.id]).expect(400); + await create([bob.id, alice.id]).expect(400); + await create([bob.id, erin.id]).expect(403); + await create([bob.id, 'no-such-user']).expect(403); + expect(await listOf(alice)).toEqual([]); + }); + + it('creates a group owned by its creator and tells everyone in it', async () => { + const bobSocket = await sockets.connectAs(bob); + const carolSocket = await sockets.connectAs(carol); + const forBob = nextEvent(bobSocket, 'conversations:changed'); + const forCarol = nextEvent(carolSocket, 'conversations:changed'); + + const response = await alice.agent + .post('/conversations/group') + .send({ name: ' Coven ', memberIds: [bob.id, carol.id] }) + .expect(201); + group = response.body; + + expect(group).toMatchObject({ + type: 'group', + name: 'Coven', + ownerId: alice.id, + lastMessage: null, + }); + expect(idsOf(group)).toEqual([alice.id, bob.id, carol.id].sort()); + expect(group.members[0].id).toBe(alice.id); + await Promise.all([forBob, forCarol]); + for (const member of [alice, bob, carol]) { + expect((await listOf(member)).map((item) => item.id)).toEqual([group.id]); + } + }); + + it('lets members who are not friends with each other talk', async () => { + const aliceSocket = await sockets.connectAs(alice); + const bobSocket = await sockets.connectAs(bob); + const forAlice = nextEvent(aliceSocket, 'message:created'); + const forBob = nextEvent(bobSocket, 'message:created'); + + // Carol and Bob never befriended each other. + const response = await carol.agent + .post(`/conversations/${group.id}/messages`) + .send({ content: 'hello, coven' }) + .expect(201); + + expect(response.body.author).toMatchObject({ id: carol.id, name: 'Carol' }); + expect(await forAlice).toEqual(response.body); + expect(await forBob).toEqual(response.body); + }); + + it('lets any member rename it, and clear the name', async () => { + const aliceSocket = await sockets.connectAs(alice); + const forAlice = nextEvent(aliceSocket, 'conversations:changed'); + + const renamed = await bob.agent + .patch(`/conversations/${group.id}`) + .send({ name: 'Night shift' }) + .expect(200); + expect(renamed.body.name).toBe('Night shift'); + await forAlice; + + const cleared = await carol.agent + .patch(`/conversations/${group.id}`) + .send({ name: ' ' }) + .expect(200); + expect(cleared.body.name).toBeNull(); + + await bob.agent + .patch(`/conversations/${group.id}`) + .send({ name: 'x'.repeat(101) }) + .expect(400); + }); + + it('hides the group from people who are not in it', async () => { + await dave.agent.get(`/conversations/${group.id}`).expect(404); + await dave.agent + .patch(`/conversations/${group.id}`) + .send({ name: 'Mine now' }) + .expect(404); + await dave.agent + .post(`/conversations/${group.id}/members`) + .send({ userIds: [erin.id] }) + .expect(404); + await dave.agent + .delete(`/conversations/${group.id}/members/${bob.id}`) + .expect(404); + }); + + it('lets a member add their own friends, who then see the history', async () => { + const path = `/conversations/${group.id}/members`; + // Dave is Bob's friend, not Alice's. + await alice.agent + .post(path) + .send({ userIds: [dave.id] }) + .expect(403); + await alice.agent.post(path).send({ userIds: [] }).expect(400); + + const daveSocket = await sockets.connectAs(dave); + const forDave = nextEvent(daveSocket, 'conversations:changed'); + const added = await bob.agent + .post(path) + .send({ userIds: [dave.id] }) + .expect(200); + expect(idsOf(added.body)).toEqual( + [alice.id, bob.id, carol.id, dave.id].sort(), + ); + // The owner comes first; whoever joins later goes last. + expect(added.body.members[0].id).toBe(alice.id); + expect(added.body.members.at(-1).id).toBe(dave.id); + await forDave; + + const history = await dave.agent + .get(`/conversations/${group.id}/messages`) + .expect(200); + expect( + (history.body as MessagePage).items.map((item) => item.content), + ).toEqual(['hello, coven']); + + // Adding someone who is already in changes nothing. + const again = await bob.agent + .post(path) + .send({ userIds: [dave.id] }) + .expect(200); + expect(again.body.members).toHaveLength(4); + }); + + it('lets only the owner remove someone', async () => { + const path = `/conversations/${group.id}/members`; + await bob.agent.delete(`${path}/${carol.id}`).expect(403); + await alice.agent.delete(`${path}/${erin.id}`).expect(404); + + const carolSocket = await sockets.connectAs(carol); + const forCarol = nextEvent(carolSocket, 'conversations:changed'); + await alice.agent.delete(`${path}/${carol.id}`).expect(204); + await forCarol; + + expect(await listOf(carol)).toEqual([]); + await carol.agent.get(`/conversations/${group.id}/messages`).expect(404); + await carol.agent + .post(`/conversations/${group.id}/messages`) + .send({ content: 'still here?' }) + .expect(404); + }); + + it("keeps a removed member's messages, with their name", async () => { + const history = await bob.agent + .get(`/conversations/${group.id}/messages`) + .expect(200); + expect((history.body as MessagePage).items[0]).toMatchObject({ + content: 'hello, coven', + author: { id: carol.id, name: 'Carol' }, + }); + }); + + it('stops messages reaching someone who was removed', async () => { + const carolSocket = await sockets.connectAs(carol); + const daveSocket = await sockets.connectAs(dave); + let carolGotIt = false; + carolSocket.on('message:created', () => { + carolGotIt = true; + }); + + const forDave = nextEvent(daveSocket, 'message:created'); + await bob.agent + .post(`/conversations/${group.id}/messages`) + .send({ content: 'members only' }) + .expect(201); + await forDave; + expect(carolGotIt).toBe(false); + }); + + it('passes ownership on when the owner leaves', async () => { + await alice.agent + .delete(`/conversations/${group.id}/members/${alice.id}`) + .expect(204); + expect(await listOf(alice)).toEqual([]); + + // Bob has been in it longer than Dave. + const [remaining] = await listOf(bob); + expect(remaining.ownerId).toBe(bob.id); + expect(idsOf(remaining)).toEqual([bob.id, dave.id].sort()); + + // And the new owner has the owner's powers. + await bob.agent + .delete(`/conversations/${group.id}/members/${dave.id}`) + .expect(204); + }); + + it('deletes the group when the last person leaves', async () => { + await bob.agent + .delete(`/conversations/${group.id}/members/${bob.id}`) + .expect(204); + for (const account of [alice, bob, carol, dave]) { + expect(await listOf(account)).toEqual([]); + await account.agent.get(`/conversations/${group.id}`).expect(404); + } + }); + + it('keeps group actions away from direct conversations', async () => { + const direct = await alice.agent + .post('/conversations/direct') + .send({ userId: bob.id }) + .expect(200); + const path = `/conversations/${direct.body.id}`; + + expect(direct.body).toMatchObject({ name: null, ownerId: null }); + await alice.agent.patch(path).send({ name: 'Us' }).expect(400); + await alice.agent + .post(`${path}/members`) + .send({ userIds: [carol.id] }) + .expect(400); + await alice.agent.delete(`${path}/members/${alice.id}`).expect(400); + }); + + it(`holds a group to ${GROUP_MAX_MEMBERS} people`, async () => { + const friends = await Promise.all( + Array.from({ length: GROUP_MAX_MEMBERS }, (_, index) => + accounts.signUp(`Friend${index}`), + ), + ); + for (const friend of friends) await befriend(alice, friend); + const [extra, ...others] = friends; + + await alice.agent + .post('/conversations/group') + .send({ memberIds: friends.map((friend) => friend.id) }) + .expect(400); + const full = await alice.agent + .post('/conversations/group') + .send({ memberIds: others.map((friend) => friend.id) }) + .expect(201); + expect(full.body.members).toHaveLength(GROUP_MAX_MEMBERS); + + await alice.agent + .post(`/conversations/${full.body.id}/members`) + .send({ userIds: [extra.id] }) + .expect(409); + const [unchanged] = (await listOf(alice)).filter( + (item) => item.id === full.body.id, + ); + expect(unchanged.members).toHaveLength(GROUP_MAX_MEMBERS); + }); +}); diff --git a/apps/api/test/helpers.ts b/apps/api/test/helpers.ts new file mode 100644 index 0000000..e820d79 --- /dev/null +++ b/apps/api/test/helpers.ts @@ -0,0 +1,272 @@ +import { randomUUID } from 'node:crypto'; +import { INestApplication } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { getDrizzleToken } from '@nestjs/drizzle'; +import { Test, type TestingModuleBuilder } from '@nestjs/testing'; +import type { + AttachmentUpload, + ClientToServerEvents, + CreateAttachment, + ServerToClientEvents, +} from '@repo/contracts'; +import { and, eq, inArray, isNull, like, notExists } from 'drizzle-orm'; +import { io, type Socket } from 'socket.io-client'; +import request from 'supertest'; +import type { App } from 'supertest/types'; +import { AppModule } from '../src/app.module'; +import type { Env } from '../src/config/env'; +import type { Database } from '../src/db/database'; +import { setUpHttp } from '../src/setup'; +import { + attachment, + conversation, + conversationMember, + user, +} from '../src/db/schema'; + +export type TestApp = INestApplication; +export type Agent = ReturnType; + +export interface TestUser { + id: string; + name: string; + username: string; + /** Sends requests as this user. */ + agent: Agent; + /** The session cookie, for clients that aren't supertest (sockets). */ + cookie: string; +} + +/** + * The whole app, as main.ts starts it. `adjust` can swap providers for + * stand-ins before it is put together. + */ +export async function createTestApp( + adjust: (builder: TestingModuleBuilder) => TestingModuleBuilder = (builder) => + builder, +): Promise { + const moduleFixture = await adjust( + Test.createTestingModule({ imports: [AppModule] }), + ).compile(); + // Same option as main.ts: Better Auth reads the raw body itself. + const app = moduleFixture.createNestApplication({ + bodyParser: false, + }); + setUpHttp(app); + await app.init(); + return app; +} + +/** + * Creates accounts in the local database for one spec file. Each file passes + * its own email domain, and `cleanup()` deletes every account under it (and, + * through cascades, everything those accounts own), then the conversations + * that are left with no members. + */ +export class TestAccounts { + // Spec files run side by side and may start in the same millisecond, so + // the time alone wouldn't keep their usernames apart. + private readonly run = + Date.now().toString(36) + randomUUID().replaceAll('-', '').slice(0, 4); + private readonly password = randomUUID(); + private readonly origin: string; + + constructor( + private readonly app: TestApp, + private readonly emailDomain: string, + ) { + [this.origin] = app + .get>(ConfigService) + .getOrThrow('TRUSTED_ORIGINS', { infer: true }); + } + + emailOf(name: string) { + return `${name.toLowerCase()}-${this.run}${this.emailDomain}`; + } + + /** A username that is unique to this run, e.g. "alice_m1x2y3". */ + usernameOf(name: string) { + return `${name.toLowerCase()}_${this.run}`; + } + + /** The raw sign-up request, for asserting on refusals. */ + requestSignUp(agent: Agent, name: string, username?: string) { + return agent + .post('/api/auth/sign-up/email') + .set('Origin', this.origin) + .send({ + name, + email: this.emailOf(name), + password: this.password, + username, + }); + } + + async signUp(name: string): Promise { + const agent = request.agent(this.app.getHttpServer()); + const username = this.usernameOf(name); + const response = await this.requestSignUp(agent, name, username).expect( + 200, + ); + const setCookie = response.get('Set-Cookie') ?? []; + return { + id: response.body.user.id, + name, + username, + agent, + cookie: setCookie.map((cookie) => cookie.split(';')[0]).join('; '), + }; + } + + signOut(account: TestUser) { + return account.agent + .post('/api/auth/sign-out') + .set('Origin', this.origin) + .send({}); + } + + async cleanup() { + const db = this.app.get(getDrizzleToken()); + const accounts = db + .select({ id: user.id }) + .from(user) + .where(like(user.email, `%${this.emailDomain}`)); + // Attachments outlive their uploader (for a day, until the cleanup), so + // these go first, while they can still be told apart. + await db.delete(attachment).where(inArray(attachment.uploaderId, accounts)); + await db.delete(user).where(like(user.email, `%${this.emailDomain}`)); + // Deleting a user removes their memberships and messages, not the + // conversation row itself. Cauldrons never have members and go with + // their realm, so they are left alone (another spec may be using them). + await db + .delete(conversation) + .where( + and( + isNull(conversation.realmId), + notExists( + db + .select() + .from(conversationMember) + .where(eq(conversationMember.conversationId, conversation.id)), + ), + ), + ); + } +} + +/** Makes two accounts friends: one asks, the other accepts. */ +export async function befriend(asker: TestUser, answerer: TestUser) { + await asker.agent + .post('/friends/requests') + .send({ username: answerer.username }) + .expect(201); + await answerer.agent.post(`/friends/requests/${asker.id}/accept`).expect(204); +} + +/** Asks for an upload the way the web app does, without sending the file. */ +export async function requestUpload( + account: TestUser, + file: CreateAttachment, +): Promise { + return (await account.agent.post('/attachments').send(file).expect(201)).body; +} + +/** + * Sends bytes to a signed upload address. No session goes along: the + * signature in the address is what lets the request in. + */ +export function putFile( + app: TestApp, + { upload }: AttachmentUpload, + bytes: Buffer, +) { + const { pathname, search } = new URL(upload.url); + return ( + request(app.getHttpServer()) + .put(pathname + search) + .set(upload.headers) + // As they are: left alone, the client would rewrite the bytes of a file + // whose type is JSON. + .serialize(() => bytes as unknown as string) + .send(bytes) + ); +} + +/** Uploads a file in full; answers with the id to list in a message. */ +export async function uploadFile( + app: TestApp, + account: TestUser, + file: Omit, + bytes: Buffer, +): Promise { + const upload = await requestUpload(account, { ...file, size: bytes.length }); + await putFile(app, upload, bytes).expect(200); + return upload.attachment.id; +} + +export type ClientSocket = Socket; + +/** Starts the app on a free port and returns its address, for sockets. */ +export async function listen(app: TestApp): Promise { + await app.listen(0); + return (await app.getUrl()).replace('[::1]', '127.0.0.1'); +} + +/** Opens sockets to a listening test app and closes them all at the end. */ +export class TestSockets { + private readonly sockets: ClientSocket[] = []; + + constructor(private readonly url: string) {} + + /** Opens a socket the way a browser would, with the session cookie. */ + connect(cookie?: string, headers: Record = {}): ClientSocket { + const socket: ClientSocket = io(this.url, { + transports: ['websocket'], + forceNew: true, + reconnection: false, + extraHeaders: { ...(cookie ? { cookie } : {}), ...headers }, + }); + this.sockets.push(socket); + return socket; + } + + /** A socket for this account, once the API has let it in. */ + async connectAs(account: TestUser): Promise { + const socket = this.connect(account.cookie); + await connected(socket); + return socket; + } + + closeAll() { + for (const socket of this.sockets) socket.disconnect(); + } +} + +/** Resolves when the API accepts the socket; rejects when it refuses. */ +export function connected(socket: ClientSocket) { + return new Promise((resolve, reject) => { + socket.once('connect', resolve); + socket.once('connect_error', reject); + }); +} + +/** Resolves with the next event's first argument (undefined if none). */ +export function nextEvent( + socket: ClientSocket, + event: Event, +) { + return new Promise[0]>( + (resolve, reject) => { + const timer = setTimeout( + () => reject(new Error(`No "${event}" event within 2s`)), + 2000, + ); + // The cast: TypeScript can't relate the listener of a generic event + // name to that event's own signature. + socket.once(event, ((payload?: unknown) => { + clearTimeout(timer); + resolve(payload as Parameters[0]); + }) as never); + }, + ); +} diff --git a/apps/api/test/messages.e2e-spec.ts b/apps/api/test/messages.e2e-spec.ts new file mode 100644 index 0000000..c34d231 --- /dev/null +++ b/apps/api/test/messages.e2e-spec.ts @@ -0,0 +1,571 @@ +import { + ATTACHMENT_MAX_SIZE, + MESSAGE_MAX_REACTIONS, + type Conversation, + type ConversationRead, + type Message, + type MessagePage, + type Realm, + type RealmInvite, + type RealmListItem, +} from '@repo/contracts'; +import request from 'supertest'; +import { + befriend, + createTestApp, + listen, + nextEvent, + putFile, + requestUpload, + TestAccounts, + TestSockets, + uploadFile, + type ClientSocket, + type TestApp, + type TestUser, +} from './helpers'; + +const PNG = { filename: 'cat.png', contentType: 'image/png' }; +const NOTES = { filename: 'notes.txt', contentType: 'text/plain' }; + +describe('Attachments, reactions and unread counts (e2e)', () => { + let app: TestApp; + let accounts: TestAccounts; + let sockets: TestSockets; + // Ada and Ben are friends with a direct chat; Cy is a friend of neither. + // Ada owns a realm that Ben joins part-way through. + let ada: TestUser; + let ben: TestUser; + let cy: TestUser; + let adaSocket: ClientSocket; + let benSocket: ClientSocket; + let chat: string; + + async function send( + account: TestUser, + conversationId: string, + body: { content?: string; attachmentIds?: string[] }, + ): Promise { + return ( + await account.agent + .post(`/conversations/${conversationId}/messages`) + .send(body) + .expect(201) + ).body; + } + + async function historyFor( + account: TestUser, + conversationId: string, + ): Promise { + const page: MessagePage = ( + await account.agent + .get(`/conversations/${conversationId}/messages`) + .expect(200) + ).body; + return page.items; + } + + async function chatFor(account: TestUser): Promise { + return (await account.agent.get(`/conversations/${chat}`).expect(200)).body; + } + + const reactionPath = ( + conversationId: string, + messageId: string, + emoji: string, + ) => + `/conversations/${conversationId}/messages/${messageId}/reactions/${encodeURIComponent(emoji)}`; + + /** Follows the redirect of GET /attachments/:id and fetches the file. */ + async function download(account: TestUser, attachmentId: string) { + const redirect = await account.agent + .get(`/attachments/${attachmentId}`) + .expect(302); + const { pathname, search } = new URL(redirect.get('Location') ?? ''); + return request(app.getHttpServer()) + .get(pathname + search) + .buffer(true) + .parse((res, done) => { + const chunks: Buffer[] = []; + res.on('data', (chunk: Buffer) => chunks.push(chunk)); + res.on('end', () => done(null, Buffer.concat(chunks))); + }) + .expect(200); + } + + beforeAll(async () => { + app = await createTestApp(); + sockets = new TestSockets(await listen(app)); + accounts = new TestAccounts(app, '@messages-e2e.test'); + await accounts.cleanup(); + ada = await accounts.signUp('Ada'); + ben = await accounts.signUp('Ben'); + cy = await accounts.signUp('Cy'); + await befriend(ada, ben); + const opened = await ada.agent + .post('/conversations/direct') + .send({ userId: ben.id }) + .expect(200); + chat = opened.body.id; + adaSocket = await sockets.connectAs(ada); + benSocket = await sockets.connectAs(ben); + }); + + afterAll(async () => { + sockets.closeAll(); + await accounts.cleanup(); + await app.close(); + }); + + describe('attachments', () => { + const picture = Buffer.from('not really a picture, but bytes all the same'); + let pictureId: string; + + it('requires a session to ask for an upload', () => { + return request(app.getHttpServer()) + .post('/attachments') + .send({ ...PNG, size: 10 }) + .expect(401); + }); + + it('refuses empty and oversized files and odd types', async () => { + await ada.agent + .post('/attachments') + .send({ ...PNG, size: 0 }) + .expect(400); + await ada.agent + .post('/attachments') + .send({ ...PNG, size: ATTACHMENT_MAX_SIZE + 1 }) + .expect(400); + await ada.agent + .post('/attachments') + .send({ filename: 'x', contentType: 'nonsense', size: 10 }) + .expect(400); + }); + + it('only accepts the bytes it was told to expect', async () => { + const upload = await requestUpload(ada, { + ...PNG, + size: picture.length, + width: 640, + height: 480, + }); + expect(upload.attachment).toEqual({ + id: upload.attachment.id, + filename: 'cat.png', + contentType: 'image/png', + size: picture.length, + width: 640, + height: 480, + }); + expect(upload.upload.method).toBe('PUT'); + + // Too short, and the wrong type: neither is stored. + const short = await putFile(app, upload, picture.subarray(0, 5)); + expect(short.status).toBeGreaterThanOrEqual(400); + const mistyped = await putFile(app, upload, picture).set( + 'Content-Type', + 'text/html', + ); + expect(mistyped.status).toBeGreaterThanOrEqual(400); + // A message can't carry a file that hasn't arrived. + await ada.agent + .post(`/conversations/${chat}/messages`) + .send({ attachmentIds: [upload.attachment.id] }) + .expect(400); + + await putFile(app, upload, picture).expect(200); + pictureId = upload.attachment.id; + }); + + it('refuses a tampered upload address', async () => { + const upload = await requestUpload(ada, { ...NOTES, size: 4 }); + const { pathname, search } = new URL(upload.upload.url); + await request(app.getHttpServer()) + .put(pathname + search.slice(0, -4) + 'AAAA') + .set(upload.upload.headers) + .send(Buffer.from('boo!')) + .expect(403); + await ada.agent + .delete(`/attachments/${upload.attachment.id}`) + .expect(204); + }); + + it('lets the uploader see a file before it is sent, and no one else', async () => { + expect((await download(ada, pictureId)).body).toEqual(picture); + await ben.agent.get(`/attachments/${pictureId}`).expect(404); + }); + + it("won't put someone else's upload on a message", async () => { + await ben.agent + .post(`/conversations/${chat}/messages`) + .send({ content: 'mine now', attachmentIds: [pictureId] }) + .expect(400); + }); + + it('posts a message with nothing but a file, and tells both people', async () => { + const forBen = nextEvent(benSocket, 'message:created'); + const message = await send(ada, chat, { attachmentIds: [pictureId] }); + expect(message.content).toBe(''); + expect(message.attachments).toEqual([ + { + id: pictureId, + filename: 'cat.png', + contentType: 'image/png', + size: picture.length, + width: 640, + height: 480, + }, + ]); + expect((await forBen).attachments).toEqual(message.attachments); + expect((await historyFor(ben, chat)).at(0)?.attachments).toEqual( + message.attachments, + ); + const last = (await chatFor(ben)).lastMessage; + expect(last?.attachments.map((file) => file.id)).toEqual([pictureId]); + }); + + it('serves the file to people in the chat, pictures inline', async () => { + const response = await download(ben, pictureId); + expect(response.body).toEqual(picture); + expect(response.get('Content-Type')).toBe('image/png'); + expect(response.get('Content-Disposition')).toMatch(/^inline/); + }); + + it('hides it from everyone else', async () => { + await cy.agent.get(`/attachments/${pictureId}`).expect(404); + await request(app.getHttpServer()) + .get(`/attachments/${pictureId}`) + .expect(401); + }); + + it("won't send the same file twice or take back one that was sent", async () => { + await ada.agent + .post(`/conversations/${chat}/messages`) + .send({ content: 'again', attachmentIds: [pictureId] }) + .expect(400); + await ada.agent.delete(`/attachments/${pictureId}`).expect(404); + await download(ben, pictureId); + }); + + it('keeps several files in the order they were uploaded, as downloads', async () => { + const first = await uploadFile(app, ada, NOTES, Buffer.from('one')); + const second = await uploadFile( + app, + ada, + { filename: 'page.html', contentType: 'text/html' }, + Buffer.from(''), + ); + const message = await send(ada, chat, { + content: 'two files', + attachmentIds: [second, first], + }); + expect(message.attachments.map((file) => file.id)).toEqual([ + first, + second, + ]); + // No sizes are kept for what isn't shown as a picture. + expect(message.attachments[0]).toMatchObject({ + width: null, + height: null, + }); + + const page = await download(ben, second); + expect(page.get('Content-Disposition')).toMatch( + /^attachment; filename="page\.html"/, + ); + expect(page.get('X-Content-Type-Options')).toBe('nosniff'); + }); + + it('takes back an upload that was never sent', async () => { + const id = await uploadFile(app, ada, NOTES, Buffer.from('draft')); + await ben.agent.delete(`/attachments/${id}`).expect(404); + await ada.agent.delete(`/attachments/${id}`).expect(204); + await ada.agent.get(`/attachments/${id}`).expect(404); + await ada.agent + .post(`/conversations/${chat}/messages`) + .send({ attachmentIds: [id] }) + .expect(400); + }); + + it('stores a JSON file as it is, without reading it as a request', async () => { + const bytes = Buffer.from('{"not": "a request body"}'); + const id = await uploadFile( + app, + ada, + { filename: 'data.json', contentType: 'application/json' }, + bytes, + ); + expect((await download(ada, id)).body).toEqual(bytes); + await ada.agent.delete(`/attachments/${id}`).expect(204); + }); + }); + + describe('reactions', () => { + let message: Message; + + beforeAll(async () => { + message = await send(ada, chat, { content: 'React to this' }); + }); + + it('adds a reaction once and tells both people', async () => { + const forAda = nextEvent(adaSocket, 'reaction:changed'); + const forBen = nextEvent(benSocket, 'reaction:changed'); + await ben.agent.put(reactionPath(chat, message.id, '👍')).expect(204); + const change = { + conversationId: chat, + messageId: message.id, + emoji: '👍', + count: 1, + userId: ben.id, + added: true, + }; + expect(await forAda).toEqual(change); + expect(await forBen).toEqual(change); + + // Again changes nothing. + await ben.agent.put(reactionPath(chat, message.id, '👍')).expect(204); + expect((await historyFor(ben, chat)).at(0)?.reactions).toEqual([ + { emoji: '👍', count: 1, mine: true }, + ]); + expect((await historyFor(ada, chat)).at(0)?.reactions).toEqual([ + { emoji: '👍', count: 1, mine: false }, + ]); + }); + + it('counts people per emoji, in the order the emoji were first used', async () => { + await ada.agent.put(reactionPath(chat, message.id, '👨‍👩‍👧')).expect(204); + await ada.agent.put(reactionPath(chat, message.id, '👍')).expect(204); + expect((await historyFor(ada, chat)).at(0)?.reactions).toEqual([ + { emoji: '👍', count: 2, mine: true }, + { emoji: '👨‍👩‍👧', count: 1, mine: true }, + ]); + }); + + it('takes a reaction back and tells both people', async () => { + const forAda = nextEvent(adaSocket, 'reaction:changed'); + await ben.agent.delete(reactionPath(chat, message.id, '👍')).expect(204); + expect(await forAda).toMatchObject({ + emoji: '👍', + count: 1, + userId: ben.id, + added: false, + }); + // Taking back what isn't there is fine. + await ben.agent.delete(reactionPath(chat, message.id, '👍')).expect(204); + await ada.agent.delete(reactionPath(chat, message.id, '👨‍👩‍👧')).expect(204); + expect((await historyFor(ben, chat)).at(0)?.reactions).toEqual([ + { emoji: '👍', count: 1, mine: false }, + ]); + }); + + it('only takes single emoji', async () => { + await ben.agent.put(reactionPath(chat, message.id, 'lol')).expect(400); + await ben.agent.put(reactionPath(chat, message.id, '👍👍')).expect(400); + }); + + it('answers 404 to outsiders and for a message from elsewhere', async () => { + await cy.agent.put(reactionPath(chat, message.id, '👍')).expect(404); + const realm: Realm = ( + await ada.agent.post('/realms').send({ name: 'Elsewhere' }).expect(201) + ).body; + await ada.agent + .put(reactionPath(realm.cauldrons[0].id, message.id, '👍')) + .expect(404); + await ada.agent.delete(`/realms/${realm.id}`).expect(204); + }); + + it(`stops at ${MESSAGE_MAX_REACTIONS} different emoji`, async () => { + const crowded = await send(ada, chat, { content: 'Popular' }); + const emoji = + '😀 😁 😂 🤣 😃 😄 😅 😆 😉 😊 😋 😎 😍 😘 🥰 😗 😙 😚 🙂 🤗 🤩'.split( + ' ', + ); + expect(emoji).toHaveLength(MESSAGE_MAX_REACTIONS + 1); + for (const one of emoji.slice(0, MESSAGE_MAX_REACTIONS)) { + await ada.agent.put(reactionPath(chat, crowded.id, one)).expect(204); + } + await ben.agent + .put(reactionPath(chat, crowded.id, emoji[MESSAGE_MAX_REACTIONS])) + .expect(409); + // One that is there already still has room for more people. + await ben.agent.put(reactionPath(chat, crowded.id, emoji[0])).expect(204); + }); + }); + + describe('unread counts', () => { + let first: Message; + let second: Message; + + it('counts what other people posted since the reader last looked', async () => { + // Ben has posted nothing and read nothing so far. + const before = (await chatFor(ben)).unreadCount; + expect(before).toBeGreaterThan(0); + first = await send(ada, chat, { content: 'Unread one' }); + second = await send(ada, chat, { content: 'Unread two' }); + expect((await chatFor(ben)).unreadCount).toBe(before + 2); + // Posting counts as having read. + expect((await chatFor(ada)).unreadCount).toBe(0); + const listed: Conversation[] = ( + await ben.agent.get('/conversations').expect(200) + ).body; + expect(listed.find((item) => item.id === chat)?.unreadCount).toBe( + before + 2, + ); + }); + + it('marks a conversation read up to a message, on every device', async () => { + const elsewhere = nextEvent(benSocket, 'conversation:read'); + const read: ConversationRead = ( + await ben.agent + .put(`/conversations/${chat}/read`) + .send({ messageId: first.id }) + .expect(200) + ).body; + expect(read).toEqual({ + conversationId: chat, + realmId: null, + unreadCount: 1, + }); + expect(await elsewhere).toEqual(read); + expect((await chatFor(ben)).unreadCount).toBe(1); + }); + + it('never moves the marker back', async () => { + await ben.agent + .put(`/conversations/${chat}/read`) + .send({ messageId: second.id }) + .expect(200); + const read: ConversationRead = ( + await ben.agent + .put(`/conversations/${chat}/read`) + .send({ messageId: first.id }) + .expect(200) + ).body; + expect(read.unreadCount).toBe(0); + expect((await chatFor(ben)).unreadCount).toBe(0); + }); + + it('answers 404 to outsiders and for a message from elsewhere', async () => { + await cy.agent + .put(`/conversations/${chat}/read`) + .send({ messageId: first.id }) + .expect(404); + await ben.agent + .put(`/conversations/${chat}/read`) + .send({ messageId: chat }) + .expect(404); + }); + + it("doesn't count a sender's own messages against them", async () => { + await send(ben, chat, { content: 'Reply' }); + expect((await chatFor(ben)).unreadCount).toBe(0); + expect((await chatFor(ada)).unreadCount).toBe(1); + }); + }); + + describe('in a realm', () => { + let realm: Realm; + let general: string; + let fileId: string; + + async function realmFor(account: TestUser): Promise { + return (await account.agent.get(`/realms/${realm.id}`).expect(200)).body; + } + + async function listedFor(account: TestUser): Promise { + const realms: RealmListItem[] = ( + await account.agent.get('/realms').expect(200) + ).body; + const listed = realms.find((item) => item.id === realm.id); + if (!listed) throw new Error('The realm is not in the list.'); + return listed; + } + + beforeAll(async () => { + realm = ( + await ada.agent.post('/realms').send({ name: 'Library' }).expect(201) + ).body; + general = realm.cauldrons[0].id; + expect(realm.cauldrons[0].unreadCount).toBe(0); + + fileId = await uploadFile(app, ada, NOTES, Buffer.from('for members')); + await send(ada, general, { + content: 'Before Ben', + attachmentIds: [fileId], + }); + const invite: RealmInvite = ( + await ada.agent.post(`/realms/${realm.id}/invites`).send({}).expect(201) + ).body; + await ben.agent.post(`/invites/${invite.code}/accept`).expect(200); + }); + + it('starts a new member with nothing unread', async () => { + expect((await realmFor(ben)).cauldrons[0].unreadCount).toBe(0); + expect((await listedFor(ben)).hasUnread).toBe(false); + }); + + it('counts unread messages per cauldron and flags the realm', async () => { + const message = await send(ada, general, { content: 'After Ben' }); + expect((await realmFor(ben)).cauldrons[0].unreadCount).toBe(1); + expect((await listedFor(ben)).hasUnread).toBe(true); + expect((await listedFor(ada)).hasUnread).toBe(false); + + const read: ConversationRead = ( + await ben.agent + .put(`/conversations/${general}/read`) + .send({ messageId: message.id }) + .expect(200) + ).body; + expect(read).toEqual({ + conversationId: general, + realmId: realm.id, + unreadCount: 0, + }); + expect((await listedFor(ben)).hasUnread).toBe(false); + }); + + it('lets members react, and tells the realm', async () => { + const message = (await historyFor(ben, general)).at(0); + if (!message) throw new Error('The cauldron is empty.'); + const forAda = nextEvent(adaSocket, 'reaction:changed'); + await ben.agent.put(reactionPath(general, message.id, '🔥')).expect(204); + expect(await forAda).toMatchObject({ + emoji: '🔥', + count: 1, + added: true, + }); + await cy.agent.put(reactionPath(general, message.id, '🔥')).expect(404); + }); + + it("serves a cauldron's files to members only", async () => { + expect((await download(ben, fileId)).body).toEqual( + Buffer.from('for members'), + ); + await cy.agent.get(`/attachments/${fileId}`).expect(404); + await ben.agent + .delete(`/realms/${realm.id}/members/${ben.id}`) + .expect(204); + await ben.agent.get(`/attachments/${fileId}`).expect(404); + }); + + it('stops serving files once their realm is deleted', async () => { + await ada.agent.delete(`/realms/${realm.id}`).expect(204); + await ben.agent.get(`/attachments/${fileId}`).expect(404); + }); + }); + + describe('after unfriending', () => { + it('keeps the history and its files readable, but not open to reactions', async () => { + const message = (await historyFor(ben, chat)).at(0); + if (!message) throw new Error('The chat is empty.'); + await ada.agent.delete(`/friends/${ben.id}`).expect(204); + await ben.agent.put(reactionPath(chat, message.id, '👋')).expect(403); + await ben.agent + .put(`/conversations/${chat}/read`) + .send({ messageId: message.id }) + .expect(200); + }); + }); +}); diff --git a/apps/api/test/moderation.e2e-spec.ts b/apps/api/test/moderation.e2e-spec.ts new file mode 100644 index 0000000..77248ad --- /dev/null +++ b/apps/api/test/moderation.e2e-spec.ts @@ -0,0 +1,396 @@ +import { randomUUID } from 'node:crypto'; +import type { + Conversation, + FriendsOverview, + InvitePreview, + Message, + MessagePage, + Realm, + RealmBan, + RealmInvite, + RealmMember, + RealmRole, +} from '@repo/contracts'; +import { + befriend, + createTestApp, + listen, + nextEvent, + TestAccounts, + TestSockets, + uploadFile, + type ClientSocket, + type TestApp, + type TestUser, +} from './helpers'; + +describe('Moderation (e2e)', () => { + let app: TestApp; + let accounts: TestAccounts; + let sockets: TestSockets; + // Rosa owns the group and the realm. Sam and Tess are her friends and in + // both; Uma is a stranger to everyone until she joins the realm. + let rosa: TestUser; + let sam: TestUser; + let tess: TestUser; + let uma: TestUser; + let rosaSocket: ClientSocket; + let samSocket: ClientSocket; + + async function post( + account: TestUser, + conversationId: string, + body: { content?: string; attachmentIds?: string[] }, + ): Promise { + return ( + await account.agent + .post(`/conversations/${conversationId}/messages`) + .send(body) + .expect(201) + ).body; + } + + const remove = (account: TestUser, message: Message) => + account.agent.delete( + `/conversations/${message.conversationId}/messages/${message.id}`, + ); + + async function historyOf( + account: TestUser, + conversationId: string, + ): Promise { + const page: MessagePage = ( + await account.agent + .get(`/conversations/${conversationId}/messages`) + .expect(200) + ).body; + return page.items.map((item) => item.id); + } + + async function friendsOf(account: TestUser): Promise { + return (await account.agent.get('/friends').expect(200)).body; + } + + beforeAll(async () => { + app = await createTestApp(); + sockets = new TestSockets(await listen(app)); + accounts = new TestAccounts(app, '@moderation-e2e.test'); + await accounts.cleanup(); + [rosa, sam, tess, uma] = await Promise.all( + ['Rosa', 'Sam', 'Tess', 'Uma'].map((name) => accounts.signUp(name)), + ); + await befriend(rosa, sam); + await befriend(rosa, tess); + await befriend(sam, tess); + [rosaSocket, samSocket] = await Promise.all([ + sockets.connectAs(rosa), + sockets.connectAs(sam), + ]); + }); + + afterAll(async () => { + sockets.closeAll(); + await accounts.cleanup(); + await app.close(); + }); + + describe('deleting messages', () => { + let direct: Conversation; + let group: Conversation; + + beforeAll(async () => { + direct = ( + await rosa.agent + .post('/conversations/direct') + .send({ userId: sam.id }) + .expect(200) + ).body; + group = ( + await rosa.agent + .post('/conversations/group') + .send({ memberIds: [sam.id, tess.id] }) + .expect(201) + ).body; + }); + + it('lets the author delete their message, and tells everyone there', async () => { + const message = await post(rosa, direct.id, { content: 'oops' }); + const forSam = nextEvent(samSocket, 'message:deleted'); + const forRosa = nextEvent(rosaSocket, 'message:deleted'); + await remove(rosa, message).expect(204); + + const deletion = { + conversationId: direct.id, + messageId: message.id, + realmId: null, + }; + expect(await forSam).toEqual(deletion); + expect(await forRosa).toEqual(deletion); + expect(await historyOf(sam, direct.id)).not.toContain(message.id); + // Gone is gone. + await remove(rosa, message).expect(404); + }); + + it("refuses someone else's message in a direct chat", async () => { + const message = await post(rosa, direct.id, { content: 'mine' }); + await remove(sam, message).expect(403); + // Someone who can't read the chat isn't told the message exists. + await remove(tess, message).expect(404); + await rosa.agent + .delete(`/conversations/${direct.id}/messages/${randomUUID()}`) + .expect(404); + expect(await historyOf(sam, direct.id)).toContain(message.id); + }); + + it('takes the unread count and the files along', async () => { + const unreadOf = async () => + ( + (await sam.agent.get(`/conversations/${direct.id}`).expect(200)) + .body as Conversation + ).unreadCount; + const before = await unreadOf(); + const fileId = await uploadFile( + app, + rosa, + { filename: 'notes.txt', contentType: 'text/plain' }, + Buffer.from('for your eyes only'), + ); + const message = await post(rosa, direct.id, { attachmentIds: [fileId] }); + expect(await unreadOf()).toBe(before + 1); + await sam.agent.get(`/attachments/${fileId}`).expect(302); + + await remove(rosa, message).expect(204); + expect(await unreadOf()).toBe(before); + await sam.agent.get(`/attachments/${fileId}`).expect(404); + }); + + it("lets a group's owner delete anyone's message there", async () => { + const fromSam = await post(sam, group.id, { content: 'spam' }); + const fromRosa = await post(rosa, group.id, { content: 'rules' }); + await remove(tess, fromSam).expect(403); + await remove(sam, fromRosa).expect(403); + await remove(rosa, fromSam).expect(204); + expect(await historyOf(tess, group.id)).toEqual([fromRosa.id]); + }); + }); + + describe('in a realm', () => { + let realm: Realm; + let cauldronId: string; + let invite: RealmInvite; + let keeper: RealmRole; + + const membersOf = async (account: TestUser) => + ( + (await account.agent.get(`/realms/${realm.id}/members`).expect(200)) + .body as RealmMember[] + ).map((member) => member.user.id); + + const join = (account: TestUser) => + account.agent.post(`/invites/${invite.code}/accept`); + + const ban = (by: TestUser, target: TestUser, body: object = {}) => + by.agent.put(`/realms/${realm.id}/bans/${target.id}`).send(body); + + beforeAll(async () => { + realm = ( + await rosa.agent.post('/realms').send({ name: 'Order' }).expect(201) + ).body; + cauldronId = realm.cauldrons[0].id; + invite = ( + await rosa.agent + .post(`/realms/${realm.id}/invites`) + .send({ expiresInDays: null }) + .expect(201) + ).body; + for (const account of [sam, tess, uma]) await join(account).expect(200); + // Sam becomes a keeper: may delete messages and ban, nothing more. + keeper = ( + await rosa.agent + .post(`/realms/${realm.id}/roles`) + .send({ + name: 'Keeper', + permissions: ['manageMessages', 'banMembers'], + }) + .expect(201) + ).body; + await rosa.agent + .put(`/realms/${realm.id}/members/${sam.id}/roles`) + .send({ roleIds: [keeper.id] }) + .expect(200); + }); + + it('lets members with "manageMessages" delete what others posted', async () => { + const fromUma = await post(uma, cauldronId, { content: 'rude' }); + const fromSam = await post(sam, cauldronId, { content: 'calm down' }); + // Tess has no such permission; Uma may only delete her own. + await remove(tess, fromUma).expect(403); + await remove(uma, fromSam).expect(403); + + const forRosa = nextEvent(rosaSocket, 'message:deleted'); + await remove(sam, fromUma).expect(204); + expect(await forRosa).toEqual({ + conversationId: cauldronId, + messageId: fromUma.id, + realmId: realm.id, + }); + await remove(sam, fromSam).expect(204); + expect(await historyOf(tess, cauldronId)).toEqual([]); + }); + + it('takes "banMembers" to ban, and to see or lift bans', async () => { + await ban(tess, uma).expect(403); + await tess.agent.get(`/realms/${realm.id}/bans`).expect(403); + await tess.agent.delete(`/realms/${realm.id}/bans/${uma.id}`).expect(403); + // Someone outside the realm isn't told it exists. + const outsider = await accounts.signUp('Vic'); + await ban(outsider, uma).expect(404); + }); + + it('never bans the owner, oneself, or someone who can do more', async () => { + await ban(sam, rosa).expect(403); + await ban(sam, sam).expect(400); + // Tess is given more than Sam has. + const elder: RealmRole = ( + await rosa.agent + .post(`/realms/${realm.id}/roles`) + .send({ name: 'Elder', permissions: ['manageRealm'] }) + .expect(201) + ).body; + await rosa.agent + .put(`/realms/${realm.id}/members/${tess.id}/roles`) + .send({ roleIds: [elder.id] }) + .expect(200); + await ban(sam, tess).expect(403); + expect(await membersOf(rosa)).toContain(tess.id); + await ban(sam, uma, { reason: 'x'.repeat(201) }).expect(400); + }); + + it('puts a banned member out and keeps them out', async () => { + const umaSocket = await sockets.connectAs(uma); + const forUma = nextEvent(umaSocket, 'realm:changed'); + await ban(sam, uma, { reason: ' Kept being rude ' }).expect(204); + // They are told the realm changed, which takes it off their list. + expect(await forUma).toBe(realm.id); + + expect(await membersOf(rosa)).not.toContain(uma.id); + await uma.agent.get(`/realms/${realm.id}`).expect(404); + await uma.agent.get(`/conversations/${cauldronId}/messages`).expect(404); + + const preview: InvitePreview = ( + await uma.agent.get(`/invites/${invite.code}`).expect(200) + ).body; + expect(preview).toMatchObject({ isMember: false, isBanned: true }); + await join(uma).expect(403); + expect(await membersOf(rosa)).not.toContain(uma.id); + // Someone no longer in the realm can't be banned again. + await ban(sam, uma).expect(404); + }); + + it('lists bans with who made them and why', async () => { + const bans: RealmBan[] = ( + await rosa.agent.get(`/realms/${realm.id}/bans`).expect(200) + ).body; + expect(bans).toEqual([ + { + user: { + id: uma.id, + name: 'Uma', + username: uma.username, + image: null, + }, + bannedBy: expect.objectContaining({ id: sam.id }), + reason: 'Kept being rude', + createdAt: expect.any(String), + }, + ]); + }); + + it('lets them back in once the ban is lifted', async () => { + await sam.agent.delete(`/realms/${realm.id}/bans/${uma.id}`).expect(204); + await sam.agent.delete(`/realms/${realm.id}/bans/${uma.id}`).expect(404); + expect( + (await rosa.agent.get(`/realms/${realm.id}/bans`).expect(200)).body, + ).toEqual([]); + // Lifting a ban doesn't bring them back by itself. + expect(await membersOf(rosa)).not.toContain(uma.id); + await join(uma).expect(200); + expect(await membersOf(rosa)).toContain(uma.id); + }); + }); + + describe('blocking', () => { + let direct: Conversation; + + const block = (account: TestUser, userId: string) => + account.agent.put(`/friends/blocks/${userId}`); + const unblock = (account: TestUser, userId: string) => + account.agent.delete(`/friends/blocks/${userId}`); + const ask = (account: TestUser, target: TestUser) => + account.agent + .post('/friends/requests') + .send({ username: target.username }); + const ids = (people: { id: string }[]) => people.map((person) => person.id); + + beforeAll(async () => { + direct = ( + await tess.agent + .post('/conversations/direct') + .send({ userId: sam.id }) + .expect(200) + ).body; + }); + + it('refuses to block oneself or nobody', async () => { + await block(tess, tess.id).expect(400); + await block(tess, 'no-such-user').expect(404); + await unblock(tess, sam.id).expect(404); + }); + + it('ends the friendship, and both are told their lists changed', async () => { + const forSam = nextEvent(samSocket, 'friends:changed'); + await block(tess, sam.id).expect(204); + await forSam; + // Doing it again changes nothing. + await block(tess, sam.id).expect(204); + + const mine = await friendsOf(tess); + expect(ids(mine.friends)).not.toContain(sam.id); + expect(ids(mine.blocked)).toEqual([sam.id]); + const theirs = await friendsOf(sam); + expect(ids(theirs.friends)).not.toContain(tess.id); + // The blocked person isn't shown who blocked them. + expect(theirs.blocked).toEqual([]); + }); + + it('keeps the two from becoming friends again or messaging', async () => { + await ask(sam, tess).expect(403); + await ask(tess, sam).expect(409); + await sam.agent + .post(`/conversations/${direct.id}/messages`) + .send({ content: 'hello?' }) + .expect(403); + await sam.agent.post(`/conversations/${direct.id}/call`).expect(403); + expect((await friendsOf(tess)).incoming).toEqual([]); + }); + + it('drops a request that was waiting', async () => { + const wes = await accounts.signUp('Wes'); + await ask(wes, tess).expect(201); + expect((await friendsOf(tess)).incoming).toHaveLength(1); + await block(tess, wes.id).expect(204); + expect((await friendsOf(tess)).incoming).toEqual([]); + expect((await friendsOf(wes)).outgoing).toEqual([]); + }); + + it('lets them ask again once unblocked', async () => { + await unblock(tess, sam.id).expect(204); + expect( + (await friendsOf(tess)).blocked.map((user) => user.id), + ).not.toContain(sam.id); + // Unblocking doesn't restore the friendship. + expect(ids((await friendsOf(tess)).friends)).not.toContain(sam.id); + await ask(sam, tess).expect(201); + }); + }); +}); diff --git a/apps/api/test/rate-limit.e2e-spec.ts b/apps/api/test/rate-limit.e2e-spec.ts new file mode 100644 index 0000000..2233770 --- /dev/null +++ b/apps/api/test/rate-limit.e2e-spec.ts @@ -0,0 +1,95 @@ +import { ConfigService } from '@nestjs/config'; +import type { Redis } from 'ioredis'; +import request from 'supertest'; +import type { Env } from '../src/config/env'; +import { DEFAULT_LIMIT } from '../src/rate-limit/rate-limit.module'; +import { REDIS } from '../src/redis/redis.module'; +import { createTestApp, TestAccounts, type TestApp } from './helpers'; + +// The other specs run with the limits lifted; this one is about them. The +// setting is read when the app's modules load, which is before anything +// below this line would run. +vi.hoisted(() => { + process.env.RATE_LIMIT = 'true'; +}); + +describe('Rate limits (e2e)', () => { + let app: TestApp; + let accounts: TestAccounts; + + beforeAll(async () => { + app = await createTestApp(); + // Sign-ins are counted per address, and every run comes from this + // machine: start from nothing, or a second run within the minute fails. + const redis = app.get(REDIS); + const counted = await redis.keys('rate:*'); + if (counted.length > 0) await redis.del(counted); + accounts = new TestAccounts(app, '@rate-limit-e2e.test'); + await accounts.cleanup(); + }); + + afterAll(async () => { + await accounts.cleanup(); + await app.close(); + }); + + it('counts per person and per route, and says when to come back', async () => { + const [ada, ben] = await Promise.all([ + accounts.signUp('Ada'), + accounts.signUp('Ben'), + ]); + // Creating a realm is allowed 5 times a minute. + for (let count = 1; count <= 5; count++) { + const made = await ada.agent + .post('/realms') + .send({ name: `Realm ${count}` }) + .expect(201); + expect(made.headers['x-ratelimit-remaining']).toBe(String(5 - count)); + } + const refused = await ada.agent + .post('/realms') + .send({ name: 'One too many' }) + .expect(429); + const wait = Number(refused.headers['retry-after']); + expect(wait).toBeGreaterThan(0); + expect(wait).toBeLessThanOrEqual(60); + + // Her other routes still answer, and so does the same route for Ben. + const listed = await ada.agent.get('/realms').expect(200); + expect(listed.body).toHaveLength(5); + expect(listed.headers['x-ratelimit-limit']).toBe( + String(DEFAULT_LIMIT.limit), + ); + await ben.agent.post('/realms').send({ name: "Ben's" }).expect(201); + }); + + it('leaves the health checks alone', async () => { + const checked = await request(app.getHttpServer()) + .get('/health') + .expect(200); + expect(checked.headers).not.toHaveProperty('x-ratelimit-limit'); + }); + + it('slows down guessing a password', async () => { + const cal = await accounts.signUp('Cal'); + const [origin] = app + .get>(ConfigService) + .getOrThrow('TRUSTED_ORIGINS', { infer: true }); + const guess = () => + request(app.getHttpServer()) + .post('/api/auth/sign-in/username') + .set('Origin', origin) + .send({ username: cal.username, password: 'not-the-password' }); + + // Sign-in allows an address 10 tries a minute. Other specs' sign-ins + // don't count here: their limits are off, so nothing is recorded. + const answers: number[] = []; + for (let count = 0; count < 12; count++) { + answers.push((await guess()).status); + } + expect(answers.slice(0, 10)).toEqual(Array(10).fill(401)); + expect(answers.slice(10)).toEqual([429, 429]); + const refused = await guess(); + expect(Number(refused.headers['x-retry-after'])).toBeGreaterThan(0); + }); +}); diff --git a/apps/api/test/realms.e2e-spec.ts b/apps/api/test/realms.e2e-spec.ts new file mode 100644 index 0000000..ae170ec --- /dev/null +++ b/apps/api/test/realms.e2e-spec.ts @@ -0,0 +1,644 @@ +import { + REALM_MAX_ROLES, + REALM_PERMISSIONS, + type Conversation, + type InvitePreview, + type Message, + type MessagePage, + type Realm, + type RealmInvite, + type RealmMember, + type RealmRole, + type RealmListItem, +} from '@repo/contracts'; +import { + createTestApp, + listen, + TestAccounts, + TestSockets, + type ClientSocket, + type TestApp, + type TestUser, +} from './helpers'; + +describe('Realms (e2e)', () => { + let app: TestApp; + let accounts: TestAccounts; + let sockets: TestSockets; + // Olga owns the realm. Mia becomes a moderator, Nat stays an ordinary + // member, Pat is made an admin and Quin never joins. + let olga: TestUser; + let mia: TestUser; + let nat: TestUser; + let pat: TestUser; + let quin: TestUser; + let realm: Realm; + let general: string; + let invite: RealmInvite; + let moderator: RealmRole; + let admin: RealmRole; + + const everyoneRole = (of: Realm) => { + const role = of.roles.find((candidate) => candidate.isDefault); + if (!role) throw new Error('The realm has no default role.'); + return role; + }; + + async function realmFor(account: TestUser): Promise { + return (await account.agent.get(`/realms/${realm.id}`).expect(200)).body; + } + + async function realmsOf(account: TestUser): Promise { + return (await account.agent.get('/realms').expect(200)).body; + } + + async function membersSeenBy(account: TestUser): Promise { + return (await account.agent.get(`/realms/${realm.id}/members`).expect(200)) + .body; + } + + async function newInvite( + account: TestUser, + body: object = {}, + ): Promise { + return ( + await account.agent + .post(`/realms/${realm.id}/invites`) + .send(body) + .expect(201) + ).body; + } + + const post = (account: TestUser, content: string) => + account.agent.post(`/conversations/${general}/messages`).send({ content }); + + /** Resolves when the socket is told this part of the realm changed. */ + function realmChange(socket: ClientSocket, what: 'details' | 'members') { + return new Promise((resolve, reject) => { + const timer = setTimeout( + () => reject(new Error(`No "${what}" change within 2s`)), + 2000, + ); + const listener = (realmId: string, changed: string) => { + if (realmId !== realm.id || changed !== what) return; + clearTimeout(timer); + socket.off('realm:changed', listener); + resolve(); + }; + socket.on('realm:changed', listener); + }); + } + + /** Resolves with the next message and what came with it. */ + function nextMessage(socket: ClientSocket) { + return new Promise<[Message, { realmId: string | null }]>( + (resolve, reject) => { + const timer = setTimeout( + () => reject(new Error('No message within 2s')), + 2000, + ); + socket.once('message:created', (message, context) => { + clearTimeout(timer); + resolve([message, context]); + }); + }, + ); + } + + beforeAll(async () => { + app = await createTestApp(); + sockets = new TestSockets(await listen(app)); + accounts = new TestAccounts(app, '@realms-e2e.test'); + await accounts.cleanup(); + [olga, mia, nat, pat, quin] = await Promise.all( + ['Olga', 'Mia', 'Nat', 'Pat', 'Quin'].map((name) => + accounts.signUp(name), + ), + ); + }); + + afterAll(async () => { + sockets.closeAll(); + await accounts.cleanup(); + await app.close(); + }); + + it('creates a realm with a first cauldron and an "Everyone" role', async () => { + await olga.agent.post('/realms').send({ name: ' ' }).expect(400); + await olga.agent + .post('/realms') + .send({ name: 'x'.repeat(51) }) + .expect(400); + + const response = await olga.agent + .post('/realms') + .send({ name: ' Moonlit Coven ' }) + .expect(201); + realm = response.body; + general = realm.cauldrons[0].id; + + expect(realm).toMatchObject({ + name: 'Moonlit Coven', + ownerId: olga.id, + memberCount: 1, + permissions: [...REALM_PERMISSIONS], + }); + expect(realm.cauldrons.map((cauldron) => cauldron.name)).toEqual([ + 'general', + ]); + expect(realm.roles).toEqual([ + expect.objectContaining({ + name: 'Everyone', + isDefault: true, + permissions: ['createInvites', 'sendMessages'], + }), + ]); + expect(await realmsOf(olga)).toEqual([ + { + id: realm.id, + name: 'Moonlit Coven', + ownerId: olga.id, + hasUnread: false, + }, + ]); + }); + + it('hides a realm from people who are not in it', async () => { + const path = `/realms/${realm.id}`; + expect(await realmsOf(quin)).toEqual([]); + await quin.agent.get(path).expect(404); + await quin.agent.get(`${path}/members`).expect(404); + await quin.agent.get(`${path}/invites`).expect(404); + await quin.agent.patch(path).send({ name: 'Mine now' }).expect(404); + await quin.agent.post(`${path}/cauldrons`).send({ name: 'x' }).expect(404); + await quin.agent.post(`${path}/invites`).send({}).expect(404); + await quin.agent.delete(path).expect(404); + await quin.agent.get(`/conversations/${general}/messages`).expect(404); + await post(quin, 'let me in').expect(404); + await olga.agent.get('/realms/not-a-uuid').expect(400); + }); + + it('makes invite links that show where they lead', async () => { + invite = await newInvite(olga); + expect(invite).toMatchObject({ + realmId: realm.id, + createdBy: { id: olga.id }, + maxUses: null, + uses: 0, + }); + // A week, unless asked otherwise. + const lifetimeMs = Date.parse(invite.expiresAt ?? '') - Date.now(); + expect(lifetimeMs).toBeGreaterThan(6.9 * 24 * 60 * 60 * 1000); + expect(lifetimeMs).toBeLessThan(7.1 * 24 * 60 * 60 * 1000); + + const preview: InvitePreview = ( + await mia.agent.get(`/invites/${invite.code}`).expect(200) + ).body; + expect(preview).toEqual({ + code: invite.code, + realm: { id: realm.id, name: 'Moonlit Coven', memberCount: 1 }, + isMember: false, + isBanned: false, + }); + + await mia.agent.get('/invites/AAAAAAAAAAAA').expect(404); + await mia.agent.post('/invites/AAAAAAAAAAAA/accept').expect(404); + await mia.agent.get('/invites/nope').expect(400); + await olga.agent + .post(`/realms/${realm.id}/invites`) + .send({ expiresInDays: 2 }) + .expect(400); + }); + + it('lets someone with a link join, once, and tells the realm', async () => { + const olgaSocket = await sockets.connectAs(olga); + // Open before joining: it has to start hearing the realm on its own. + const miaSocket = await sockets.connectAs(mia); + const forOlga = realmChange(olgaSocket, 'members'); + const forMia = realmChange(miaSocket, 'details'); + + const joined = await mia.agent + .post(`/invites/${invite.code}/accept`) + .expect(200); + expect(joined.body).toMatchObject({ + id: realm.id, + memberCount: 2, + permissions: ['createInvites', 'sendMessages'], + }); + await Promise.all([forOlga, forMia]); + + // Using the link again changes nothing and isn't counted. + await mia.agent.post(`/invites/${invite.code}/accept`).expect(200); + const members = await membersSeenBy(mia); + expect(members.map((member) => member.user.id)).toEqual([olga.id, mia.id]); + expect(members[1]).toMatchObject({ roleIds: [] }); + const [listed]: RealmInvite[] = ( + await olga.agent.get(`/realms/${realm.id}/invites`).expect(200) + ).body; + expect(listed).toMatchObject({ code: invite.code, uses: 1 }); + expect( + (await mia.agent.get(`/invites/${invite.code}`).expect(200)).body, + ).toMatchObject({ isMember: true }); + + // The socket that was open all along now gets the realm's messages. + const heard = nextMessage(miaSocket); + const sent = await post(olga, 'welcome, Mia').expect(201); + expect(await heard).toEqual([sent.body, { realmId: realm.id }]); + }); + + it('stops a link working once it is used up or revoked', async () => { + const single = await newInvite(olga, { maxUses: 1, expiresInDays: null }); + expect(single).toMatchObject({ maxUses: 1, expiresAt: null }); + await nat.agent.post(`/invites/${single.code}/accept`).expect(200); + await pat.agent.get(`/invites/${single.code}`).expect(404); + await pat.agent.post(`/invites/${single.code}/accept`).expect(404); + // Whoever is in the realm already is still shown it. + await nat.agent.get(`/invites/${single.code}`).expect(200); + + const revoked = await newInvite(olga); + await olga.agent + .delete(`/realms/${realm.id}/invites/${revoked.code}`) + .expect(204); + await pat.agent.post(`/invites/${revoked.code}/accept`).expect(404); + expect(await realmsOf(pat)).toEqual([]); + + await pat.agent.post(`/invites/${invite.code}/accept`).expect(200); + expect((await realmFor(olga)).memberCount).toBe(4); + }); + + it("shows members their own invites, and the realm's managers all of them", async () => { + const path = `/realms/${realm.id}/invites`; + const natsInvite = await newInvite(nat); + + const seenByNat: RealmInvite[] = (await nat.agent.get(path).expect(200)) + .body; + expect(seenByNat.map((item) => item.code)).toEqual([natsInvite.code]); + const seenByOlga: RealmInvite[] = (await olga.agent.get(path).expect(200)) + .body; + // Newest first; the used-up and revoked ones are gone. + expect(seenByOlga.map((item) => item.code)).toEqual([ + natsInvite.code, + invite.code, + ]); + + await nat.agent.delete(`${path}/${invite.code}`).expect(403); + await nat.agent.delete(`${path}/${natsInvite.code}`).expect(204); + await nat.agent.delete(`${path}/${natsInvite.code}`).expect(404); + }); + + it("carries a cauldron's messages to everyone in the realm", async () => { + const olgaSocket = await sockets.connectAs(olga); + // Connected after joining: the realm comes with the connection. + const natSocket = await sockets.connectAs(nat); + const forOlga = nextMessage(olgaSocket); + const forNat = nextMessage(natSocket); + + const sent = await post(mia, 'double, double').expect(201); + expect(sent.body).toMatchObject({ + conversationId: general, + author: { id: mia.id, name: 'Mia' }, + }); + expect(await forOlga).toEqual([sent.body, { realmId: realm.id }]); + expect(await forNat).toEqual([sent.body, { realmId: realm.id }]); + + const history: MessagePage = ( + await pat.agent.get(`/conversations/${general}/messages`).expect(200) + ).body; + expect(history.items.map((item) => item.content)).toEqual([ + 'double, double', + 'welcome, Mia', + ]); + }); + + it('keeps cauldrons out of the list of chats', async () => { + const chats: Conversation[] = ( + await mia.agent.get('/conversations').expect(200) + ).body; + expect(chats).toEqual([]); + await mia.agent.get(`/conversations/${general}`).expect(404); + await mia.agent + .patch(`/conversations/${general}`) + .send({ name: 'Ours' }) + .expect(404); + await mia.agent + .delete(`/conversations/${general}/members/${mia.id}`) + .expect(404); + }); + + it('lets only those who manage cauldrons add, rename and delete them', async () => { + const path = `/realms/${realm.id}/cauldrons`; + await nat.agent.post(path).send({ name: 'potions' }).expect(403); + await olga.agent.post(path).send({ name: '' }).expect(400); + + const olgaSocket = await sockets.connectAs(olga); + const natSocket = await sockets.connectAs(nat); + const forNat = realmChange(natSocket, 'details'); + const created = await olga.agent + .post(path) + .send({ name: ' potions ' }) + .expect(201); + expect(created.body).toMatchObject({ name: 'potions' }); + await forNat; + expect( + (await realmFor(nat)).cauldrons.map((cauldron) => cauldron.name), + ).toEqual(['general', 'potions']); + + await nat.agent + .patch(`${path}/${created.body.id}`) + .send({ name: 'mine' }) + .expect(403); + const renamed = await olga.agent + .patch(`${path}/${created.body.id}`) + .send({ name: 'brews' }) + .expect(200); + expect(renamed.body).toEqual({ id: created.body.id, name: 'brews' }); + + // A new cauldron is as open as the first one. + const heard = nextMessage(olgaSocket); + await nat.agent + .post(`/conversations/${created.body.id}/messages`) + .send({ content: 'eye of newt' }) + .expect(201); + expect((await heard)[0]).toMatchObject({ content: 'eye of newt' }); + + await nat.agent.delete(`${path}/${created.body.id}`).expect(403); + await olga.agent.delete(`${path}/${created.body.id}`).expect(204); + await olga.agent.delete(`${path}/${created.body.id}`).expect(404); + await nat.agent + .get(`/conversations/${created.body.id}/messages`) + .expect(404); + // Another realm's owner can't reach into this one by id. + const other = await quin.agent + .post('/realms') + .send({ name: 'Elsewhere' }) + .expect(201); + await quin.agent + .patch(`/realms/${other.body.id}/cauldrons/${general}`) + .send({ name: 'taken' }) + .expect(404); + await quin.agent + .delete(`/realms/${other.body.id}/cauldrons/${general}`) + .expect(404); + await quin.agent.delete(`/realms/${other.body.id}`).expect(204); + }); + + it('gives members the permissions of the roles they hold', async () => { + const roles = `/realms/${realm.id}/roles`; + await nat.agent + .post(roles) + .send({ name: 'Boss', permissions: ['manageRealm'] }) + .expect(403); + await olga.agent + .post(roles) + .send({ name: 'Boss', permissions: ['rule'] }) + .expect(400); + + moderator = ( + await olga.agent + .post(roles) + .send({ + name: 'Moderator', + permissions: ['manageRoles', 'kickMembers'], + }) + .expect(201) + ).body; + admin = ( + await olga.agent + .post(roles) + .send({ + name: 'Admin', + permissions: ['manageRealm', 'manageCauldrons', 'kickMembers'], + }) + .expect(201) + ).body; + expect(moderator).toMatchObject({ name: 'Moderator', isDefault: false }); + + const miaSocket = await sockets.connectAs(mia); + const natSocket = await sockets.connectAs(nat); + const forMia = realmChange(miaSocket, 'details'); + const forNat = realmChange(natSocket, 'members'); + const updated = await olga.agent + .put(`/realms/${realm.id}/members/${mia.id}/roles`) + .send({ roleIds: [moderator.id] }) + .expect(200); + expect(updated.body).toMatchObject({ + user: { id: mia.id }, + roleIds: [moderator.id], + }); + await Promise.all([forMia, forNat]); + await olga.agent + .put(`/realms/${realm.id}/members/${pat.id}/roles`) + .send({ roleIds: [admin.id] }) + .expect(200); + + expect((await realmFor(mia)).permissions).toEqual([ + 'manageRoles', + 'kickMembers', + 'createInvites', + 'sendMessages', + ]); + expect((await realmFor(nat)).permissions).toEqual([ + 'createInvites', + 'sendMessages', + ]); + expect((await realmFor(nat)).roles.map((role) => role.name)).toEqual([ + 'Everyone', + 'Moderator', + 'Admin', + ]); + // What a role allows shows at once: Pat may now rename the realm. + await pat.agent + .patch(`/realms/${realm.id}`) + .send({ name: 'Moonlit Coven' }) + .expect(200); + await mia.agent + .patch(`/realms/${realm.id}`) + .send({ name: 'Mia’s' }) + .expect(403); + }); + + it("doesn't let anyone hand out more than they can do themselves", async () => { + const roles = `/realms/${realm.id}/roles`; + const rolesOf = (member: TestUser) => + `/realms/${realm.id}/members/${member.id}/roles`; + + // Mia manages roles, but can't manage the realm or its cauldrons. + await mia.agent + .post(roles) + .send({ name: 'Usurper', permissions: ['manageRealm'] }) + .expect(403); + await mia.agent + .patch(`${roles}/${moderator.id}`) + .send({ permissions: ['manageRoles', 'kickMembers', 'manageRealm'] }) + .expect(403); + await mia.agent + .patch(`${roles}/${admin.id}`) + .send({ name: 'Nobody' }) + .expect(403); + await mia.agent.delete(`${roles}/${admin.id}`).expect(403); + await mia.agent + .put(rolesOf(mia)) + .send({ roleIds: [moderator.id, admin.id] }) + .expect(403); + // Taking a bigger role away is refused as well. + await mia.agent.put(rolesOf(pat)).send({ roleIds: [] }).expect(403); + await mia.agent + .put(rolesOf(olga)) + .send({ roleIds: [moderator.id] }) + .expect(403); + await nat.agent + .put(rolesOf(nat)) + .send({ roleIds: [moderator.id] }) + .expect(403); + + // Within her own reach she can make, give and delete roles. + const helper: RealmRole = ( + await mia.agent + .post(roles) + .send({ name: 'Helper', permissions: ['kickMembers'] }) + .expect(201) + ).body; + await mia.agent + .put(rolesOf(nat)) + .send({ roleIds: [helper.id] }) + .expect(200); + expect((await realmFor(nat)).permissions).toContain('kickMembers'); + // Leaving Pat's bigger role where it is, is no change to it. + await mia.agent + .put(rolesOf(pat)) + .send({ roleIds: [admin.id, helper.id] }) + .expect(200); + await mia.agent.delete(`${roles}/${helper.id}`).expect(204); + expect((await realmFor(nat)).permissions).not.toContain('kickMembers'); + const patNow = (await membersSeenBy(olga)).find( + (member) => member.user.id === pat.id, + ); + expect(patNow?.roleIds).toEqual([admin.id]); + + await mia.agent + .put(rolesOf(nat)) + .send({ roleIds: [helper.id] }) + .expect(400); + await mia.agent + .put(rolesOf(nat)) + .send({ roleIds: [everyoneRole(realm).id] }) + .expect(400); + await mia.agent + .put(rolesOf(quin)) + .send({ roleIds: [moderator.id] }) + .expect(404); + }); + + it('keeps the "Everyone" role, while letting what it allows change', async () => { + const everyone = `/realms/${realm.id}/roles/${everyoneRole(realm).id}`; + await olga.agent.delete(everyone).expect(400); + await olga.agent.patch(everyone).send({ name: 'Peasants' }).expect(400); + + await olga.agent + .patch(everyone) + .send({ permissions: ['createInvites'] }) + .expect(200); + await post(nat, 'can anyone hear me?').expect(403); + // Reading stays open, and the owner can always post. + await nat.agent.get(`/conversations/${general}/messages`).expect(200); + await post(olga, 'quiet, please').expect(201); + + await olga.agent + .patch(everyone) + .send({ permissions: ['createInvites', 'sendMessages'] }) + .expect(200); + await post(nat, 'thank you').expect(201); + }); + + it('lets moderators remove members, but nobody above them', async () => { + const membersPath = `/realms/${realm.id}/members`; + await nat.agent.delete(`${membersPath}/${mia.id}`).expect(403); + await mia.agent.delete(`${membersPath}/${olga.id}`).expect(403); + // Pat can do things Mia can't. + await mia.agent.delete(`${membersPath}/${pat.id}`).expect(403); + await mia.agent.delete(`${membersPath}/${quin.id}`).expect(404); + + const natSocket = await sockets.connectAs(nat); + const olgaSocket = await sockets.connectAs(olga); + const forNat = realmChange(natSocket, 'details'); + const forOlga = realmChange(olgaSocket, 'members'); + await mia.agent.delete(`${membersPath}/${nat.id}`).expect(204); + await Promise.all([forNat, forOlga]); + + expect(await realmsOf(nat)).toEqual([]); + await nat.agent.get(`/realms/${realm.id}`).expect(404); + await nat.agent.get(`/conversations/${general}/messages`).expect(404); + await post(nat, 'still here?').expect(404); + + let natHeard = false; + natSocket.on('message:created', () => { + natHeard = true; + }); + const heard = nextMessage(olgaSocket); + await post(mia, 'members only').expect(201); + await heard; + expect(natHeard).toBe(false); + + // Messages of someone who was removed stay, with their name. + const history: MessagePage = ( + await olga.agent.get(`/conversations/${general}/messages`).expect(200) + ).body; + expect(history.items).toContainEqual( + expect.objectContaining({ + content: 'thank you', + author: expect.objectContaining({ id: nat.id, name: 'Nat' }), + }), + ); + }); + + it('lets members leave, but not the owner', async () => { + const membersPath = `/realms/${realm.id}/members`; + await olga.agent.delete(`${membersPath}/${olga.id}`).expect(400); + + await mia.agent.delete(`${membersPath}/${mia.id}`).expect(204); + expect(await realmsOf(mia)).toEqual([]); + const members = await membersSeenBy(olga); + expect(members.map((member) => member.user.id)).toEqual([olga.id, pat.id]); + + // Coming back with a link starts from nothing: the old roles are gone. + await mia.agent.post(`/invites/${invite.code}/accept`).expect(200); + expect((await realmFor(mia)).permissions).toEqual([ + 'createInvites', + 'sendMessages', + ]); + }); + + it(`holds a realm to ${REALM_MAX_ROLES} roles`, async () => { + const roles = `/realms/${realm.id}/roles`; + const existing = (await realmFor(olga)).roles.length; + for (let index = existing; index < REALM_MAX_ROLES; index += 1) { + await olga.agent + .post(roles) + .send({ name: `Role ${index}`, permissions: [] }) + .expect(201); + } + await olga.agent + .post(roles) + .send({ name: 'One too many', permissions: [] }) + .expect(409); + expect((await realmFor(olga)).roles).toHaveLength(REALM_MAX_ROLES); + }); + + it('lets only the owner delete the realm, with everything in it', async () => { + // Pat manages the realm, which still isn't owning it. + await pat.agent.delete(`/realms/${realm.id}`).expect(403); + + const patSocket = await sockets.connectAs(pat); + const forPat = realmChange(patSocket, 'details'); + await olga.agent.delete(`/realms/${realm.id}`).expect(204); + await forPat; + + for (const account of [olga, mia, pat]) { + expect(await realmsOf(account)).toEqual([]); + await account.agent.get(`/realms/${realm.id}`).expect(404); + await account.agent.get(`/conversations/${general}/messages`).expect(404); + } + await quin.agent.get(`/invites/${invite.code}`).expect(404); + await quin.agent.post(`/invites/${invite.code}/accept`).expect(404); + }); +}); diff --git a/apps/api/test/users.e2e-spec.ts b/apps/api/test/users.e2e-spec.ts new file mode 100644 index 0000000..60d929e --- /dev/null +++ b/apps/api/test/users.e2e-spec.ts @@ -0,0 +1,120 @@ +import request from 'supertest'; +import { + createTestApp, + TestAccounts, + type TestApp, + type TestUser, +} from './helpers'; + +describe('Users (e2e)', () => { + let app: TestApp; + let accounts: TestAccounts; + + beforeAll(async () => { + app = await createTestApp(); + accounts = new TestAccounts(app, '@users-e2e.test'); + await accounts.cleanup(); + }); + + afterAll(async () => { + await accounts.cleanup(); + await app.close(); + }); + + it('GET /users/me requires a session', () => { + return request(app.getHttpServer()).get('/users/me').expect(401); + }); + + it('refuses to sign up without a username', async () => { + const agent = request.agent(app.getHttpServer()); + const response = await accounts.requestSignUp(agent, 'Nouser'); + expect(response.status).toBe(400); + expect(response.body.message).toBe('Username is required.'); + }); + + it('refuses to sign up with an invalid username', async () => { + const agent = request.agent(app.getHttpServer()); + await accounts.requestSignUp(agent, 'Badname', 'not valid!').expect(400); + }); + + describe('with two accounts', () => { + let alice: TestUser; + let bob: TestUser; + + beforeAll(async () => { + alice = await accounts.signUp('Alice'); + bob = await accounts.signUp('Bob'); + }); + + it('returns the own profile with a lower-cased username', async () => { + const response = await alice.agent.get('/users/me').expect(200); + expect(response.body).toEqual({ + id: alice.id, + username: alice.username, + name: 'Alice', + bio: null, + image: null, + email: accounts.emailOf('Alice'), + createdAt: expect.any(String), + }); + }); + + it('lower-cases a username on update', async () => { + const response = await bob.agent + .patch('/users/me') + .send({ username: bob.username.toUpperCase() }) + .expect(200); + expect(response.body.username).toBe(bob.username); + }); + + it('updates only the fields sent', async () => { + const response = await alice.agent + .patch('/users/me') + .send({ bio: ' Brewing something. ' }) + .expect(200); + expect(response.body).toMatchObject({ + name: 'Alice', + bio: 'Brewing something.', + }); + }); + + it('clears the bio when it is blank', async () => { + const response = await alice.agent + .patch('/users/me') + .send({ bio: ' ' }) + .expect(200); + expect(response.body.bio).toBeNull(); + }); + + it('rejects an invalid body', async () => { + await alice.agent.patch('/users/me').send({ name: '' }).expect(400); + await alice.agent + .patch('/users/me') + .send({ username: 'no spaces allowed' }) + .expect(400); + }); + + it('answers 409 for a username someone else has', async () => { + const response = await bob.agent + .patch('/users/me') + .send({ username: alice.username }) + .expect(409); + expect(response.body.message).toBe('Username is already taken.'); + }); + + it('shows a public profile without the email', async () => { + const response = await bob.agent + .get(`/users/${alice.username}`) + .expect(200); + expect(response.body).toMatchObject({ + username: alice.username, + name: 'Alice', + }); + expect(response.body).not.toHaveProperty('email'); + }); + + it('answers 404 for an unknown username', () => { + return bob.agent.get('/users/nobody_by_this_name').expect(404); + }); + }); +}); diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json index 1d5deef..8ee1406 100644 --- a/apps/api/tsconfig.json +++ b/apps/api/tsconfig.json @@ -4,7 +4,6 @@ "moduleResolution": "bundler", "esModuleInterop": true, "isolatedModules": true, - "declaration": true, "removeComments": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, diff --git a/apps/api/vitest.config.e2e.ts b/apps/api/vitest.config.e2e.ts index d0cf949..bfc7cb2 100644 --- a/apps/api/vitest.config.e2e.ts +++ b/apps/api/vitest.config.e2e.ts @@ -6,5 +6,17 @@ export default defineConfig({ globals: true, root: './', include: ['**/*.e2e-spec.ts'], + env: { + // Specs call the API far faster than a person would; the spec that + // covers the limits switches them back on for itself. + RATE_LIMIT: 'false', + // Uploaded files stay in memory, away from the folder development uses. + STORAGE_DRIVER: 'memory', + // Calls are switched on, but no media server is ever contacted: the + // spec that covers calls puts a stand-in in its place. + LIVEKIT_URL: 'ws://livekit.invalid', + LIVEKIT_API_KEY: 'e2e-key', + LIVEKIT_API_SECRET: 'e2e-secret-0123456789-0123456789-0123', + }, }, }); diff --git a/apps/web/.env.example b/apps/web/.env.example new file mode 100644 index 0000000..84c1f13 --- /dev/null +++ b/apps/web/.env.example @@ -0,0 +1,2 @@ +# URL of the API (apps/api). +VITE_API_URL=http://localhost:3001 diff --git a/apps/web/package.json b/apps/web/package.json index 7cb2907..1533046 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -8,20 +8,29 @@ "generate-routes": "tsr generate", "build": "vite build", "preview": "vite preview", + "start": "srvx --prod -s ../client dist/server/server.js", "lint": "oxlint", "format": "prettier --write \"**/*.{ts,tsx}\"", "typecheck": "tsc --noEmit" }, "dependencies": { + "@livekit/components-react": "^2.9.26", + "@repo/contracts": "workspace:*", "@repo/ui": "workspace:*", "@tailwindcss/vite": "^4", "@tanstack/react-devtools": "latest", + "@tanstack/react-query": "^5.108.4", "@tanstack/react-router": "latest", "@tanstack/react-router-devtools": "latest", + "@tanstack/react-router-ssr-query": "^1.167.3", "@tanstack/react-start": "latest", + "better-auth": "^1.7.29", + "livekit-client": "^2.26.0", "lucide-react": "^1.84.0", "react": "^19.3.1", "react-dom": "^19.3.1", + "socket.io-client": "^4.8.4", + "srvx": "^1.0.6", "tailwindcss": "^4" }, "devDependencies": { diff --git a/apps/web/src/components/auth-form.tsx b/apps/web/src/components/auth-form.tsx new file mode 100644 index 0000000..c1e0ffb --- /dev/null +++ b/apps/web/src/components/auth-form.tsx @@ -0,0 +1,215 @@ +import { useEffect, useState } from 'react'; +import { Link, useNavigate } from '@tanstack/react-router'; +import { + NAME_MAX_LENGTH, + USERNAME_MAX_LENGTH, + USERNAME_MIN_LENGTH, + usernameSchema, +} from '@repo/contracts'; +import { Alert, AlertDescription } from '@repo/ui/components/alert'; +import { Button } from '@repo/ui/components/button'; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from '@repo/ui/components/card'; +import { + Field, + FieldDescription, + FieldGroup, + FieldLabel, +} from '@repo/ui/components/field'; +import { Input } from '@repo/ui/components/input'; +import { Spinner } from '@repo/ui/components/spinner'; +import { authClient } from '@/lib/auth-client'; +import { DEFAULT_SIGNED_IN_PATH, toSitePath } from '@/lib/redirect'; + +const MIN_PASSWORD_LENGTH = 8; + +const copy = { + login: { + title: 'Log in', + description: 'Enter your email and password to continue.', + submit: 'Log in', + fallbackError: 'Could not log in. Please try again.', + }, + register: { + title: 'Create an account', + description: 'Enter your details to get started.', + submit: 'Create account', + fallbackError: 'Could not create the account. Please try again.', + }, +}; + +interface AuthFormProps { + mode: 'login' | 'register'; + /** A path on this site to open after signing in. */ + redirectTo?: string; +} + +export function AuthForm({ mode, redirectTo: requested }: AuthFormProps) { + // Checked again here, so no caller can pass an off-site address through. + const redirectTo = toSitePath(requested) ?? DEFAULT_SIGNED_IN_PATH; + const navigate = useNavigate(); + const { data: session } = authClient.useSession(); + const [error, setError] = useState(null); + const [isSubmitting, setIsSubmitting] = useState(false); + const text = copy[mode]; + // Keeps the return path when switching between the two forms. + const linkSearch = { redirect: toSitePath(requested) }; + + // Already signed in (or just signed in): there is nothing to do here. + const isSignedIn = Boolean(session); + useEffect(() => { + if (isSignedIn) void navigate({ href: redirectTo, replace: true }); + }, [isSignedIn, navigate, redirectTo]); + if (isSignedIn) return null; + + async function handleSubmit(event: React.FormEvent) { + event.preventDefault(); + const form = new FormData(event.currentTarget); + const field = (name: string) => { + const value = form.get(name); + return typeof value === 'string' ? value : ''; + }; + const email = field('email'); + const password = field('password'); + + let username = ''; + if (mode === 'register') { + const parsed = usernameSchema.safeParse(field('username')); + if (!parsed.success) { + setError(parsed.error.issues[0]?.message ?? text.fallbackError); + return; + } + username = parsed.data; + } + + setError(null); + setIsSubmitting(true); + const result = + mode === 'login' + ? await authClient.signIn.email({ email, password }) + : await authClient.signUp.email({ + name: field('name'), + username, + email, + password, + }); + + if (result.error) { + setError(result.error.message ?? text.fallbackError); + setIsSubmitting(false); + return; + } + await navigate({ href: redirectTo, replace: true }); + } + + return ( +
+ + + {text.title} + {text.description} + + +
+ + {mode === 'register' && ( + <> + + Name + + + + Username + + + How friends find you. Letters, numbers, underscores and + dots. + + + + )} + + Email + + + + Password + + {mode === 'register' && ( + + At least {MIN_PASSWORD_LENGTH} characters. + + )} + + {error && ( + + {error} + + )} + + + + {mode === 'login' ? ( + <> + Don't have an account?{' '} + + Register + + + ) : ( + <> + Already have an account?{' '} + + Log in + + + )} + + + +
+
+
+
+ ); +} diff --git a/apps/web/src/components/ban-dialog.tsx b/apps/web/src/components/ban-dialog.tsx new file mode 100644 index 0000000..1cbbe96 --- /dev/null +++ b/apps/web/src/components/ban-dialog.tsx @@ -0,0 +1,117 @@ +import { useState } from 'react'; +import { BAN_REASON_MAX_LENGTH } from '@repo/contracts'; +import type { UserSummary } from '@repo/contracts'; +import { Button } from '@repo/ui/components/button'; +import { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from '@repo/ui/components/dialog'; +import { Field, FieldDescription, FieldLabel } from '@repo/ui/components/field'; +import { Input } from '@repo/ui/components/input'; +import { Spinner } from '@repo/ui/components/spinner'; +import type { TriggerButtonProps } from '@/components/trigger-button'; +import { errorMessage } from '@/lib/errors'; +import { useBanMember } from '@/lib/realms'; + +interface BanDialogProps extends TriggerButtonProps { + realmId: string; + realmName: string; + /** The member to ban. */ + user: UserSummary; +} + +/** A button that asks why, then bans a member from a realm. */ +export function BanDialog({ + realmId, + realmName, + user, + children, + ...button +}: BanDialogProps) { + const [open, setOpen] = useState(false); + + return ( + + }>{children} + + {/* Mounted only while open, so each opening starts empty. */} + setOpen(false)} + /> + + + ); +} + +function BanForm({ + realmId, + realmName, + user, + onDone, +}: { + realmId: string; + realmName: string; + user: UserSummary; + onDone: () => void; +}) { + const ban = useBanMember(realmId); + const [reason, setReason] = useState(''); + + return ( +
{ + event.preventDefault(); + // The row this dialog hangs from goes once the ban is known, which + // may be before the answer; closing first is harmless either way. + ban.mutate({ userId: user.id, reason }, { onSuccess: onDone }); + }} + > + + + Ban {user.name} from {realmName}? + + + They are removed and no invite link lets them back in until the ban is + lifted. Their messages stay. + + + + Reason (optional) + setReason(event.target.value)} + /> + + Shown to those who can manage bans, not to {user.name}. + + + {ban.isError && ( +

+ {errorMessage(ban.error)} +

+ )} + + }> + Cancel + + + +
+ ); +} diff --git a/apps/web/src/components/brand.tsx b/apps/web/src/components/brand.tsx new file mode 100644 index 0000000..002dfe0 --- /dev/null +++ b/apps/web/src/components/brand.tsx @@ -0,0 +1,14 @@ +import { Zap } from 'lucide-react'; +import { site } from '@/lib/site'; + +/** The logo mark and site name. */ +export function Brand() { + return ( + + + + {site.name} + + ); +} diff --git a/apps/web/src/components/call-button.tsx b/apps/web/src/components/call-button.tsx new file mode 100644 index 0000000..3d12e38 --- /dev/null +++ b/apps/web/src/components/call-button.tsx @@ -0,0 +1,77 @@ +import { Phone, PhoneOff } from 'lucide-react'; +import { Button } from '@repo/ui/components/button'; +import { useCalls } from '@/components/call-provider'; +import type { CallPlace } from '@/components/call-provider'; +import { UserAvatar } from '@/components/user-avatar'; +import { callSummary, useCallIn, useCallsEnabled } from '@/lib/calls'; + +/** How many faces of a call to show before "+2". */ +const MAX_FACES = 3; + +interface CallButtonProps { + place: CallPlace; + /** Whether the user may start or join a call here. */ + canJoin: boolean; +} + +/** + * For a page's header: starts a call there, or shows who is in the one + * going on and joins it. Renders nothing when the server has no calls. + */ +export function CallButton({ place, canJoin }: CallButtonProps) { + const isEnabled = useCallsEnabled(); + const call = useCallIn(place.conversationId); + const { active, join, leave } = useCalls(); + if (!isEnabled) return null; + + if (active?.place.conversationId === place.conversationId) { + return ( + + ); + } + + if (!call) { + if (!canJoin) return null; + return ( + + ); + } + + const faces = call.participants.slice(0, MAX_FACES); + const more = call.participants.length - faces.length; + return ( +
+

{callSummary(call)}

+
+ {faces.map((person) => ( + + ))} + {more > 0 && ( + +{more} + )} +
+ {canJoin && ( + + )} +
+ ); +} diff --git a/apps/web/src/components/call-mark.tsx b/apps/web/src/components/call-mark.tsx new file mode 100644 index 0000000..6ecfe19 --- /dev/null +++ b/apps/web/src/components/call-mark.tsx @@ -0,0 +1,12 @@ +import { Phone } from 'lucide-react'; +import { cn } from '@repo/ui/lib/utils'; + +/** A small mark for "a call is going on here", for the lists. */ +export function CallMark({ className }: { className?: string }) { + return ( + + + ); +} diff --git a/apps/web/src/components/call-panel.tsx b/apps/web/src/components/call-panel.tsx new file mode 100644 index 0000000..6cf74fb --- /dev/null +++ b/apps/web/src/components/call-panel.tsx @@ -0,0 +1,345 @@ +import { useState } from 'react'; +import { useQuery } from '@tanstack/react-query'; +import { Link } from '@tanstack/react-router'; +import { + RoomAudioRenderer, + RoomContext, + StartAudio, + VideoTrack, + useIsMuted, + useIsSpeaking, + useLocalParticipant, + useParticipantTracks, + useParticipants, + useTrackToggle, + useTracks, +} from '@livekit/components-react'; +import type { TrackReference } from '@livekit/components-react'; +import { Track } from 'livekit-client'; +import type { Participant } from 'livekit-client'; +import { + Maximize2, + Mic, + MicOff, + Minimize2, + MonitorUp, + MonitorX, + Phone, + PhoneOff, + Video, + VideoOff, +} from 'lucide-react'; +import { Button, buttonVariants } from '@repo/ui/components/button'; +import { Spinner } from '@repo/ui/components/spinner'; +import { toast } from '@repo/ui/components/toast'; +import { cn } from '@repo/ui/lib/utils'; +import { useCalls } from '@/components/call-provider'; +import type { ActiveCall, CallPlace } from '@/components/call-provider'; +import { UserAvatar } from '@/components/user-avatar'; +import { callsQuery } from '@/lib/calls'; + +/** + * The call the user is in, docked above whatever page they are on: who is + * there, their video and shared screens, and the controls. Renders nothing + * outside a call. + */ +export function CallPanel() { + const { active, leave } = useCalls(); + const [isLarge, setIsLarge] = useState(false); + if (!active) return null; + + return ( +
+
+
+ + {active.status === 'connecting' ? ( +
+ +
+ ) : ( + // The key: LiveKit's hooks keep what they learned from one room. + + + + + )} + +
+ {active.status === 'connected' && ( + + + + )} + +
+
+ ); +} + +function PlaceLink({ place }: { place: CallPlace }) { + const className = 'font-medium hover:underline'; + return place.realmId ? ( + + {place.title} + + ) : ( + + {place.title} + + ); +} + +/** Everyone in the call, and before them the screens being shared. */ +function Stage({ call, isLarge }: { call: ActiveCall; isLarge: boolean }) { + const participants = useParticipants(); + const screens = useTracks([Track.Source.ScreenShare]); + // The API's word on who these people are: their pictures come from it. + const { data } = useQuery(callsQuery); + const people = data?.calls.find( + (item) => item.conversationId === call.place.conversationId, + )?.participants; + + return ( +
    + {screens.map((screen) => ( + + + + ))} + {participants.map((participant) => ( + person.id === participant.identity) + ?.image ?? null + } + isLarge={isLarge} + /> + ))} +
+ ); +} + +function ParticipantTile({ + participant, + image, + isLarge, +}: { + participant: Participant; + image: string | null; + isLarge: boolean; +}) { + const name = nameOf(participant); + const isSpeaking = useIsSpeaking(participant); + const isMuted = useIsMuted({ + participant, + source: Track.Source.Microphone, + }); + const [camera] = useParticipantTracks( + [Track.Source.Camera], + participant.identity, + ) as (TrackReference | undefined)[]; + const hasVideo = camera !== undefined && !camera.publication.isMuted; + + return ( + + + ); +} + +function Tile({ + label, + isLarge, + isSpeaking = false, + badge, + children, +}: { + label: string; + isLarge: boolean; + isSpeaking?: boolean; + /** Shown beside the name. */ + badge?: React.ReactNode; + children: React.ReactNode; +}) { + return ( +
  • + {children} +

    + {label} + {badge} +

    +
  • + ); +} + +function Controls() { + const { localParticipant } = useLocalParticipant(); + const onDeviceError = (what: string) => () => + toast.add({ + title: `Couldn’t use your ${what}. Check the browser’s permission for this site.`, + type: 'error', + }); + const microphone = useTrackToggle({ + source: Track.Source.Microphone, + onDeviceError: onDeviceError('microphone'), + }); + const camera = useTrackToggle({ + source: Track.Source.Camera, + onDeviceError: onDeviceError('camera'), + }); + const screen = useTrackToggle({ + source: Track.Source.ScreenShare, + // Closing the browser's own picker is a "no", not a fault. + onDeviceError: () => undefined, + }); + // Phones have no screens to share this way. + const canShareScreen = + typeof navigator.mediaDevices.getDisplayMedia === 'function'; + + return ( + <> + + + + {canShareScreen && ( + + )} + + {localParticipant.isMicrophoneEnabled + ? 'Your microphone is on.' + : 'Your microphone is off.'} + + + ); +} + +/** The display name the API put in the participant's token. */ +function nameOf(participant: Participant): string { + return participant.name || 'Someone'; +} diff --git a/apps/web/src/components/call-provider.tsx b/apps/web/src/components/call-provider.tsx new file mode 100644 index 0000000..d253474 --- /dev/null +++ b/apps/web/src/components/call-provider.tsx @@ -0,0 +1,147 @@ +import { + createContext, + use, + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from 'react'; +import { DisconnectReason, Room, RoomEvent } from 'livekit-client'; +import { toast } from '@repo/ui/components/toast'; +import { ApiError } from '@/lib/api'; +import { requestCallAccess, stopRinging } from '@/lib/calls'; + +/** Where a call is: a conversation, or a cauldron of a realm. */ +export interface CallPlace { + conversationId: string; + /** Set for a cauldron. */ + realmId: string | null; + /** What the place is called, as its own page shows it. */ + title: string; +} + +/** The call this tab is in. */ +export interface ActiveCall { + place: CallPlace; + /** The connection to the media server; LiveKit's hooks read from it. */ + room: Room; + status: 'connecting' | 'connected'; +} + +interface CallContextValue { + /** Nothing when the user isn't in a call. */ + active: ActiveCall | null; + /** Joins the call of a place, leaving the current one first. */ + join: (place: CallPlace) => void; + leave: () => void; +} + +const CallContext = createContext(null); + +export function useCalls(): CallContextValue { + const value = use(CallContext); + if (!value) throw new Error('useCalls needs a CallProvider above it.'); + return value; +} + +/** + * Holds the call the user is in, above the pages, so that moving around + * the app doesn't hang up. One call at a time: joining another leaves the + * first. + */ +export function CallProvider({ children }: { children: React.ReactNode }) { + const [active, setActive] = useState(null); + // The same call for the callbacks below, which outlive the render that + // made them and need to know whether their call is still the one. + const current = useRef<{ room: Room; conversationId: string } | null>(null); + + const leave = useCallback(() => { + const room = current.current?.room; + current.current = null; + setActive(null); + void room?.disconnect(); + }, []); + + const join = useCallback((place: CallPlace) => { + stopRinging(place.conversationId); + if (current.current?.conversationId === place.conversationId) return; + void current.current?.room.disconnect(); + + // Send each viewer only the video sizes they show, and none they don't. + const room = new Room({ adaptiveStream: true, dynacast: true }); + const isCurrent = () => current.current?.room === room; + const end = (message?: string, type: 'info' | 'error' = 'error') => { + if (!isCurrent()) return; + current.current = null; + setActive(null); + if (message) toast.add({ title: message, type }); + }; + current.current = { room, conversationId: place.conversationId }; + setActive({ place, room, status: 'connecting' }); + + // Only reached for a call that is still the current one: leaving and + // switching clear `current` before they disconnect. + room.on(RoomEvent.Disconnected, (reason) => + end(...disconnectNotice(reason)), + ); + + void (async () => { + try { + const access = await requestCallAccess(place.conversationId); + if (!isCurrent()) return; + await room.connect(access.url, access.token); + } catch (error) { + void room.disconnect(); + end( + error instanceof ApiError + ? error.message + : 'Couldn’t connect to the call. Check your connection and try again.', + ); + return; + } + if (!isCurrent()) return; + setActive({ place, room, status: 'connected' }); + try { + await room.localParticipant.setMicrophoneEnabled(true); + } catch { + if (!isCurrent()) return; + toast.add({ + title: + 'Your microphone isn’t available, so you joined muted. Check the browser’s permission for this site.', + type: 'warning', + }); + } + })(); + }, []); + + // Signing out (or anything else that takes the app away) hangs up. + useEffect( + () => () => { + void current.current?.room.disconnect(); + current.current = null; + }, + [], + ); + + const value = useMemo(() => ({ active, join, leave }), [active, join, leave]); + return {children}; +} + +/** What to tell someone whose call ended without them hanging up. */ +function disconnectNotice( + reason: DisconnectReason | undefined, +): [message?: string, type?: 'info' | 'error'] { + switch (reason) { + case DisconnectReason.CLIENT_INITIATED: + return []; + case DisconnectReason.DUPLICATE_IDENTITY: + return ['You joined this call somewhere else, so it ended here.', 'info']; + case DisconnectReason.PARTICIPANT_REMOVED: + return ['You were taken out of the call.', 'info']; + case DisconnectReason.ROOM_DELETED: + return ['The call was ended.', 'info']; + default: + return ['The call was disconnected.', 'error']; + } +} diff --git a/apps/web/src/components/cauldron-dialog.tsx b/apps/web/src/components/cauldron-dialog.tsx new file mode 100644 index 0000000..3590d64 --- /dev/null +++ b/apps/web/src/components/cauldron-dialog.tsx @@ -0,0 +1,127 @@ +import { useState } from 'react'; +import { CAULDRON_NAME_MAX_LENGTH } from '@repo/contracts'; +import type { Cauldron } from '@repo/contracts'; +import { Button } from '@repo/ui/components/button'; +import { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from '@repo/ui/components/dialog'; +import { Field, FieldLabel } from '@repo/ui/components/field'; +import { Input } from '@repo/ui/components/input'; +import { Spinner } from '@repo/ui/components/spinner'; +import type { TriggerButtonProps } from '@/components/trigger-button'; +import { errorMessage } from '@/lib/errors'; +import { useCreateCauldron, useRenameCauldron } from '@/lib/realms'; + +interface CauldronDialogProps extends TriggerButtonProps { + realmId: string; + /** The cauldron to rename; a new one is created without it. */ + cauldron?: Cauldron; + /** Called with a cauldron that was just created. */ + onCreated?: (cauldron: Cauldron) => void; +} + +/** A button that opens the form for naming a new or existing cauldron. */ +export function CauldronDialog({ + realmId, + cauldron, + onCreated, + children, + ...button +}: CauldronDialogProps) { + const [open, setOpen] = useState(false); + + return ( + + }>{children} + + {/* Mounted only while open, so each opening starts from the saved name. */} + { + setOpen(false); + if (created) onCreated?.(created); + }} + /> + + + ); +} + +function CauldronForm({ + realmId, + cauldron, + onDone, +}: { + realmId: string; + cauldron?: Cauldron; + onDone: (created?: Cauldron) => void; +}) { + const create = useCreateCauldron(realmId); + const rename = useRenameCauldron(realmId); + const [name, setName] = useState(cauldron?.name ?? ''); + const failure = create.error ?? rename.error; + const isPending = create.isPending || rename.isPending; + + function handleSubmit(event: React.FormEvent) { + event.preventDefault(); + if (cauldron) { + rename.mutate( + { cauldronId: cauldron.id, name }, + { onSuccess: () => onDone() }, + ); + } else { + create.mutate(name, { onSuccess: onDone }); + } + } + + return ( +
    + + + {cauldron ? 'Rename cauldron' : 'New cauldron'} + + + Everyone in the realm can read a cauldron. + + + + Name + setName(event.target.value)} + /> + + {failure && ( +

    + {errorMessage(failure)} +

    + )} + + }> + Cancel + + + +
    + ); +} diff --git a/apps/web/src/components/chat-view.tsx b/apps/web/src/components/chat-view.tsx new file mode 100644 index 0000000..ddb8efd --- /dev/null +++ b/apps/web/src/components/chat-view.tsx @@ -0,0 +1,181 @@ +import { useEffect, useMemo, useRef } from 'react'; +import { + useSuspenseInfiniteQuery, + useSuspenseQuery, +} from '@tanstack/react-query'; +import type { Message } from '@repo/contracts'; +import { ArrowDown } from 'lucide-react'; +import { Button } from '@repo/ui/components/button'; +import { Composer } from '@/components/composer'; +import { MessageRow } from '@/components/message-row'; +import { + chronological, + messagesQuery, + useDeleteMessage, + useToggleReaction, +} from '@/lib/conversations'; +import { ownProfileQuery } from '@/lib/profile'; +import { + setConversationOnScreen, + useAttentive, + useMarkRead, +} from '@/lib/unread'; +import { useChatScroll } from '@/lib/use-chat-scroll'; + +// Messages from one person within this long are shown as one block. +const GROUP_WINDOW_MS = 5 * 60 * 1000; + +interface ChatViewProps { + /** A conversation's id, or a cauldron's: both hold messages the same way. */ + conversationId: string; + /** What the place is called, for the message box and screen readers. */ + title: string; + /** Shown above the first message once the whole history is loaded. */ + startOfHistory: string; + /** Set when the messages belong to a realm's cauldron: that realm's id. */ + realmId?: string; + /** How many messages here the user hasn't read, as the lists show it. */ + unreadCount: number; + /** Whether the user may add reactions; they can always take theirs back. */ + canReact?: boolean; + /** Whether the user may delete other people's messages here, not only theirs. */ + canModerate?: boolean; + /** Why the user can't post here; shown in place of the message box. */ + blockedNotice?: React.ReactNode; +} + +/** + * The messages of a conversation and the box to write one, filling the space + * below whatever header the page puts above it. The history must be loaded + * (or loading under a Suspense boundary) before this renders. Give it a `key` + * per conversation, so each has its own draft and scroll position. + */ +export function ChatView({ + conversationId, + title, + startOfHistory, + realmId, + unreadCount, + canReact = true, + canModerate = false, + blockedNotice, +}: ChatViewProps) { + const { data: profile } = useSuspenseQuery(ownProfileQuery); + const history = useSuspenseInfiniteQuery(messagesQuery(conversationId)); + const messages = useMemo( + () => chronological(history.data.pages), + [history.data.pages], + ); + const scroll = useChatScroll(messages); + const toggleReaction = useToggleReaction(conversationId, profile.id); + const { mutateAsync: deleteMessage } = useDeleteMessage( + conversationId, + realmId ?? null, + ); + + // While the newest messages are in view, new ones aren't counted as + // unread (see lib/unread) and are marked read below instead. + useEffect(() => { + setConversationOnScreen(conversationId, scroll.isAtEnd); + return () => setConversationOnScreen(conversationId, false); + }, [conversationId, scroll.isAtEnd]); + + const latest = messages.at(-1); + const isAttentive = useAttentive(); + const { mutate: markRead } = useMarkRead(conversationId, realmId ?? null); + // The newest message the API has been told about. Starts at the newest + // one loaded when there is nothing to tell. + const marked = useRef(unreadCount === 0 ? latest?.id : undefined); + useEffect(() => { + if (!latest || latest.id === marked.current) return; + if (!isAttentive || !scroll.isAtEnd) return; + marked.current = latest.id; + // The user's own message moves their marker when it is posted. + if (unreadCount > 0 || latest.author.id !== profile.id) markRead(latest.id); + }, [latest, isAttentive, scroll.isAtEnd, unreadCount, profile.id, markRead]); + + return ( + <> +
    +
    + {/* justify-end: a short conversation sits just above the composer. */} +
    +
    + {history.hasNextPage ? ( + + ) : ( +

    + {startOfHistory} +

    + )} +
    + {messages.map((message, index) => ( + + toggleReaction.mutate({ message: target, emoji }) + : undefined + } + onDelete={ + canModerate || message.author.id === profile.id + ? (target) => deleteMessage(target.id) + : undefined + } + /> + ))} +
    +
    + {!scroll.isAtEnd && ( + + )} +
    + + {blockedNotice ? ( +

    + {blockedNotice} +

    + ) : ( + + )} + + ); +} + +function startsGroup(message: Message, previous: Message | undefined) { + return ( + !previous || + previous.author.id !== message.author.id || + Date.parse(message.createdAt) - Date.parse(previous.createdAt) > + GROUP_WINDOW_MS + ); +} diff --git a/apps/web/src/components/composer.tsx b/apps/web/src/components/composer.tsx new file mode 100644 index 0000000..932d912 --- /dev/null +++ b/apps/web/src/components/composer.tsx @@ -0,0 +1,310 @@ +import { useEffect, useRef, useState } from 'react'; +import { + MESSAGE_MAX_ATTACHMENTS, + MESSAGE_MAX_LENGTH, + sendMessageSchema, +} from '@repo/contracts'; +import type { Attachment } from '@repo/contracts'; +import { CircleAlert, Paperclip, SendHorizontal, X } from 'lucide-react'; +import { Button } from '@repo/ui/components/button'; +import { Spinner } from '@repo/ui/components/spinner'; +import { Textarea } from '@repo/ui/components/textarea'; +import { + discardAttachment, + fileProblem, + formatFileSize, + uploadAttachment, +} from '@/lib/attachments'; +import { useSendMessage } from '@/lib/conversations'; +import { errorMessage } from '@/lib/errors'; + +/** A file picked for the next message, on its way up or already there. */ +interface PickedFile { + key: number; + file: File; + /** Set once the upload is done; its id goes in the message. */ + attachment?: Attachment; + /** Why the upload failed, in words to show. */ + problem?: string; + /** Stops the upload if the file is removed first. */ + abort: AbortController; +} + +interface ComposerProps { + conversationId: string; + /** The conversation is a realm's cauldron. */ + inRealm: boolean; + /** Who or what the message goes to, for the placeholder. */ + recipient: string; + /** Called as a message goes out, before it shows up in the list. */ + onSend: () => void; +} + +/** + * The box a message is written in, with the files picked for it. Files + * start uploading as soon as they are picked (with the button, by pasting + * or by dropping them on the page) and go out with the next message. + */ +export function Composer({ + conversationId, + inRealm, + recipient, + onSend, +}: ComposerProps) { + const sendMessage = useSendMessage(conversationId, inRealm); + const [draft, setDraft] = useState(''); + const [files, setFiles] = useState([]); + const [error, setError] = useState(null); + const fileInput = useRef(null); + const nextKey = useRef(0); + // Uploads go one after another, so files keep the order they were picked in. + const queue = useRef>(Promise.resolve()); + const picked = useRef(files); + useEffect(() => { + picked.current = files; + }, [files]); + + // Leaving the chat stops what is still going up. + useEffect( + () => () => { + for (const file of picked.current) file.abort.abort(); + }, + [], + ); + + // Files dropped anywhere on the page are attached, not opened in place + // of the app. Set up again on each render, so it sees the current files. + useEffect(() => { + const allow = (event: DragEvent) => { + if (event.dataTransfer?.types.includes('Files')) event.preventDefault(); + }; + const take = (event: DragEvent) => { + const dropped = event.dataTransfer?.files; + if (!dropped || dropped.length === 0) return; + event.preventDefault(); + addFiles([...dropped]); + }; + window.addEventListener('dragover', allow); + window.addEventListener('drop', take); + return () => { + window.removeEventListener('dragover', allow); + window.removeEventListener('drop', take); + }; + }); + + function update(key: number, change: Partial) { + setFiles((current) => + current.map((item) => (item.key === key ? { ...item, ...change } : item)), + ); + } + + function addFiles(chosen: File[]) { + if (chosen.length === 0) return; + setError(null); + const room = MESSAGE_MAX_ATTACHMENTS - files.length; + if (chosen.length > room) { + setError(`A message can have at most ${MESSAGE_MAX_ATTACHMENTS} files.`); + } + const added: PickedFile[] = []; + for (const file of chosen.slice(0, Math.max(room, 0))) { + const problem = fileProblem(file); + if (problem) { + setError(problem); + continue; + } + added.push({ + key: nextKey.current++, + file, + abort: new AbortController(), + }); + } + setFiles((current) => [...current, ...added]); + for (const item of added) { + // Asked afresh each time: the file may be removed at any point. + const isRemoved = () => item.abort.signal.aborted; + queue.current = queue.current.then(async () => { + if (isRemoved()) return; + try { + const attachment = await uploadAttachment( + item.file, + item.abort.signal, + ); + // Removed while the last bytes went up: the API can forget it. + if (isRemoved()) { + void discardAttachment(attachment.id).catch(() => undefined); + } else { + update(item.key, { attachment }); + } + } catch (failure) { + if (isRemoved()) return; + update(item.key, { + problem: errorMessage(failure, 'The upload failed.'), + }); + } + }); + } + } + + function remove(item: PickedFile) { + item.abort.abort(); + if (item.attachment) { + void discardAttachment(item.attachment.id).catch(() => undefined); + } + setFiles((current) => current.filter((other) => other.key !== item.key)); + } + + const isUploading = files.some((item) => !item.attachment && !item.problem); + const ready = files.flatMap((item) => + item.attachment ? [item.attachment.id] : [], + ); + const parsed = sendMessageSchema.safeParse({ + content: draft, + attachmentIds: ready, + }); + // Nothing goes out while a file is still on its way. + const canSend = parsed.success && !isUploading; + + function send() { + if (!parsed.success || isUploading) return; + const sent = { draft, files }; + setDraft(''); + setFiles([]); + setError(null); + onSend(); + sendMessage.mutate(parsed.data, { + onError: (failure) => { + // Give it all back, unless something new was started meanwhile. + setDraft((current) => (current === '' ? sent.draft : current)); + setFiles((current) => (current.length === 0 ? sent.files : current)); + setError( + errorMessage( + failure, + 'Could not send the message. Please try again.', + ), + ); + }, + }); + } + + return ( +
    { + event.preventDefault(); + send(); + }} + > + {error && ( +

    + {error} +

    + )} + {files.length > 0 && ( +
      + {files.map((item) => ( +
    • + {item.problem ? ( +
    • + ))} +
    + )} +
    + { + addFiles([...(event.target.files ?? [])]); + // So picking the same file again is noticed. + event.target.value = ''; + }} + /> + +