-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
303 lines (266 loc) · 9.13 KB
/
server.js
File metadata and controls
303 lines (266 loc) · 9.13 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
const express = require('express');
const http = require('http');
const { WebSocketServer } = require('ws');
const path = require('path');
const rateLimit = require('express-rate-limit');
const config = require('./lib/config');
const store = require('./lib/store');
const app = express();
const server = http.createServer(app);
const wss = new WebSocketServer({ server, maxPayload: 64 * 1024 });
// Trust proxy headers (needed for localtunnel/ngrok to work with rate limiting)
app.set('trust proxy', 1);
app.use(express.json({ limit: '16kb' }));
// Rate limiting
const apiLimiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 30,
standardHeaders: true,
legacyHeaders: false,
message: { error: 'Too many requests, please try again later' },
});
const createLimiter = rateLimit({
windowMs: 60 * 1000,
max: 10,
standardHeaders: true,
legacyHeaders: false,
message: { error: 'Too many requests, please try again later' },
});
app.use('/api/', apiLimiter);
// Cookie parser helper
function parseCookie(cookieHeader, name) {
const match = cookieHeader.split(';').find(c => c.trim().startsWith(name + '='));
return match ? match.split('=')[1].trim() : '';
}
// Auth middleware - accepts cookie, header, or query param
function authCheck(req, res, next) {
const token = req.query.token
|| req.headers['x-auth-token']
|| parseCookieFromReq(req, 'mob_session');
if (token !== config.AUTH_TOKEN) {
return res.status(401).json({ error: 'Unauthorized' });
}
next();
}
function parseCookieFromReq(req, name) {
return parseCookie(req.headers.cookie || '', name);
}
// Serve static files (index.html) - no auth required for page load
app.use(express.static(path.join(config.PROJECT_DIR, 'public')));
// Auth endpoint: exchange token for HttpOnly session cookie
app.post('/auth', (req, res) => {
const { token } = req.body || {};
if (token !== config.AUTH_TOKEN) {
return res.status(401).json({ error: 'Invalid token' });
}
res.cookie('mob_session', config.AUTH_TOKEN, {
httpOnly: true,
secure: req.secure || req.headers['x-forwarded-proto'] === 'https',
sameSite: 'strict',
maxAge: config.SESSION_TTL,
path: '/',
});
res.json({ ok: true });
});
// Rotate the auth token -- invalidates all existing sessions
app.post('/api/rotate-token', authCheck, (req, res) => {
const newToken = config.rotateToken();
// Clear old cookie, set new one
res.cookie('mob_session', newToken, {
httpOnly: true,
secure: req.secure || req.headers['x-forwarded-proto'] === 'https',
sameSite: 'strict',
maxAge: config.SESSION_TTL,
path: '/',
});
// Close all existing WebSocket connections (they have the old token)
for (const ws of wsClients) {
ws.close(4002, 'Token rotated');
}
wsClients.clear();
res.json({ ok: true, message: 'Token rotated. Reconnect with new token.' });
});
// Health check - no auth required, used by hooks to detect if server is running
app.get('/api/health', (req, res) => {
res.json({ ok: true });
});
// API routes - all require auth
const VALID_TYPES = ['permission', 'question', 'notification'];
app.post('/api/request', createLimiter, authCheck, (req, res) => {
const { type, payload } = req.body;
if (!type || !payload) {
return res.status(400).json({ error: 'type and payload required' });
}
if (!VALID_TYPES.includes(type)) {
return res.status(400).json({ error: 'Invalid request type' });
}
if (typeof payload !== 'object' || payload === null) {
return res.status(400).json({ error: 'payload must be an object' });
}
const id = store.create(type, payload);
broadcast({ event: 'new_request', data: store.get(id) ? serialize(store.get(id)) : null });
res.json({ id });
});
app.get('/api/request/:id/wait', authCheck, async (req, res) => {
const { id } = req.params;
try {
const response = await store.wait(id);
res.json({ status: 'resolved', response });
} catch (err) {
if (err.message === 'Request timeout') {
res.status(408).json({ error: 'timeout', message: 'Request timed out waiting for response' });
} else {
res.status(404).json({ error: err.message });
}
}
});
app.post('/api/request/:id/respond', authCheck, (req, res) => {
const { id } = req.params;
const { decision } = req.body;
if (!decision) {
return res.status(400).json({ error: 'decision required' });
}
const ok = store.respond(id, decision);
if (!ok) {
return res.status(404).json({ error: 'Request not found or already resolved' });
}
// Broadcast is now handled by store 'resolved' event listener
res.json({ ok: true });
});
app.get('/api/requests', authCheck, (req, res) => {
res.json({ pending: store.getPending(), all: store.getAll() });
});
app.post('/api/notify', authCheck, (req, res) => {
const { message } = req.body;
broadcast({ event: 'notification', data: { message, timestamp: Date.now() } });
res.json({ ok: true });
});
function serialize(entry) {
return {
id: entry.id,
type: entry.type,
payload: entry.payload,
status: entry.status,
response: entry.response,
createdAt: entry.createdAt,
resolvedAt: entry.resolvedAt,
};
}
// WebSocket
const wsClients = new Set();
const wsConnectTimes = new Map(); // IP -> [timestamps] for rate limiting
wss.on('connection', (ws, req) => {
// Rate limit WebSocket connections: max 10 per minute per IP
const ip = req.socket.remoteAddress || 'unknown';
const now = Date.now();
const times = wsConnectTimes.get(ip) || [];
const recent = times.filter(t => now - t < 60000);
if (recent.length >= 10) {
ws.close(4003, 'Too many connections');
return;
}
recent.push(now);
wsConnectTimes.set(ip, recent);
// Auth via cookie (preferred) or query string (fallback for hooks/MCP)
const url = new URL(req.url, `http://${req.headers.host}`);
const token = url.searchParams.get('token');
const cookieToken = parseCookie(req.headers.cookie || '', 'mob_session');
if (token !== config.AUTH_TOKEN && cookieToken !== config.AUTH_TOKEN) {
ws.close(4001, 'Unauthorized');
return;
}
wsClients.add(ws);
ws.isAlive = true;
// Send current pending requests on connect
ws.send(JSON.stringify({ event: 'init', data: { pending: store.getPending() } }));
ws.on('pong', () => { ws.isAlive = true; });
ws.on('close', () => wsClients.delete(ws));
ws.on('error', () => wsClients.delete(ws));
// Handle client messages (ping keepalive)
ws.on('message', (data) => {
ws.isAlive = true; // Any message means connection is alive
try {
const msg = JSON.parse(data.toString());
if (msg.type === 'ping') {
// Respond with pong to keep connection alive
ws.send(JSON.stringify({ event: 'pong' }));
}
} catch (e) {
// Ignore invalid messages
}
});
});
// Ping/pong keepalive - terminate stale connections every 30s
const wsKeepalive = setInterval(() => {
for (const ws of wsClients) {
if (!ws.isAlive) {
wsClients.delete(ws);
ws.terminate();
continue;
}
ws.isAlive = false;
ws.ping();
}
}, 30000);
wss.on('close', () => clearInterval(wsKeepalive));
function broadcast(msg) {
const data = JSON.stringify(msg);
for (const ws of wsClients) {
if (ws.readyState === 1) {
ws.send(data);
}
}
}
// Broadcast when store resolves requests (including timeouts/expiry)
store.on('resolved', (entry) => {
broadcast({ event: 'resolved', data: entry });
});
// Start
server.listen(config.PORT, config.BIND_HOST, async () => {
const localUrl = `http://localhost:${config.PORT}`;
console.log('');
console.log(' cc-mob server running');
console.log(' ========================');
console.log(` Local: ${localUrl}`);
if (config.LAN_MODE) {
const lanUrl = `http://${config.LAN_IP}:${config.PORT}`;
console.log(` LAN: ${lanUrl}`);
} else {
console.log(' LAN: disabled (use --lan to enable)');
}
// Attempt localtunnel
try {
const localtunnel = require('localtunnel');
const tunnel = await localtunnel({ port: config.PORT });
const tunnelUrl = `${tunnel.url}?token=${config.AUTH_TOKEN}`;
console.log(` Tunnel: ${tunnel.url}`);
console.log(` Auth: ${tunnelUrl}`);
console.log('');
const qrcode = require('qrcode-terminal');
qrcode.generate(tunnelUrl, { small: true }, (qr) => {
console.log(qr);
});
console.log(' Scan the QR code to authenticate. Token will be exchanged for a secure cookie.');
tunnel.on('close', () => {
console.log(' [tunnel] Connection closed, attempting reconnect...');
setTimeout(async () => {
try {
const newTunnel = await localtunnel({ port: config.PORT });
console.log(` [tunnel] Reconnected: ${newTunnel.url}`);
newTunnel.on('error', (err) => {
console.log(' [tunnel] Error:', err.message);
});
} catch (e) {
console.log(' [tunnel] Reconnect failed:', e.message);
}
}, 3000);
});
tunnel.on('error', (err) => {
console.log(' [tunnel] Error:', err.message);
console.log(' [tunnel] Server continues running. Use local/LAN URL instead.');
});
} catch (e) {
console.log(` Tunnel: failed (${e.message}) - use LAN URL instead`);
}
console.log('');
});