mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-27 00:52:50 +00:00
feat: WIP element Chat intergration
This commit is contained in:
73
apps/edr-freight-api/src/modules/chat/chat-bridge.service.ts
Normal file
73
apps/edr-freight-api/src/modules/chat/chat-bridge.service.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { Inject, Injectable, Logger } from '@nestjs/common';
|
||||
import type { ConfigType } from '@nestjs/config';
|
||||
import { NotificationType, type NotifyInput } from '@edr/types';
|
||||
|
||||
import chatConfig from '../../config/chat.config';
|
||||
import { MatrixClient } from './matrix.client';
|
||||
|
||||
const FALLBACK_ROOM = { alias: 'freight-alerts', name: 'Freight Alerts' };
|
||||
|
||||
/**
|
||||
* Best-effort per-type routing to an existing dept room. Anything not listed
|
||||
* (including GENERIC) falls through to #freight-alerts — safer than a wrong
|
||||
* guess at which department a type belongs to. Extend as real usage shows
|
||||
* which types actually want a dept room instead of the shared feed.
|
||||
*
|
||||
* `name` matters only if this bridge is the very first thing to touch that
|
||||
* alias (normally the nightly/on-demand reconcile creates dept rooms first,
|
||||
* with the position's real name) — ensureRoom never renames an existing
|
||||
* room, so this must match what ChatProvisioningService would have used.
|
||||
*/
|
||||
const ROOM_FOR_TYPE: Partial<Record<NotificationType, { alias: string; name: string }>> = {
|
||||
[NotificationType.REQUEST_SUBMITTED]: { alias: 'dept-operation', name: 'Operation' },
|
||||
[NotificationType.CLEARANCE_REVIEW]: { alias: 'dept-operation', name: 'Operation' },
|
||||
};
|
||||
|
||||
/**
|
||||
* Mirrors BACKOFFICE-audience notifications into chat so staff see them
|
||||
* without having the inbox open. Hooked once into
|
||||
* NotificationInboxService.notify() — every one of that service's ~20
|
||||
* callers gets this for free.
|
||||
*
|
||||
* Gated on BACKOFFICE only: notify() also serves PORTAL (customer)
|
||||
* notifications, which must never land in an internal staff room.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ChatBridgeService {
|
||||
private readonly logger = new Logger(ChatBridgeService.name);
|
||||
|
||||
constructor(
|
||||
@Inject(chatConfig.KEY)
|
||||
private readonly config: ConfigType<typeof chatConfig>,
|
||||
private readonly matrix: MatrixClient,
|
||||
) {}
|
||||
|
||||
async bridge(input: NotifyInput): Promise<void> {
|
||||
if (!this.config.enabled) return;
|
||||
|
||||
try {
|
||||
const room = ROOM_FOR_TYPE[input.type] ?? FALLBACK_ROOM;
|
||||
const roomId = await this.matrix.ensureRoom(room.alias, room.name);
|
||||
const body = input.link ? `${input.title}\n${input.body}\n${input.link}` : `${input.title}\n${input.body}`;
|
||||
const html = `<strong>${escapeHtml(input.title)}</strong><br/>${escapeHtml(input.body)}${
|
||||
input.link ? `<br/><a href="${escapeHtml(input.link)}">${escapeHtml(input.link)}</a>` : ''
|
||||
}`;
|
||||
await this.matrix.sendMessage(roomId, body, html);
|
||||
} catch (err) {
|
||||
// Same contract as NotificationInboxService.notify(): a chat-bridge
|
||||
// failure must never break or roll back the notification that
|
||||
// triggered it.
|
||||
this.logger.error(
|
||||
`Chat bridge failed for ${input.type}: ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function escapeHtml(s: string): string {
|
||||
return s
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Cron, CronExpression } from '@nestjs/schedule';
|
||||
import { InjectDataSource } from '@nestjs/typeorm';
|
||||
import { DataSource } from 'typeorm';
|
||||
|
||||
import { MatrixClient } from './matrix.client';
|
||||
|
||||
/** edr-org.seeder.ts's EDR_ORG_KEY / EDR_UNIT_KEY — the org is currently flat
|
||||
* (one org, one unit), so this is the entire scope of what gets provisioned. */
|
||||
const ORG_KEY = 'edr_freight';
|
||||
const UNIT_KEY = 'edr_freight_app';
|
||||
|
||||
const SPACE_ALIAS = 'edr-freight';
|
||||
const GENERAL_ALIAS = 'general';
|
||||
|
||||
interface PositionHolder {
|
||||
positionKey: string;
|
||||
positionName: string;
|
||||
userId: string;
|
||||
userName: string;
|
||||
}
|
||||
|
||||
export interface ReconcileResult {
|
||||
rooms: number;
|
||||
joined: number;
|
||||
kicked: number;
|
||||
deactivated: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps Matrix rooms and their membership in sync with IAM's unit/position
|
||||
* tree. There is no local hook on "employee position changed" — IAM writes
|
||||
* happen inside the vendored @tria-plc/iamapi-common package — so this is a
|
||||
* reconcile loop, not an event handler: nightly, plus on-demand via
|
||||
* POST /chat/sync.
|
||||
*
|
||||
* Room identity is a deterministic alias (#dept-<positionKey>), not a stored
|
||||
* mapping table — resolved via the directory API, created on first miss.
|
||||
* Room membership is diffed against Matrix's own joined_members, not a local
|
||||
* snapshot — so a user removed from IAM disappears from chat on the very
|
||||
* next reconcile, with no extra state for this service to own.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ChatProvisioningService {
|
||||
private readonly logger = new Logger(ChatProvisioningService.name);
|
||||
|
||||
constructor(
|
||||
@InjectDataSource() private readonly dataSource: DataSource,
|
||||
private readonly matrix: MatrixClient,
|
||||
) {}
|
||||
|
||||
@Cron(CronExpression.EVERY_DAY_AT_3AM, { name: 'chat-provisioning-reconcile' })
|
||||
async scheduledReconcile(): Promise<void> {
|
||||
try {
|
||||
const result = await this.reconcile();
|
||||
this.logger.log(
|
||||
`Chat reconcile: ${result.rooms} room(s), ${result.joined} joined, ` +
|
||||
`${result.kicked} kicked, ${result.deactivated} deactivated`,
|
||||
);
|
||||
} catch (err) {
|
||||
// Never throws into the scheduler — chat provisioning must not be able
|
||||
// to take down anything else on the cron registry.
|
||||
this.logger.error(
|
||||
`Chat reconcile failed: ${(err as Error).message}`,
|
||||
(err as Error).stack,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async currentHolders(): Promise<PositionHolder[]> {
|
||||
return this.dataSource.query(
|
||||
`SELECT p.key AS "positionKey",
|
||||
COALESCE(p.name->>'en', p.key) AS "positionName",
|
||||
e.user_id AS "userId",
|
||||
COALESCE(iu.name->>'en', iu.username, iu.email) AS "userName"
|
||||
FROM iam.employee_positions ep
|
||||
JOIN iam.employees e ON e.id = ep.employee_id
|
||||
JOIN iam.positions p ON p.id = ep.position_id
|
||||
JOIN iam.units u ON u.id = p.unit_id
|
||||
JOIN iam.organizations o ON o.id = u.organization_id
|
||||
JOIN iam.users iu ON iu.id = e.user_id
|
||||
WHERE ep.is_current = true
|
||||
AND e.is_current = true
|
||||
AND o.key = $1
|
||||
AND u.key = $2`,
|
||||
[ORG_KEY, UNIT_KEY],
|
||||
);
|
||||
}
|
||||
|
||||
/** Force-joins additions, kicks+deactivates users no longer entitled anywhere. */
|
||||
private async syncMembership(
|
||||
roomId: string,
|
||||
desiredUserIds: Set<string>,
|
||||
botMxid: string,
|
||||
): Promise<{ joined: number; kicked: string[] }> {
|
||||
const current = await this.matrix.joinedMembers(roomId);
|
||||
const currentSet = new Set(current.filter((id) => id !== botMxid));
|
||||
|
||||
let joined = 0;
|
||||
for (const userId of desiredUserIds) {
|
||||
if (!currentSet.has(userId)) {
|
||||
await this.matrix.forceJoin(roomId, userId);
|
||||
joined += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const kicked: string[] = [];
|
||||
for (const userId of currentSet) {
|
||||
if (!desiredUserIds.has(userId)) {
|
||||
await this.matrix.kick(roomId, userId, 'No longer assigned to this room');
|
||||
kicked.push(userId);
|
||||
}
|
||||
}
|
||||
|
||||
return { joined, kicked };
|
||||
}
|
||||
|
||||
async reconcile(): Promise<ReconcileResult> {
|
||||
const holders = await this.currentHolders();
|
||||
const botMxid = await this.matrix.whoami();
|
||||
|
||||
const spaceId = await this.matrix.ensureRoom(SPACE_ALIAS, 'EDR Freight', {
|
||||
isSpace: true,
|
||||
});
|
||||
const generalRoomId = await this.matrix.ensureRoom(GENERAL_ALIAS, 'General', {
|
||||
parentSpaceId: spaceId,
|
||||
});
|
||||
|
||||
const allUserIds = new Set(holders.map((h) => this.matrix.mxid(h.userId)));
|
||||
|
||||
// Accounts are otherwise only created lazily on first JWT login (see
|
||||
// ChatSsoService) — force-joining someone who has never clicked "Chat"
|
||||
// yet 404s ("User not found") without this.
|
||||
const seenUserIds = new Set<string>();
|
||||
for (const h of holders) {
|
||||
const mxid = this.matrix.mxid(h.userId);
|
||||
if (seenUserIds.has(mxid)) continue;
|
||||
seenUserIds.add(mxid);
|
||||
await this.matrix.ensureUser(mxid, h.userName);
|
||||
}
|
||||
|
||||
let rooms = 2; // space + general
|
||||
let joined = 0;
|
||||
let kicked = 0;
|
||||
// A user kicked from anything while holding zero current positions
|
||||
// anywhere in the unit (allUserIds spans every position) is a full
|
||||
// leaver, not just moved between positions — deactivate their account.
|
||||
const kickedUserIds = new Set<string>();
|
||||
|
||||
const generalDiff = await this.syncMembership(generalRoomId, allUserIds, botMxid);
|
||||
joined += generalDiff.joined;
|
||||
kicked += generalDiff.kicked.length;
|
||||
generalDiff.kicked.forEach((uid) => kickedUserIds.add(uid));
|
||||
|
||||
const byPosition = new Map<string, { name: string; userIds: Set<string> }>();
|
||||
for (const h of holders) {
|
||||
const entry = byPosition.get(h.positionKey) ?? {
|
||||
name: h.positionName,
|
||||
userIds: new Set<string>(),
|
||||
};
|
||||
entry.userIds.add(this.matrix.mxid(h.userId));
|
||||
byPosition.set(h.positionKey, entry);
|
||||
}
|
||||
|
||||
for (const [positionKey, { name, userIds }] of byPosition) {
|
||||
const roomId = await this.matrix.ensureRoom(`dept-${positionKey}`, name, {
|
||||
parentSpaceId: spaceId,
|
||||
});
|
||||
rooms += 1;
|
||||
|
||||
const diff = await this.syncMembership(roomId, userIds, botMxid);
|
||||
joined += diff.joined;
|
||||
kicked += diff.kicked.length;
|
||||
diff.kicked.forEach((uid) => kickedUserIds.add(uid));
|
||||
}
|
||||
|
||||
let deactivated = 0;
|
||||
for (const userId of kickedUserIds) {
|
||||
if (allUserIds.has(userId)) continue; // moved position, still current elsewhere
|
||||
try {
|
||||
await this.matrix.deactivateUser(userId);
|
||||
deactivated += 1;
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Failed to deactivate departed user ${userId}: ${(err as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return { rooms, joined, kicked, deactivated };
|
||||
}
|
||||
}
|
||||
59
apps/edr-freight-api/src/modules/chat/chat-sso.service.ts
Normal file
59
apps/edr-freight-api/src/modules/chat/chat-sso.service.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import type { ConfigType } from '@nestjs/config';
|
||||
import type { TCurrentUser } from '@tria-plc/api-common/modules/auth/types/current-user.type';
|
||||
import { SignJWT } from 'jose';
|
||||
|
||||
import chatConfig from '../../config/chat.config';
|
||||
import { MatrixClient } from './matrix.client';
|
||||
|
||||
/** Matrix login_tokens are single-use and expire in 5 minutes (Synapse default). */
|
||||
const JWT_TTL_SECONDS = 60;
|
||||
|
||||
function displayName(user: TCurrentUser): string {
|
||||
return (
|
||||
user.name?.en ||
|
||||
Object.values(user.name ?? {}).find((v) => typeof v === 'string' && v) ||
|
||||
user.username ||
|
||||
user.email
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The SSO handoff: turn an already-authenticated freight session into a
|
||||
* one-click Element sign-in link, with no second password anywhere.
|
||||
*
|
||||
* 1. Sign a short-lived JWT asserting this user's id (Synapse's
|
||||
* org.matrix.login.jwt auto-registers the account on first use).
|
||||
* 2. Trade that JWT for a real Matrix access token.
|
||||
* 3. Trade the access token for a one-shot login_token.
|
||||
* 4. Hand the caller a link to Element's sso.html shim, which seeds
|
||||
* localStorage and forwards the token into Element's own login flow.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ChatSsoService {
|
||||
constructor(
|
||||
@Inject(chatConfig.KEY)
|
||||
private readonly config: ConfigType<typeof chatConfig>,
|
||||
private readonly matrix: MatrixClient,
|
||||
) {}
|
||||
|
||||
async getSsoUrl(user: TCurrentUser): Promise<{ url: string }> {
|
||||
const secret = new TextEncoder().encode(this.config.jwtSecret);
|
||||
const jwt = await new SignJWT({ name: displayName(user) })
|
||||
.setProtectedHeader({ alg: 'HS256' })
|
||||
.setSubject(user.id)
|
||||
.setIssuer('edr-freight-api')
|
||||
.setAudience('matrix')
|
||||
.setIssuedAt()
|
||||
.setExpirationTime(`${JWT_TTL_SECONDS}s`)
|
||||
.sign(secret);
|
||||
|
||||
const { access_token } = await this.matrix.loginWithJwt(jwt);
|
||||
const { login_token } = await this.matrix.getLoginToken(access_token);
|
||||
|
||||
const url = new URL(`${this.config.webUrl}/sso.html`);
|
||||
url.searchParams.set('t', login_token);
|
||||
url.searchParams.set('hs', this.config.publicBaseUrl);
|
||||
return { url: url.toString() };
|
||||
}
|
||||
}
|
||||
35
apps/edr-freight-api/src/modules/chat/chat.controller.ts
Normal file
35
apps/edr-freight-api/src/modules/chat/chat.controller.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { Controller, Get, Post, UseGuards } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { CurrentUser } from '@tria-plc/api-common/modules/auth/decorators/current-user.decorator';
|
||||
import { JwtGuard } from '@tria-plc/api-common/modules/auth/services/jwt.guard';
|
||||
import type { TCurrentUser } from '@tria-plc/api-common/modules/auth/types/current-user.type';
|
||||
|
||||
import { ChatSync } from '../../common/booking-guards';
|
||||
import { ChatProvisioningService } from './chat-provisioning.service';
|
||||
import { ChatSsoService } from './chat-sso.service';
|
||||
|
||||
@ApiTags('chat')
|
||||
@Controller('chat')
|
||||
@ApiBearerAuth()
|
||||
export class ChatController {
|
||||
constructor(
|
||||
private readonly sso: ChatSsoService,
|
||||
private readonly provisioning: ChatProvisioningService,
|
||||
) {}
|
||||
|
||||
@Get('sso')
|
||||
@UseGuards(JwtGuard)
|
||||
@ApiOperation({ summary: 'One-click sign-in link into EDR internal chat' })
|
||||
getSso(@CurrentUser() user: TCurrentUser) {
|
||||
return this.sso.getSsoUrl(user);
|
||||
}
|
||||
|
||||
@Post('sync')
|
||||
@ChatSync()
|
||||
@ApiOperation({
|
||||
summary: 'Re-run the chat room/membership reconcile immediately (normally nightly)',
|
||||
})
|
||||
sync() {
|
||||
return this.provisioning.reconcile();
|
||||
}
|
||||
}
|
||||
16
apps/edr-freight-api/src/modules/chat/chat.module.ts
Normal file
16
apps/edr-freight-api/src/modules/chat/chat.module.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
import { ChatBridgeService } from './chat-bridge.service';
|
||||
import { ChatController } from './chat.controller';
|
||||
import { ChatProvisioningService } from './chat-provisioning.service';
|
||||
import { ChatSsoService } from './chat-sso.service';
|
||||
import { MatrixClient } from './matrix.client';
|
||||
|
||||
@Module({
|
||||
controllers: [ChatController],
|
||||
providers: [MatrixClient, ChatSsoService, ChatProvisioningService, ChatBridgeService],
|
||||
// ChatBridgeService: consumed by NotificationInboxModule to mirror
|
||||
// BACKOFFICE notifications into chat — see notification-inbox.module.ts.
|
||||
exports: [ChatBridgeService],
|
||||
})
|
||||
export class ChatModule {}
|
||||
263
apps/edr-freight-api/src/modules/chat/matrix.client.ts
Normal file
263
apps/edr-freight-api/src/modules/chat/matrix.client.ts
Normal file
@@ -0,0 +1,263 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import type { ConfigType } from '@nestjs/config';
|
||||
|
||||
import chatConfig from '../../config/chat.config';
|
||||
|
||||
/**
|
||||
* Thin wrapper over the handful of Matrix Client-Server + Synapse Admin API
|
||||
* calls this app needs. Not a general Matrix SDK — matrix-js-sdk is a
|
||||
* browser/Element concern; the server side only ever provisions rooms/users
|
||||
* and posts bot messages, so a fetch wrapper is the whole job.
|
||||
*
|
||||
* All admin-scoped calls act as the account behind MATRIX_ADMIN_TOKEN. That
|
||||
* same account also posts the notification-bridge messages (see
|
||||
* ChatBridgeService) — one bot/admin account covers both jobs, no separate
|
||||
* bot user needed.
|
||||
*/
|
||||
@Injectable()
|
||||
export class MatrixClient {
|
||||
constructor(
|
||||
@Inject(chatConfig.KEY)
|
||||
private readonly config: ConfigType<typeof chatConfig>,
|
||||
) {}
|
||||
|
||||
/** `@<localpart>:<server_name>` — the one place this format is assembled. */
|
||||
mxid(localpart: string): string {
|
||||
return `@${localpart}:${this.config.serverName}`;
|
||||
}
|
||||
|
||||
get serverName(): string {
|
||||
return this.config.serverName;
|
||||
}
|
||||
|
||||
private async request<T>(
|
||||
method: string,
|
||||
path: string,
|
||||
body?: unknown,
|
||||
token: string = this.config.adminToken,
|
||||
): Promise<T> {
|
||||
const res = await fetch(`${this.config.baseUrl}${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '');
|
||||
throw new Error(
|
||||
`Matrix ${method} ${path} -> ${res.status}: ${text.slice(0, 500)}`,
|
||||
);
|
||||
}
|
||||
if (res.status === 204) return undefined as T;
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
/** No auth — only /login accepts a bare JWT with nothing else on the request. */
|
||||
private async publicRequest<T>(
|
||||
method: string,
|
||||
path: string,
|
||||
body: unknown,
|
||||
): Promise<T> {
|
||||
const res = await fetch(`${this.config.baseUrl}${path}`, {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '');
|
||||
throw new Error(
|
||||
`Matrix ${method} ${path} -> ${res.status}: ${text.slice(0, 500)}`,
|
||||
);
|
||||
}
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
/** 404 → null. Every other non-2xx still throws via {@link request}. */
|
||||
private async requestOrNull<T>(
|
||||
method: string,
|
||||
path: string,
|
||||
token?: string,
|
||||
): Promise<T | null> {
|
||||
const res = await fetch(`${this.config.baseUrl}${path}`, {
|
||||
method,
|
||||
headers: { Authorization: `Bearer ${token ?? this.config.adminToken}` },
|
||||
});
|
||||
if (res.status === 404) return null;
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '');
|
||||
throw new Error(
|
||||
`Matrix ${method} ${path} -> ${res.status}: ${text.slice(0, 500)}`,
|
||||
);
|
||||
}
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
/** Sign an already-authenticated freight session into a Matrix session. */
|
||||
loginWithJwt(
|
||||
jwt: string,
|
||||
): Promise<{ access_token: string; user_id: string; device_id: string }> {
|
||||
return this.publicRequest('POST', '/_matrix/client/v3/login', {
|
||||
type: 'org.matrix.login.jwt',
|
||||
token: jwt,
|
||||
initial_device_display_name: 'EDR Backoffice',
|
||||
});
|
||||
}
|
||||
|
||||
/** The account behind MATRIX_ADMIN_TOKEN — used to exclude the bot itself from membership reconciliation. */
|
||||
async whoami(): Promise<string> {
|
||||
const res = await this.request<{ user_id: string }>(
|
||||
'GET',
|
||||
'/_matrix/client/v3/account/whoami',
|
||||
);
|
||||
return res.user_id;
|
||||
}
|
||||
|
||||
/** Currently-joined user ids for a room (not full member-event state). */
|
||||
async joinedMembers(roomId: string): Promise<string[]> {
|
||||
const res = await this.request<{ joined: Record<string, unknown> }>(
|
||||
'GET',
|
||||
`/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/joined_members`,
|
||||
);
|
||||
return Object.keys(res.joined);
|
||||
}
|
||||
|
||||
/** Exchange a fresh access token for a one-shot login_token (5 min TTL). */
|
||||
getLoginToken(accessToken: string): Promise<{ login_token: string }> {
|
||||
return this.request(
|
||||
'POST',
|
||||
'/_matrix/client/v1/login/get_token',
|
||||
{},
|
||||
accessToken,
|
||||
);
|
||||
}
|
||||
|
||||
/** null when the alias doesn't resolve to a room yet. */
|
||||
resolveAlias(alias: string): Promise<{ room_id: string } | null> {
|
||||
return this.requestOrNull(
|
||||
'GET',
|
||||
`/_matrix/client/v3/directory/room/${encodeURIComponent(alias)}`,
|
||||
);
|
||||
}
|
||||
|
||||
createRoom(input: {
|
||||
alias: string;
|
||||
name: string;
|
||||
topic?: string;
|
||||
isSpace?: boolean;
|
||||
parentSpaceId?: string;
|
||||
}): Promise<{ room_id: string }> {
|
||||
return this.request('POST', '/_matrix/client/v3/createRoom', {
|
||||
room_alias_name: input.alias,
|
||||
name: input.name,
|
||||
topic: input.topic,
|
||||
preset: 'private_chat',
|
||||
creation_content: input.isSpace ? { type: 'm.space' } : undefined,
|
||||
initial_state: input.parentSpaceId
|
||||
? [
|
||||
{
|
||||
type: 'm.space.parent',
|
||||
state_key: input.parentSpaceId,
|
||||
content: { via: [this.config.serverName], canonical: true },
|
||||
},
|
||||
]
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
addToSpace(spaceId: string, childRoomId: string): Promise<void> {
|
||||
return this.request(
|
||||
'PUT',
|
||||
`/_matrix/client/v3/rooms/${encodeURIComponent(spaceId)}/state/m.space.child/${encodeURIComponent(childRoomId)}`,
|
||||
{ via: [this.config.serverName] },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get-or-create by alias — the room identity scheme this whole module
|
||||
* relies on instead of a local id-mapping table. Idempotent: safe to call
|
||||
* on every reconcile run and every bridged notification alike.
|
||||
*/
|
||||
async ensureRoom(
|
||||
alias: string,
|
||||
name: string,
|
||||
opts: { isSpace?: boolean; parentSpaceId?: string } = {},
|
||||
): Promise<string> {
|
||||
const existing = await this.resolveAlias(`#${alias}:${this.config.serverName}`);
|
||||
if (existing) return existing.room_id;
|
||||
|
||||
const { room_id } = await this.createRoom({
|
||||
alias,
|
||||
name,
|
||||
isSpace: opts.isSpace,
|
||||
parentSpaceId: opts.parentSpaceId,
|
||||
});
|
||||
if (opts.parentSpaceId) {
|
||||
await this.addToSpace(opts.parentSpaceId, room_id);
|
||||
}
|
||||
return room_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the account if absent (no password — this deployment is JWT-SSO
|
||||
* only), or no-op if it already exists. Needed before force-joining a
|
||||
* position holder who has never clicked "Chat": accounts are otherwise
|
||||
* only created lazily on first JWT login, and the admin join API 404s
|
||||
* ("User not found") on an account that doesn't exist yet.
|
||||
*/
|
||||
async ensureUser(userId: string, displayName?: string): Promise<void> {
|
||||
const existing = await this.requestOrNull<{ name: string }>(
|
||||
'GET',
|
||||
`/_synapse/admin/v2/users/${encodeURIComponent(userId)}`,
|
||||
);
|
||||
if (existing) return;
|
||||
await this.request(
|
||||
'PUT',
|
||||
`/_synapse/admin/v2/users/${encodeURIComponent(userId)}`,
|
||||
displayName ? { displayname: displayName } : {},
|
||||
);
|
||||
}
|
||||
|
||||
/** Server-admin force-join — no invite to accept, works even mid-outage for the invitee. */
|
||||
forceJoin(roomIdOrAlias: string, userId: string): Promise<void> {
|
||||
return this.request(
|
||||
'POST',
|
||||
`/_synapse/admin/v1/join/${encodeURIComponent(roomIdOrAlias)}`,
|
||||
{ user_id: userId },
|
||||
);
|
||||
}
|
||||
|
||||
kick(roomId: string, userId: string, reason: string): Promise<void> {
|
||||
return this.request(
|
||||
'POST',
|
||||
`/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/kick`,
|
||||
{ user_id: userId, reason },
|
||||
);
|
||||
}
|
||||
|
||||
/** Deactivating (rather than just kicking) a leaver's account revokes all their sessions. */
|
||||
deactivateUser(userId: string): Promise<void> {
|
||||
return this.request(
|
||||
'POST',
|
||||
`/_synapse/admin/v1/deactivate/${encodeURIComponent(userId)}`,
|
||||
{ erase: false },
|
||||
);
|
||||
}
|
||||
|
||||
sendMessage(roomId: string, body: string, formattedBody?: string): Promise<void> {
|
||||
const txnId = `edr-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
return this.request(
|
||||
'PUT',
|
||||
`/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/send/m.room.message/${txnId}`,
|
||||
formattedBody
|
||||
? {
|
||||
msgtype: 'm.text',
|
||||
body,
|
||||
format: 'org.matrix.custom.html',
|
||||
formatted_body: formattedBody,
|
||||
}
|
||||
: { msgtype: 'm.text', body },
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user