forked from nkuntz1934/matrix-workers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrtc.ts
More file actions
309 lines (269 loc) · 9.24 KB
/
rtc.ts
File metadata and controls
309 lines (269 loc) · 9.24 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
// MatrixRTC API endpoints (MSC4143/MSC4195)
// Provides LiveKit JWT tokens for Element X calls
// Also implements MSC4143 RTC transports discovery
import { Hono } from 'hono';
import type { AppEnv } from '../types';
import { generateLiveKitToken, getLiveKitConfig } from '../services/livekit';
const app = new Hono<AppEnv>();
// GET /_matrix/client/unstable/org.matrix.msc4143/rtc/transports
// MSC4143: RTC transports discovery - tells clients what real-time communication methods are available
// Returns empty list to indicate standard WebRTC/TURN should be used (no special transports)
app.get('/_matrix/client/unstable/org.matrix.msc4143/rtc/transports', (c) => {
const config = getLiveKitConfig(c.env);
// If LiveKit is configured, advertise it as a transport option
if (config) {
return c.json({
transports: [
{
type: 'livekit',
url: `https://${c.env.SERVER_NAME}/livekit/get_token`,
},
],
});
}
// No special transports - clients will use standard WebRTC
return c.json({
transports: [],
});
});
// OpenID token structure from Matrix client
interface OpenIDToken {
access_token: string;
token_type: string;
matrix_server_name: string;
expires_in: number;
}
// Member info from request
interface MemberInfo {
id: string;
claimed_user_id: string;
claimed_device_id: string;
}
// Request body for /get_token
// Note: Element X sends 'room' not 'room_id', and 'device_id' not 'member'
interface GetTokenRequest {
room_id?: string; // Old format
room?: string; // Element X format
slot_id?: string;
openid_token: OpenIDToken;
member?: MemberInfo; // Old format
device_id?: string; // Element X format - device ID string
delayed_event_id?: string;
}
// Response for /get_token
interface GetTokenResponse {
url: string;
jwt: string;
}
// Verify OpenID token with the homeserver
async function verifyOpenIDToken(
token: OpenIDToken,
serverName: string
): Promise<{ sub: string } | null> {
try {
// The OpenID token should be verified against the homeserver
// For our own homeserver, we can verify it directly
if (token.matrix_server_name !== serverName) {
console.log('Token from different server:', token.matrix_server_name);
// For federated calls, we'd need to verify with the remote server
// For now, we only accept tokens from our own server
return null;
}
// For our own tokens, we trust them if they came from our server
// In production, you'd want to validate the token signature or check against storage
// For simplicity, we'll accept tokens that match our server name
return { sub: token.access_token };
} catch (error) {
console.error('Error verifying OpenID token:', error);
return null;
}
}
// Convert Matrix room ID to a valid LiveKit room name
function roomIdToLiveKitName(roomId: string): string {
// LiveKit room names can only contain alphanumeric, dash, underscore
// Matrix room IDs look like: !roomid:server.name
return roomId.replace(/[^a-zA-Z0-9-_]/g, '_');
}
// POST /livekit/get_token - Get a LiveKit JWT token
// This is the endpoint that Element X calls to get call credentials
app.post('/livekit/get_token', async (c) => {
const config = getLiveKitConfig(c.env);
if (!config) {
return c.json(
{ errcode: 'M_UNKNOWN', error: 'LiveKit not configured' },
500
);
}
let body: GetTokenRequest;
try {
body = await c.req.json();
} catch {
return c.json(
{ errcode: 'M_BAD_JSON', error: 'Invalid JSON body' },
400
);
}
// Handle both old format (room_id, member) and Element X format (room, device_id)
const roomId = body.room_id || body.room;
// Validate required fields
if (!roomId || !body.openid_token) {
return c.json(
{ errcode: 'M_BAD_JSON', error: 'Missing required fields: room and openid_token' },
400
);
}
// Verify the OpenID token (simplified for now)
// In production, you'd verify the token cryptographically
const verified = await verifyOpenIDToken(body.openid_token, c.env.SERVER_NAME);
if (!verified) {
// For now, accept all tokens from our server's clients
// This is a simplification - in production you'd verify properly
console.log('OpenID token verification skipped for development');
}
// Generate participant identity - use access_token as identity if no member info
let participantId: string;
let participantName: string;
if (body.member) {
participantId = body.member.claimed_user_id;
participantName = participantId.split(':')[0].replace('@', '');
} else {
participantId = body.device_id || body.openid_token.access_token.substring(0, 16);
participantName = body.device_id || 'participant';
}
// Convert Matrix room ID to LiveKit room name
const liveKitRoom = roomIdToLiveKitName(roomId);
try {
// Generate JWT token for this participant
const jwt = await generateLiveKitToken(
config.apiKey,
config.apiSecret,
liveKitRoom,
participantId,
participantName,
3600 // 1 hour TTL
);
const response: GetTokenResponse = {
url: config.wsUrl,
jwt: jwt,
};
return c.json(response);
} catch (error) {
console.error('Error generating LiveKit token:', error);
return c.json(
{ errcode: 'M_UNKNOWN', error: 'Failed to generate token' },
500
);
}
});
// OPTIONS handler for CORS preflight
app.options('/livekit/get_token', () => {
return new Response(null, {
status: 204,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
});
});
// POST /livekit/get_token/sfu/get - Alternative endpoint format used by Element X
// This is the same as /livekit/get_token but with /sfu/get suffix
app.post('/livekit/get_token/sfu/get', async (c) => {
console.log('[LiveKit] /sfu/get request received');
const config = getLiveKitConfig(c.env);
if (!config) {
console.log('[LiveKit] Config missing - API_KEY:', !!c.env.LIVEKIT_API_KEY, 'API_SECRET:', !!c.env.LIVEKIT_API_SECRET, 'URL:', !!c.env.LIVEKIT_URL);
return c.json(
{ errcode: 'M_UNKNOWN', error: 'LiveKit not configured' },
500
);
}
let body: GetTokenRequest;
try {
const rawBody = await c.req.text();
console.log('[LiveKit] Raw body length:', rawBody.length, 'preview:', rawBody.substring(0, 200));
body = JSON.parse(rawBody);
} catch (e) {
console.log('[LiveKit] JSON parse error:', e);
return c.json(
{ errcode: 'M_BAD_JSON', error: 'Invalid JSON body' },
400
);
}
// Handle both old format (room_id, member) and Element X format (room, device_id)
const roomId = body.room_id || body.room;
// Validate required fields
if (!roomId || !body.openid_token) {
console.log('[LiveKit] Missing fields - room_id:', !!body.room_id, 'room:', !!body.room, 'openid_token:', !!body.openid_token);
return c.json(
{ errcode: 'M_BAD_JSON', error: 'Missing required fields: room and openid_token' },
400
);
}
// Verify the OpenID token (simplified for now)
const verified = await verifyOpenIDToken(body.openid_token, c.env.SERVER_NAME);
if (!verified) {
console.log('OpenID token verification skipped for development');
}
// Generate participant identity - use access_token as identity if no member info
// Element X doesn't send member info, just device_id
let participantId: string;
let participantName: string;
if (body.member) {
participantId = body.member.claimed_user_id;
participantName = participantId.split(':')[0].replace('@', '');
} else {
// For Element X, derive identity from openid_token
// The access_token's user can be looked up, but for simplicity use device_id
participantId = body.device_id || body.openid_token.access_token.substring(0, 16);
participantName = body.device_id || 'participant';
}
// Convert Matrix room ID to LiveKit room name
const liveKitRoom = roomIdToLiveKitName(roomId);
try {
// Generate JWT token for this participant
const jwt = await generateLiveKitToken(
config.apiKey,
config.apiSecret,
liveKitRoom,
participantId,
participantName,
3600 // 1 hour TTL
);
const response: GetTokenResponse = {
url: config.wsUrl,
jwt: jwt,
};
return c.json(response);
} catch (error) {
console.error('Error generating LiveKit token:', error);
return c.json(
{ errcode: 'M_UNKNOWN', error: 'Failed to generate token' },
500
);
}
});
// OPTIONS handler for /sfu/get endpoint
app.options('/livekit/get_token/sfu/get', () => {
return new Response(null, {
status: 204,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
});
});
// Return 405 Method Not Allowed for non-POST/OPTIONS methods
// Element X checks endpoint availability with GET and expects 405 (not 404)
app.all('/livekit/get_token', (c) => {
return c.text('Method Not Allowed', 405, {
Allow: 'POST, OPTIONS',
});
});
app.all('/livekit/get_token/sfu/get', (c) => {
return c.text('Method Not Allowed', 405, {
Allow: 'POST, OPTIONS',
});
});
export default app;