update
CI / Lint, types, build, tests (push) Canceled after 0s
CI / Docker images build (push) Canceled after 0s

This commit is contained in:
olehhapuk
2026-12-03 10:53:09 +02:00
parent f8de87955b
commit 98b2e0ce4b
182 changed files with 24134 additions and 288 deletions
+35
View File
@@ -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
+1 -1
View File
@@ -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.
@@ -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");
@@ -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"
}
}
]
}
@@ -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;
File diff suppressed because it is too large Load Diff
@@ -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;
@@ -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"
]
}
}
]
}
@@ -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;
File diff suppressed because it is too large Load Diff
@@ -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;
@@ -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"
}
}
]
}
@@ -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;
@@ -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"
}
}
]
}
+17 -2
View File
@@ -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",
+1 -12
View File
@@ -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<Auth>) {
return session.user;
}
}
+72 -13
View File
@@ -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<Env, true>) => ({
drizzle,
connection: config.getOrThrow<string>('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<Env, true>,
realtime: RealtimeService,
redis: Redis,
) => ({
auth: createAuth(db, {
secret: config.getOrThrow<string>('BETTER_AUTH_SECRET'),
baseURL: config.getOrThrow<string>('BETTER_AUTH_URL'),
trustedOrigins: (config.get<string>('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;
}
@@ -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);
}
}
}
@@ -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<Auth>,
@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<Auth>,
@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<Auth>,
@Param('id', { schema: attachmentIdSchema }) id: string,
) {
return this.attachments.remove(session.user.id, id);
}
}
@@ -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 {}
@@ -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<AttachmentRow> {
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<number> {
const [row] = await this.db
.select({ count: sql<number>`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<AttachmentRow[]> {
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<boolean> {
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<string[]> {
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);
}
}
@@ -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<AttachmentsRepository['deleteAbandoned']>()
.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);
});
});
@@ -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<AttachmentUpload> {
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<void> {
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<string> {
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<void> {
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<number> {
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;
}
}
}
+114 -1
View File
@@ -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<string, unknown> | 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 } } };
}
}),
},
});
}
+60
View File
@@ -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<Env, true>) {
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<string[]> {
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<string[]> {
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<void> {
await ignoreMissing(this.client?.removeParticipant(room, identity));
}
/** Ends a call for everyone in it; fine if there was none. */
async close(room: string): Promise<void> {
await ignoreMissing(this.client?.deleteRoom(room));
}
}
async function ignoreMissing(request: Promise<void> | undefined) {
try {
await request;
} catch (error) {
if (error instanceof ServerError && error.status === 404) return;
throw error;
}
}
+75
View File
@@ -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<Auth>) {
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<Auth>,
@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<string> {
const chunks: Buffer[] = [];
let size = 0;
for await (const chunk of req as AsyncIterable<Buffer>) {
size += chunk.length;
if (size > WEBHOOK_MAX_BYTES) throw new PayloadTooLargeException();
chunks.push(chunk);
}
return Buffer.concat(chunks).toString('utf8');
}
+34
View File
@@ -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 {}
+46
View File
@@ -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;
}
}
}
+115
View File
@@ -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<Env> = {
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<Env>) {
const live = new Map<string, string[]>();
const remembered = new Map<string, CallState>();
const emitToUsers = vi.fn<RealtimeService['emitToUsers']>();
const service = new CallsService(
{
get: (name: keyof Env) => env[name],
} as unknown as ConfigService<Env, true>,
{} 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);
});
});
+327
View File
@@ -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<string, Promise<void>>();
constructor(
config: ConfigService<Env, true>,
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<CallsOverview> {
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<CallAccess> {
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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
if (!this.enabled) return;
const id = await this.conversations.findDirectId(userId, otherUserId);
if (id) await this.end([id]);
}
private async syncNow(conversationId: string): Promise<void> {
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<Call> {
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<void>) {
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]);
}
+66
View File
@@ -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<typeof callStateSchema>;
// 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<CallState | undefined> {
return parse(await this.redis.hget(KEY, conversationId));
}
/** The calls among these conversations, by conversation id. */
async getMany(conversationIds: string[]): Promise<Map<string, CallState>> {
const calls = new Map<string, CallState>();
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<string[]> {
return this.redis.hkeys(KEY);
}
async set(conversationId: string, state: CallState): Promise<void> {
await this.redis.hset(KEY, conversationId, JSON.stringify(state));
}
async delete(conversationId: string): Promise<void> {
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;
}
}
+94
View File
@@ -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<typeof envSchema>;
@@ -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<ReturnType<ConversationsRepository['findForMember']>>
>;
/**
* 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<Place> {
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);
}
@@ -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<Auth>) {
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<Auth>,
@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<Auth>,
@Body({ schema: createGroupSchema }) body: CreateGroup,
) {
return this.conversations.createGroup(session.user.id, body);
}
@Get(':id')
get(
@Session() session: UserSession<Auth>,
@Param('id', { schema: conversationIdSchema }) id: string,
) {
return this.conversations.get(session.user.id, id);
}
/** Renames a group chat. */
@Patch(':id')
renameGroup(
@Session() session: UserSession<Auth>,
@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<Auth>,
@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<Auth>,
@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=<message id>&limit=50 */
@Get(':id/messages')
listMessages(
@Session() session: UserSession<Auth>,
@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<Auth>,
@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<Auth>,
@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<Auth>,
@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<Auth>,
@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<Auth>,
@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,
);
}
}
@@ -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 {}
@@ -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<boolean> {
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<string | undefined> {
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<string[]> {
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<string | undefined> {
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<string> {
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<string> {
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<void> {
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<boolean> {
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<MessageDetailsRow[]> {
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<string | undefined> {
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<boolean> {
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<number>`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<number>`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),
);
}
@@ -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<Conversation[]> {
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<Conversation> {
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<Conversation> {
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<Conversation> {
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<Conversation> {
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<Conversation> {
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<void> {
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<MessagePage> {
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<Message> {
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<void> {
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<void> {
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<void> {
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<ConversationRead> {
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<Event extends keyof ServerToClientEvents>(
place: Place,
event: Event,
...args: Parameters<ServerToClientEvents[Event]>
) {
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<ConversationRow> {
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<ConversationRow> {
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<MessageDetailsRow, 'author'> & { 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<string, Reaction>();
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,
};
}
@@ -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<Map<string, number>> {
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<Map<string, number>> {
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<Set<string>> {
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<number> {
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<number>`(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)`;
}
+30
View File
@@ -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();
}
+77 -2
View File
@@ -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 };
+2
View File
@@ -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(
+195
View File
@@ -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}`;
}
+84
View File
@@ -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 };
}
+3 -5
View File
@@ -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';
+148
View File
@@ -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<RealmPermission>().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] })],
);
+48
View File
@@ -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();
}
}
+60
View File
@@ -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<Env, true>): 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,
});
}
+24
View File
@@ -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<Env, true>) => ({
default: 'files',
disks: { files: createFilesDisk(config) },
}),
inject: [ConfigService],
}),
],
controllers: [FilesController],
})
export class FilesModule {}
@@ -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<Auth>) {
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<Auth>,
@Body({ schema: sendFriendRequestSchema }) body: SendFriendRequest,
) {
return this.friends.sendRequest(session.user.id, body.username);
}
@Post('requests/:userId/accept')
@HttpCode(204)
acceptRequest(
@Session() session: UserSession<Auth>,
@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<Auth>,
@Param('userId', { schema: userIdSchema }) userId: string,
) {
return this.friends.block(session.user.id, userId);
}
@Delete('blocks/:userId')
@HttpCode(204)
unblock(
@Session() session: UserSession<Auth>,
@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<Auth>,
@Param('userId', { schema: userIdSchema }) userId: string,
) {
return this.friends.remove(session.user.id, userId);
}
}
+16
View File
@@ -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 {}
+193
View File
@@ -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<FriendshipRow | undefined> {
const [row] = await this.db
.select()
.from(friendship)
.where(pairIs(userId, otherUserId));
return row;
}
async areFriends(userId: string, otherUserId: string): Promise<boolean> {
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<boolean> {
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<FriendshipRow | undefined> {
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<FriendshipRow | undefined> {
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<UserRow[]> {
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<void> {
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<boolean> {
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<FriendshipRow | undefined> {
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),
);
}
+144
View File
@@ -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<FriendsOverview> {
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<FriendRequestResult> {
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<void> {
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<void> {
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<void> {
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<void> {
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');
}
}
+36
View File
@@ -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'),
]);
}
}
+41
View File
@@ -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');
}
}
+15
View File
@@ -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 {}
+29 -2
View File
@@ -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<Env, true>>(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();
+10
View File
@@ -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 } });
+38
View File
@@ -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<WindowCount> {
const [hits, remainingMs] = (await redis.eval(
HIT,
1,
`rate:${key}`,
Math.ceil(windowMs),
)) as [number, number];
return { hits, remainingMs };
}
@@ -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<Env, true>, 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 {}
@@ -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,
};
}
}
@@ -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([]);
});
});
+22
View File
@@ -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));
}
+276
View File
@@ -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<Auth>) {
return this.realms.list(session.user.id);
}
@Post()
@AtMost(5, { seconds: 60 })
create(
@Session() session: UserSession<Auth>,
@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<Auth>,
@Param('id', { schema: realmIdSchema }) id: string,
) {
return this.realms.get(session.user.id, id);
}
@Patch(':id')
rename(
@Session() session: UserSession<Auth>,
@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<Auth>,
@Param('id', { schema: realmIdSchema }) id: string,
) {
return this.realms.delete(session.user.id, id);
}
@Get(':id/members')
listMembers(
@Session() session: UserSession<Auth>,
@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<Auth>,
@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<Auth>,
@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<Auth>,
@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<Auth>,
@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<Auth>,
@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<Auth>,
@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<Auth>,
@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<Auth>,
@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<Auth>,
@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<Auth>,
@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<Auth>,
@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<Auth>,
@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<Auth>,
@Param('id', { schema: realmIdSchema }) id: string,
) {
return this.realms.listInvites(session.user.id, id);
}
@Delete(':id/invites/:code')
@HttpCode(204)
revokeInvite(
@Session() session: UserSession<Auth>,
@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<Auth>,
@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<Auth>,
@Param('code', { schema: inviteCodeSchema }) code: string,
) {
return this.realms.acceptInvite(session.user.id, code);
}
}
+16
View File
@@ -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 {}
@@ -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);
});
});
+490
View File
@@ -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<Parameters<Database['transaction']>[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<RealmRow[]> {
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<string[]> {
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<RealmMembership | undefined> {
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<CauldronRow[]> {
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<RealmRoleRow[]> {
return this.db
.select()
.from(realmRole)
.where(eq(realmRole.realmId, realmId))
.orderBy(desc(realmRole.isDefault), asc(realmRole.id));
}
async countMembers(realmId: string): Promise<number> {
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<string> {
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<void> {
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<void> {
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<boolean> {
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<boolean> {
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<boolean> {
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<boolean> {
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<void> {
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<RealmRoleRow | undefined> {
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<RealmRoleRow | 'full'> {
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<RealmRoleRow | undefined> {
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<void> {
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<CauldronRow | 'full'> {
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<CauldronRow | undefined> {
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<boolean> {
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<void> {
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<void> {
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<RealmInviteRow, 'expiresAt' | 'maxUses' | 'uses'>,
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');
}
+604
View File
@@ -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<ReturnType<RealmsRepository['listMembers']>>[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<RealmListItem[]> {
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<Realm> {
return this.toRealm(await this.access(userId, realmId));
}
async create(userId: string, name: string): Promise<Realm> {
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<Realm> {
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<void> {
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<RealmMember[]> {
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<void> {
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<void> {
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<void> {
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<RealmBan[]> {
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<RealmMember> {
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<RealmRole> {
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<RealmRole> {
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<void> {
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<Cauldron> {
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<Cauldron> {
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<void> {
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<RealmInvite> {
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<RealmInvite[]> {
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<void> {
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<InvitePreview> {
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<Realm> {
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<Access> {
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<Access> {
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<RealmRoleRow> {
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<Realm> {
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,
};
}
@@ -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 {}
+101
View File
@@ -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<Auth>,
private readonly config: ConfigService<Env, true>,
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');
}
}
+8
View File
@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { RealtimeService } from './realtime.service';
@Module({
providers: [RealtimeService],
exports: [RealtimeService],
})
export class RealtimeModule {}
+85
View File
@@ -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<string, never>,
SocketData
>;
export type RealtimeSocket = Socket<
ClientToServerEvents,
ServerToClientEvents,
Record<string, never>,
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<Event extends keyof ServerToClientEvents>(
userIds: string[],
event: Event,
...args: Parameters<ServerToClientEvents[Event]>
) {
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<Event extends keyof ServerToClientEvents>(
realmId: string,
event: Event,
...args: Parameters<ServerToClientEvents[Event]>
) {
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);
}
}
+28
View File
@@ -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;
}
}
+74
View File
@@ -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<Env, true>) => {
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();
}
}
+52
View File
@@ -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<Env, true>>(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,
});
}
+17
View File
@@ -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,
};
}
+37
View File
@@ -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<Auth>) {
return this.users.getOwnProfile(session.user.id);
}
@Patch('me')
updateMe(
@Session() session: UserSession<Auth>,
@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);
}
}
+10
View File
@@ -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 {}
+47
View File
@@ -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<Pick<UserRow, 'name' | 'username' | 'bio'>>;
@Injectable()
export class UsersRepository {
constructor(@InjectDrizzle() private readonly db: Database) {}
findById(id: string): Promise<UserRow | undefined> {
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<UserRow[]> {
if (ids.length === 0) return [];
return this.db.select().from(user).where(inArray(user.id, ids));
}
findByUsername(username: string): Promise<UserRow | undefined> {
return this.db.query.user.findFirst({ where: { username } });
}
async update(id: string, changes: UserChanges): Promise<UserRow | undefined> {
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'
);
}
+68
View File
@@ -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<OwnProfile> {
const row = await this.users.findById(userId);
if (!row) throw new NotFoundException('User not found.');
return toOwnProfile(row);
}
async getPublicProfile(username: string): Promise<PublicProfile> {
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<OwnProfile> {
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 };
}
+15 -2
View File
@@ -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 () => {
+456
View File
@@ -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<string, string[]>();
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<Call[]> {
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<Env, true>>(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);
});
});
});
+326
View File
@@ -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<FriendsOverview> {
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<string>((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);
});
});
});
+305
View File
@@ -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<Conversation[]> {
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);
});
});
+272
View File
@@ -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<App>;
export type Agent = ReturnType<typeof request.agent>;
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<TestApp> {
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<TestApp>({
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<Env, true>>(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<TestUser> {
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<Database>(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<AttachmentUpload> {
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<CreateAttachment, 'size'>,
bytes: Buffer,
): Promise<string> {
const upload = await requestUpload(account, { ...file, size: bytes.length });
await putFile(app, upload, bytes).expect(200);
return upload.attachment.id;
}
export type ClientSocket = Socket<ServerToClientEvents, ClientToServerEvents>;
/** Starts the app on a free port and returns its address, for sockets. */
export async function listen(app: TestApp): Promise<string> {
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<string, string> = {}): 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<ClientSocket> {
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<void>((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<Event extends keyof ServerToClientEvents>(
socket: ClientSocket,
event: Event,
) {
return new Promise<Parameters<ServerToClientEvents[Event]>[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<ServerToClientEvents[Event]>[0]);
}) as never);
},
);
}
+571
View File
@@ -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<Message> {
return (
await account.agent
.post(`/conversations/${conversationId}/messages`)
.send(body)
.expect(201)
).body;
}
async function historyFor(
account: TestUser,
conversationId: string,
): Promise<Message[]> {
const page: MessagePage = (
await account.agent
.get(`/conversations/${conversationId}/messages`)
.expect(200)
).body;
return page.items;
}
async function chatFor(account: TestUser): Promise<Conversation> {
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('<script>alert(1)</script>'),
);
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<Realm> {
return (await account.agent.get(`/realms/${realm.id}`).expect(200)).body;
}
async function listedFor(account: TestUser): Promise<RealmListItem> {
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);
});
});
});
+396
View File
@@ -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<Message> {
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<string[]> {
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<FriendsOverview> {
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);
});
});
});
+95
View File
@@ -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>(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<Env, true>>(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<number>(10).fill(401));
expect(answers.slice(10)).toEqual([429, 429]);
const refused = await guess();
expect(Number(refused.headers['x-retry-after'])).toBeGreaterThan(0);
});
});
+644
View File
@@ -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<Realm> {
return (await account.agent.get(`/realms/${realm.id}`).expect(200)).body;
}
async function realmsOf(account: TestUser): Promise<RealmListItem[]> {
return (await account.agent.get('/realms').expect(200)).body;
}
async function membersSeenBy(account: TestUser): Promise<RealmMember[]> {
return (await account.agent.get(`/realms/${realm.id}/members`).expect(200))
.body;
}
async function newInvite(
account: TestUser,
body: object = {},
): Promise<RealmInvite> {
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<void>((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);
});
});
+120
View File
@@ -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);
});
});
});
-1
View File
@@ -4,7 +4,6 @@
"moduleResolution": "bundler",
"esModuleInterop": true,
"isolatedModules": true,
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
+12
View File
@@ -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',
},
},
});