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
+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,
};
}