forked from nkuntz1934/matrix-workers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaliases.ts
More file actions
244 lines (199 loc) · 7.21 KB
/
aliases.ts
File metadata and controls
244 lines (199 loc) · 7.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
// Room Aliases API
// Implements: https://spec.matrix.org/v1.12/client-server-api/#room-aliases
//
// Room aliases provide human-readable names for rooms (e.g., #general:server.org)
import { Hono } from 'hono';
import type { AppEnv } from '../types';
import { Errors } from '../utils/errors';
import { requireAuth } from '../middleware/auth';
const app = new Hono<AppEnv>();
// ============================================
// Endpoints
// ============================================
// GET /_matrix/client/v3/directory/room/:roomAlias - Resolve room alias
app.get('/_matrix/client/v3/directory/room/:roomAlias', async (c) => {
const roomAlias = decodeURIComponent(c.req.param('roomAlias'));
const db = c.env.DB;
// Find alias in database
const alias = await db.prepare(`
SELECT room_id, servers FROM room_aliases WHERE alias = ?
`).bind(roomAlias).first<{ room_id: string; servers: string | null }>();
if (!alias) {
return Errors.notFound('Room alias not found').toResponse();
}
// Parse servers list
let servers: string[] = [c.env.SERVER_NAME];
if (alias.servers) {
try {
servers = JSON.parse(alias.servers);
} catch {
// Use default
}
}
return c.json({
room_id: alias.room_id,
servers,
});
});
// PUT /_matrix/client/v3/directory/room/:roomAlias - Create room alias
app.put('/_matrix/client/v3/directory/room/:roomAlias', requireAuth(), async (c) => {
const userId = c.get('userId');
const roomAlias = decodeURIComponent(c.req.param('roomAlias'));
const db = c.env.DB;
let body: { room_id: string };
try {
body = await c.req.json();
} catch {
return Errors.badJson().toResponse();
}
if (!body.room_id) {
return Errors.missingParam('room_id').toResponse();
}
// Validate alias format
if (!roomAlias.startsWith('#') || !roomAlias.includes(':')) {
return c.json({
errcode: 'M_INVALID_PARAM',
error: 'Invalid room alias format',
}, 400);
}
// Check alias is for our server
const [, aliasServer] = roomAlias.split(':');
if (aliasServer !== c.env.SERVER_NAME) {
return c.json({
errcode: 'M_INVALID_PARAM',
error: 'Cannot create alias for another server',
}, 400);
}
// Check room exists
const room = await db.prepare(`
SELECT room_id FROM rooms WHERE room_id = ?
`).bind(body.room_id).first();
if (!room) {
return Errors.notFound('Room not found').toResponse();
}
// Check user is member of room
const membership = await db.prepare(`
SELECT membership FROM room_memberships WHERE room_id = ? AND user_id = ?
`).bind(body.room_id, userId).first<{ membership: string }>();
if (!membership || membership.membership !== 'join') {
return Errors.forbidden('Not a member of this room').toResponse();
}
// Check alias doesn't already exist
const existing = await db.prepare(`
SELECT alias FROM room_aliases WHERE alias = ?
`).bind(roomAlias).first();
if (existing) {
return c.json({
errcode: 'M_ROOM_IN_USE',
error: 'Room alias already exists',
}, 409);
}
// Create alias
await db.prepare(`
INSERT INTO room_aliases (alias, room_id, creator_id, servers, created_at)
VALUES (?, ?, ?, ?, ?)
`).bind(roomAlias, body.room_id, userId, JSON.stringify([c.env.SERVER_NAME]), Date.now()).run();
return c.json({});
});
// DELETE /_matrix/client/v3/directory/room/:roomAlias - Delete room alias
app.delete('/_matrix/client/v3/directory/room/:roomAlias', requireAuth(), async (c) => {
const userId = c.get('userId');
const roomAlias = decodeURIComponent(c.req.param('roomAlias'));
const db = c.env.DB;
// Find alias
const alias = await db.prepare(`
SELECT room_id, creator_id FROM room_aliases WHERE alias = ?
`).bind(roomAlias).first<{ room_id: string; creator_id: string }>();
if (!alias) {
return Errors.notFound('Room alias not found').toResponse();
}
// Check permissions - creator or room admin can delete
const canDelete = alias.creator_id === userId;
if (!canDelete) {
// Check if user has power to delete aliases in the room
const powerLevels = await db.prepare(`
SELECT e.content FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.room.power_levels'
`).bind(alias.room_id).first<{ content: string }>();
if (powerLevels) {
try {
const levels = JSON.parse(powerLevels.content);
const userPower = levels.users?.[userId] || levels.users_default || 0;
const aliasLevel = levels.state_default || 50;
if (userPower < aliasLevel) {
return Errors.forbidden('Insufficient power level to delete alias').toResponse();
}
} catch {
return Errors.forbidden('Cannot delete alias').toResponse();
}
} else {
return Errors.forbidden('Cannot delete alias').toResponse();
}
}
// Delete alias
await db.prepare(`
DELETE FROM room_aliases WHERE alias = ?
`).bind(roomAlias).run();
return c.json({});
});
// GET /_matrix/client/v3/directory/list/room/:roomId - Get room visibility
app.get('/_matrix/client/v3/directory/list/room/:roomId', async (c) => {
const roomId = c.req.param('roomId');
const db = c.env.DB;
const room = await db.prepare(`
SELECT is_public FROM rooms WHERE room_id = ?
`).bind(roomId).first<{ is_public: number }>();
if (!room) {
return Errors.notFound('Room not found').toResponse();
}
return c.json({
visibility: room.is_public ? 'public' : 'private',
});
});
// PUT /_matrix/client/v3/directory/list/room/:roomId - Set room visibility
app.put('/_matrix/client/v3/directory/list/room/:roomId', requireAuth(), async (c) => {
const userId = c.get('userId');
const roomId = c.req.param('roomId');
const db = c.env.DB;
let body: { visibility: 'public' | 'private' };
try {
body = await c.req.json();
} catch {
return Errors.badJson().toResponse();
}
if (!body.visibility || !['public', 'private'].includes(body.visibility)) {
return Errors.missingParam('visibility').toResponse();
}
// Check user has power to change visibility
const membership = await db.prepare(`
SELECT membership FROM room_memberships WHERE room_id = ? AND user_id = ?
`).bind(roomId, userId).first<{ membership: string }>();
if (!membership || membership.membership !== 'join') {
return Errors.forbidden('Not a member of this room').toResponse();
}
// Check power level
const powerLevels = await db.prepare(`
SELECT e.content FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.room.power_levels'
`).bind(roomId).first<{ content: string }>();
if (powerLevels) {
try {
const levels = JSON.parse(powerLevels.content);
const userPower = levels.users?.[userId] || levels.users_default || 0;
const requiredPower = levels.state_default || 50;
if (userPower < requiredPower) {
return Errors.forbidden('Insufficient power level').toResponse();
}
} catch {
return Errors.forbidden('Cannot change visibility').toResponse();
}
}
// Update visibility
await db.prepare(`
UPDATE rooms SET is_public = ? WHERE room_id = ?
`).bind(body.visibility === 'public' ? 1 : 0, roomId).run();
return c.json({});
});
export default app;