Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
347 lines (312 loc) · 10.7 KB
/
Copy pathserver.js
File metadata and controls
347 lines (312 loc) · 10.7 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
'use strict';
const http = require('http');
const path = require('path');
const { randomUUID } = require('node:crypto');
const express = require('express');
const { WebSocket, WebSocketServer } = require('ws');
const { normalizeRoom } = require('./public/js/config');
const TripoCore = require('./public/js/tripo-core');
const DEFAULT_ORIGINS = ['https://lab.liambroza.com'];
const SIGNAL_TYPES = new Set(['offer', 'answer', 'ice']);
const TRIPO_API_BASE = 'https://openapi.tripo3d.ai/v3';
const TRIPO_RATE_WINDOW_MS = 10 * 60 * 1000;
const TRIPO_RATE_MAX_REQUESTS = 4;
const TRIPO_MODEL_CACHE_LIMIT = 8;
function createOriginPolicy(configuredOrigins) {
const values = configuredOrigins || process.env.ALLOWED_ORIGINS || DEFAULT_ORIGINS;
const origins = Array.isArray(values)
? values
: String(values).split(',').map((value) => value.trim()).filter(Boolean);
const allowed = new Set(origins.map((value) => value.replace(/\/$/, '')));
return function isOriginAllowed(origin) {
if (!origin) return true;
if (allowed.has('*') || allowed.has(origin.replace(/\/$/, ''))) return true;
try {
const url = new URL(origin);
return (
(url.protocol === 'http:' || url.protocol === 'https:') &&
['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
);
} catch {
return false;
}
};
}
function createXrrcServer(options = {}) {
const app = express();
const server = http.createServer(app);
const rooms = new Map();
const isOriginAllowed = createOriginPolicy(options.allowedOrigins);
const wss = new WebSocketServer({
server,
path: '/ws',
maxPayload: 256 * 1024,
verifyClient(info, done) {
if (isOriginAllowed(info.origin)) {
done(true);
} else {
done(false, 403, 'Origin not allowed');
}
},
});
app.disable('x-powered-by');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/health', (req, res) => {
const origin = req.get('origin');
if (origin && !isOriginAllowed(origin)) {
res.status(403).json({ status: 'forbidden' });
return;
}
if (origin) {
res.set('Access-Control-Allow-Origin', origin);
res.set('Vary', 'Origin');
}
res.set('Cache-Control', 'no-store');
res.json({
status: 'ok',
service: 'xrrc-signaling',
connections: wss.clients.size,
rooms: rooms.size,
});
});
// -- Tripo AI generation proxy -----------------------------------------
// The client never talks to Tripo directly: the API key stays here, user
// text is composed into guard-railed prompts server-side, and generated
// GLB binaries are streamed through /api/tripo/model/:taskId so browser
// clients (including remote peers) can load them without CORS issues.
const tripoApiKey = options.tripoApiKey ?? process.env.TRIPO_API_KEY ?? '';
const tripoFetch = options.tripoFetch || globalThis.fetch;
const tripoModelCache = new Map(); // taskId -> Promise<Buffer>
const tripoRateLog = new Map(); // ip -> [timestamps]
function applyTripoCors(req, res) {
const origin = req.get('origin');
if (origin && !isOriginAllowed(origin)) {
res.status(403).json({ error: 'Origin not allowed' });
return false;
}
if (origin) {
res.set('Access-Control-Allow-Origin', origin);
res.set('Vary', 'Origin');
}
return true;
}
function tripoGuard(req, res) {
if (!applyTripoCors(req, res)) return false;
if (!tripoApiKey) {
res.status(503).json({ error: 'Tripo generation is not configured' });
return false;
}
return true;
}
function tripoRateLimited(ip) {
const now = Date.now();
const log = (tripoRateLog.get(ip) || []).filter((time) => now - time < TRIPO_RATE_WINDOW_MS);
if (log.length >= TRIPO_RATE_MAX_REQUESTS) {
tripoRateLog.set(ip, log);
return true;
}
log.push(now);
tripoRateLog.set(ip, log);
return false;
}
async function tripoRequest(pathname, init = {}) {
const response = await tripoFetch(`${TRIPO_API_BASE}${pathname}`, {
...init,
headers: {
Authorization: `Bearer ${tripoApiKey}`,
'Content-Type': 'application/json',
},
});
const body = await response.json().catch(() => null);
if (!response.ok || !body || body.code !== 0) {
const message = (body && body.message) || `Tripo request failed (${response.status})`;
throw new Error(message);
}
return body.data;
}
function createTripoTask(prompt, kind) {
return tripoRequest('/generation/text-to-model', {
method: 'POST',
body: JSON.stringify(TripoCore.taskPayload(prompt, kind)),
});
}
app.get('/api/tripo/status', (req, res) => {
if (!applyTripoCors(req, res)) return;
res.set('Cache-Control', 'no-store');
res.json({ enabled: Boolean(tripoApiKey) });
});
app.post('/api/tripo/generate', express.json({ limit: '4kb' }), async (req, res) => {
if (!tripoGuard(req, res)) return;
const kind = req.body && req.body.kind;
const text = TripoCore.cleanPromptText(req.body && req.body.text);
if (!text || (kind !== 'vehicle' && kind !== 'map')) {
res.status(400).json({ error: 'Expected { kind: "vehicle" | "map", text }' });
return;
}
if (tripoRateLimited(req.ip)) {
res.status(429).json({ error: 'Too many generations; try again in a few minutes' });
return;
}
try {
if (kind === 'vehicle') {
const data = await createTripoTask(TripoCore.composeVehiclePrompt(text), 'vehicle');
res.json({ tasks: [{ role: 'vehicle', taskId: data.task_id }] });
return;
}
const tasks = await Promise.all(
TripoCore.composePropPrompts(text).map(async ({ role, prompt }) => {
const data = await createTripoTask(prompt, 'prop');
return { role, taskId: data.task_id };
})
);
res.json({ tasks });
} catch (error) {
res.status(502).json({ error: error.message });
}
});
app.get('/api/tripo/task/:taskId', async (req, res) => {
if (!tripoGuard(req, res)) return;
if (!TripoCore.isTaskId(req.params.taskId)) {
res.status(400).json({ error: 'Invalid task id' });
return;
}
try {
const task = TripoCore.normalizeTask(await tripoRequest(`/tasks/${req.params.taskId}`));
res.set('Cache-Control', 'no-store');
// model_url stays server-side; clients fetch /api/tripo/model/:taskId.
res.json({ status: task.status, progress: task.progress, imageUrl: task.imageUrl });
} catch (error) {
res.status(502).json({ error: error.message });
}
});
app.get('/api/tripo/model/:taskId', async (req, res) => {
if (!tripoGuard(req, res)) return;
const taskId = req.params.taskId;
if (!TripoCore.isTaskId(taskId)) {
res.status(400).json({ error: 'Invalid task id' });
return;
}
if (!tripoModelCache.has(taskId)) {
tripoModelCache.set(taskId, (async () => {
const task = TripoCore.normalizeTask(await tripoRequest(`/tasks/${taskId}`));
if (task.status !== 'success' || !task.modelUrl) {
const error = new Error(`Model is not ready (task ${task.status})`);
error.notReady = true;
throw error;
}
const upstream = await tripoFetch(task.modelUrl);
if (!upstream.ok) throw new Error(`Model download failed (${upstream.status})`);
return Buffer.from(await upstream.arrayBuffer());
})());
// Bound the cache; evict the oldest entry beyond the cap.
if (tripoModelCache.size > TRIPO_MODEL_CACHE_LIMIT) {
tripoModelCache.delete(tripoModelCache.keys().next().value);
}
}
try {
const buffer = await tripoModelCache.get(taskId);
res.set('Content-Type', 'model/gltf-binary');
res.set('Cache-Control', 'private, max-age=3600');
res.send(buffer);
} catch (error) {
tripoModelCache.delete(taskId);
res.status(error.notReady ? 409 : 502).json({ error: error.message });
}
});
function getRoom(name) {
if (!rooms.has(name)) rooms.set(name, new Map());
return rooms.get(name);
}
function send(ws, message) {
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
}
function broadcastToRoom(room, senderWs, message) {
room.forEach((clientWs) => {
if (clientWs !== senderWs) send(clientWs, message);
});
}
wss.on('connection', (ws, req) => {
const url = new URL(req.url, `http://${req.headers.host}`);
const roomName = normalizeRoom(url.searchParams.get('room'));
const id = randomUUID();
const room = getRoom(roomName);
ws.isAlive = true;
ws.rcId = id;
ws.rcRoom = roomName;
ws.on('pong', () => {
ws.isAlive = true;
});
send(ws, {
type: 'welcome',
id,
peers: Array.from(room.keys()),
});
broadcastToRoom(room, ws, { type: 'peer-joined', id });
room.set(id, ws);
ws.on('message', (rawData) => {
let message;
try {
message = JSON.parse(rawData.toString());
} catch {
send(ws, { type: 'error', code: 'invalid-json' });
return;
}
if (
!message ||
typeof message !== 'object' ||
!SIGNAL_TYPES.has(message.type) ||
typeof message.to !== 'string'
) {
send(ws, { type: 'error', code: 'invalid-signal' });
return;
}
const target = room.get(message.to);
if (!target) {
send(ws, { type: 'error', code: 'peer-unavailable', peer: message.to });
return;
}
const forwarded = { type: message.type, from: id, to: message.to };
if (message.type === 'ice') {
forwarded.candidate = message.candidate;
} else {
forwarded.sdp = message.sdp;
}
send(target, forwarded);
});
ws.on('close', () => {
room.delete(id);
broadcastToRoom(room, ws, { type: 'peer-left', id });
if (room.size === 0) rooms.delete(roomName);
});
ws.on('error', (error) => {
console.error(`WebSocket error for ${id}:`, error.message);
});
});
const heartbeat = setInterval(() => {
wss.clients.forEach((ws) => {
if (!ws.isAlive) {
ws.terminate();
return;
}
ws.isAlive = false;
ws.ping();
});
}, 30000);
heartbeat.unref();
server.on('close', () => clearInterval(heartbeat));
return { app, isOriginAllowed, rooms, server, wss };
}
const service = createXrrcServer();
const PORT = Number(process.env.PORT) || 3000;
const HOST = process.env.HOST || '127.0.0.1';
if (require.main === module) {
service.server.listen(PORT, HOST, () => {
console.log(`XRRC signaling ready at http://${HOST}:${PORT}`);
console.log(`Share it privately with: tailscale serve --bg ${PORT}`);
});
}
module.exports = {
...service,
createOriginPolicy,
createXrrcServer,
};