forked from nkuntz1934/matrix-workers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver-notices.ts
More file actions
348 lines (298 loc) · 9.02 KB
/
server-notices.ts
File metadata and controls
348 lines (298 loc) · 9.02 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Server Notices API
// Implements server-generated notices to users
//
// Server notices are messages sent by the server to inform users about
// important events like terms of service updates, security alerts, etc.
import { Hono } from 'hono';
import type { AppEnv } from '../types';
import { Errors } from '../utils/errors';
import { requireAuth } from '../middleware/auth';
import { generateOpaqueId, generateEventId } from '../utils/ids';
const app = new Hono<AppEnv>();
// Server notice room configuration
const SERVER_NOTICE_ROOM_TYPE = 'm.server_notice';
const SERVER_NOTICE_USER_LOCALPART = 'server';
// ============================================
// Internal Functions
// ============================================
// Get or create the server notice user
async function getServerNoticeUser(db: D1Database, serverName: string): Promise<string> {
const userId = `@${SERVER_NOTICE_USER_LOCALPART}:${serverName}`;
const existing = await db.prepare(`
SELECT user_id FROM users WHERE user_id = ?
`).bind(userId).first();
if (!existing) {
// Create the server notice user
await db.prepare(`
INSERT INTO users (user_id, localpart, display_name, admin, is_guest, is_deactivated)
VALUES (?, ?, 'Server Notices', 0, 0, 0)
`).bind(userId, SERVER_NOTICE_USER_LOCALPART).run();
}
return userId;
}
// Get or create a server notice room for a user
async function getOrCreateNoticeRoom(
db: D1Database,
serverName: string,
targetUserId: string
): Promise<string> {
// Check if user already has a server notice room
const existing = await db.prepare(`
SELECT rm.room_id FROM room_memberships rm
JOIN room_state rs ON rm.room_id = rs.room_id
JOIN events e ON rs.event_id = e.event_id
WHERE rm.user_id = ?
AND rs.event_type = 'm.room.create'
AND e.content LIKE '%"type":"m.server_notice"%'
LIMIT 1
`).bind(targetUserId).first<{ room_id: string }>();
if (existing) {
return existing.room_id;
}
// Create a new server notice room
const serverUserId = await getServerNoticeUser(db, serverName);
const roomId = `!${await generateOpaqueId(18)}:${serverName}`;
const now = Date.now();
// Create room
await db.prepare(`
INSERT INTO rooms (room_id, room_version, is_public, creator_id, created_at)
VALUES (?, '10', 0, ?, ?)
`).bind(roomId, serverUserId, now).run();
// Create room events
const events = [
{
type: 'm.room.create',
state_key: '',
content: {
creator: serverUserId,
room_version: '10',
type: SERVER_NOTICE_ROOM_TYPE,
},
},
{
type: 'm.room.name',
state_key: '',
content: {
name: 'Server Notices',
},
},
{
type: 'm.room.join_rules',
state_key: '',
content: {
join_rule: 'invite',
},
},
{
type: 'm.room.history_visibility',
state_key: '',
content: {
history_visibility: 'joined',
},
},
{
type: 'm.room.power_levels',
state_key: '',
content: {
users: {
[serverUserId]: 100,
},
users_default: 0,
events_default: 50,
state_default: 50,
ban: 50,
kick: 50,
redact: 50,
invite: 0,
},
},
{
type: 'm.room.member',
state_key: serverUserId,
content: {
membership: 'join',
displayname: 'Server Notices',
},
},
{
type: 'm.room.member',
state_key: targetUserId,
content: {
membership: 'invite',
},
},
];
let depth = 1;
let prevEvents: string[] = [];
const authEvents: string[] = [];
for (const event of events) {
const eventId = await generateEventId(serverName);
await db.prepare(`
INSERT INTO events (
event_id, room_id, sender, event_type, state_key, content,
origin_server_ts, depth, auth_events, prev_events
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).bind(
eventId,
roomId,
serverUserId,
event.type,
event.state_key,
JSON.stringify(event.content),
now + depth,
depth,
JSON.stringify(authEvents),
JSON.stringify(prevEvents)
).run();
// Update room state
await db.prepare(`
INSERT OR REPLACE INTO room_state (room_id, event_type, state_key, event_id)
VALUES (?, ?, ?, ?)
`).bind(roomId, event.type, event.state_key, eventId).run();
// Track auth events
if (['m.room.create', 'm.room.power_levels', 'm.room.join_rules'].includes(event.type)) {
authEvents.push(eventId);
}
prevEvents = [eventId];
depth++;
}
// Create memberships
await db.prepare(`
INSERT INTO room_memberships (room_id, user_id, membership, event_id, display_name)
VALUES (?, ?, 'join', ?, 'Server Notices')
`).bind(roomId, serverUserId, prevEvents[0]).run();
await db.prepare(`
INSERT INTO room_memberships (room_id, user_id, membership, event_id)
VALUES (?, ?, 'invite', ?)
`).bind(roomId, targetUserId, prevEvents[0]).run();
return roomId;
}
// Send a server notice to a user
export async function sendServerNotice(
db: D1Database,
serverName: string,
targetUserId: string,
body: string,
msgtype: string = 'm.text',
adminContact?: string
): Promise<string> {
const roomId = await getOrCreateNoticeRoom(db, serverName, targetUserId);
const serverUserId = await getServerNoticeUser(db, serverName);
const eventId = await generateEventId(serverName);
const now = Date.now();
// Get latest event for prev_events
const latest = await db.prepare(`
SELECT event_id, depth FROM events WHERE room_id = ? ORDER BY depth DESC LIMIT 1
`).bind(roomId).first<{ event_id: string; depth: number }>();
const depth = (latest?.depth || 0) + 1;
const prevEvents = latest ? [latest.event_id] : [];
// Get auth events
const authEventRows = await db.prepare(`
SELECT e.event_id FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type IN ('m.room.create', 'm.room.power_levels', 'm.room.member')
AND (rs.state_key = '' OR rs.state_key = ?)
`).bind(roomId, serverUserId).all<{ event_id: string }>();
const authEvents = authEventRows.results.map(r => r.event_id);
const content: Record<string, any> = {
msgtype,
body,
};
if (adminContact) {
content.admin_contact = adminContact;
}
// Server notice specific content
content['m.server_notice_type'] = 'm.server_notice.usage_limit_reached'; // or other types
await db.prepare(`
INSERT INTO events (
event_id, room_id, sender, event_type, content,
origin_server_ts, depth, auth_events, prev_events
) VALUES (?, ?, ?, 'm.room.message', ?, ?, ?, ?, ?)
`).bind(
eventId,
roomId,
serverUserId,
JSON.stringify(content),
now,
depth,
JSON.stringify(authEvents),
JSON.stringify(prevEvents)
).run();
return eventId;
}
// ============================================
// Admin Endpoints for Server Notices
// ============================================
// POST /_synapse/admin/v1/send_server_notice - Send a server notice (Synapse-compatible)
app.post('/_synapse/admin/v1/send_server_notice', requireAuth(), async (c) => {
const userId = c.get('userId');
const db = c.env.DB;
// Check if user is admin
const user = await db.prepare(`
SELECT admin FROM users WHERE user_id = ?
`).bind(userId).first<{ admin: number }>();
if (!user || user.admin !== 1) {
return Errors.forbidden('Admin access required').toResponse();
}
let body: {
user_id: string;
content: {
msgtype: string;
body: string;
admin_contact?: string;
};
};
try {
body = await c.req.json();
} catch {
return Errors.badJson().toResponse();
}
if (!body.user_id || !body.content?.body) {
return Errors.missingParam('user_id or content.body').toResponse();
}
const eventId = await sendServerNotice(
db,
c.env.SERVER_NAME,
body.user_id,
body.content.body,
body.content.msgtype || 'm.text',
body.content.admin_contact
);
return c.json({ event_id: eventId });
});
// POST /_matrix/client/v3/admin/send_server_notice - Alternative endpoint
app.post('/_matrix/client/v3/admin/send_server_notice', requireAuth(), async (c) => {
const userId = c.get('userId');
const db = c.env.DB;
// Check if user is admin
const user = await db.prepare(`
SELECT admin FROM users WHERE user_id = ?
`).bind(userId).first<{ admin: number }>();
if (!user || user.admin !== 1) {
return Errors.forbidden('Admin access required').toResponse();
}
let body: {
user_id: string;
content: {
msgtype: string;
body: string;
};
};
try {
body = await c.req.json();
} catch {
return Errors.badJson().toResponse();
}
if (!body.user_id || !body.content?.body) {
return Errors.missingParam('user_id or content.body').toResponse();
}
const eventId = await sendServerNotice(
db,
c.env.SERVER_NAME,
body.user_id,
body.content.body,
body.content.msgtype || 'm.text'
);
return c.json({ event_id: eventId });
});
export default app;