forked from devartifex/copilot-unleashed
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.ts
More file actions
288 lines (259 loc) · 11.4 KB
/
Copy pathhandler.ts
File metadata and controls
288 lines (259 loc) · 11.4 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
import { WebSocketServer, WebSocket } from 'ws';
import { Server, IncomingMessage } from 'http';
import { createCopilotClient } from '../copilot/client.js';
import { config } from '../config.js';
import { logSecurity } from '../security-log.js';
import { validateGitHubToken } from '../auth/github.js';
import { checkAuth } from '../auth/guard.js';
import { clearAuth } from '../auth/session-utils.js';
import { unsealAuth, parseCookieValue, AUTH_COOKIE_NAME } from '../auth/auth-cookie.js';
import {
sessionPool, createPoolEntry, destroyPoolEntry, poolSend,
isValidTabId, countUserSessions, evictOldestUserSession,
} from './session-pool.js';
import { VALID_MESSAGE_TYPES, HEARTBEAT_INTERVAL, MAX_MISSED_PINGS, RATE_LIMITED_TYPES, WS_RATE_LIMIT_MAX, WS_RATE_LIMIT_WINDOW_MS } from './constants.js';
import { messageHandlers } from './message-handlers/index.js';
import { chatStateStore } from '../chat-state-singleton.js';
import { debug } from '../logger.js';
import type { SessionMiddleware, MessageContext } from './types.js';
export { cleanupAllSessions, cleanupUserSessions } from './session-pool.js';
export function setupWebSocket(
server: Server,
sessionMiddleware: SessionMiddleware
): void {
const wss = new WebSocketServer({ server, path: '/ws' });
// Heartbeat — detect dead connections (tolerates brief mobile background suspensions)
const heartbeat = setInterval(() => {
wss.clients.forEach((ws: WebSocket & { missedPings?: number }) => {
const missed = ws.missedPings ?? 0;
if (missed >= MAX_MISSED_PINGS) {
console.log(`[WS-SERVER] Terminating connection after ${missed} missed pings`);
return ws.terminate();
}
ws.missedPings = missed + 1;
ws.ping();
});
}, HEARTBEAT_INTERVAL);
wss.on('close', () => clearInterval(heartbeat));
wss.on('connection', async (ws: WebSocket, req: IncomingMessage) => {
console.log('[WS-SERVER] New connection from', req.socket.remoteAddress);
(ws as any).missedPings = 0;
ws.on('pong', () => { (ws as any).missedPings = 0; });
// Validate WebSocket origin
const origin = req.headers.origin;
if (origin && !config.isDev) {
const baseOrigin = new URL(config.baseUrl).origin;
if (origin !== baseOrigin) {
logSecurity('warn', 'ws_forbidden_origin', { origin, expected: baseOrigin });
ws.close(1008, 'Forbidden origin');
return;
}
}
// Extract Express session from the upgrade request
await new Promise<void>((resolve) => {
sessionMiddleware(req, {} as any, resolve);
});
const session = (req as any).session;
debug('[WS-SERVER] Session extracted:', !!session, 'token:', !!session?.githubToken, 'user:', session?.githubUser?.login);
// Restore auth from encrypted cookie when session file is missing (e.g. after EmptyDir wipe)
if (session && !session.githubToken) {
const sealed = parseCookieValue(req.headers.cookie, AUTH_COOKIE_NAME);
if (sealed) {
const data = unsealAuth(sealed, config.sessionSecret, config.tokenMaxAge);
if (data) {
session.githubToken = data.githubToken;
session.githubUser = data.githubUser;
session.githubAuthTime = data.githubAuthTime;
session.save(() => {});
debug(`[WS-SERVER] Restored auth from cookie for user=${data.githubUser.login}`);
}
}
}
const auth = checkAuth(session);
debug('[WS-SERVER] Auth check:', auth.authenticated, auth.error || 'ok');
if (!auth.authenticated) {
logSecurity('warn', 'ws_unauthorized', {
ip: req.socket.remoteAddress,
reason: auth.error,
});
ws.close(4001, auth.error ?? 'Unauthorized');
return;
}
// Validate token is still valid with GitHub (catches revoked tokens)
// Skip for tokens authenticated within the last 30 seconds (just validated by poll endpoint)
const authAge = session.githubAuthTime ? Date.now() - session.githubAuthTime : Infinity;
if (authAge > 30_000) {
const validation = await validateGitHubToken(session.githubToken);
if (!validation.valid && validation.reason === 'invalid_token') {
logSecurity('warn', 'ws_token_revoked', { user: session.githubUser?.login });
await clearAuth(session);
ws.close(4001, 'Token revoked');
return;
}
// Transient API errors are not treated as revocation — allow connection
}
const githubToken: string = session.githubToken;
const userLogin: string = session.githubUser?.login || 'unknown';
const reqUrl = new URL(req.url || '/', `http://${req.headers.host}`);
const rawTabId = reqUrl.searchParams.get('tabId') || 'default';
const tabId = isValidTabId(rawTabId) ? rawTabId : 'default';
const lastSeq = parseInt(reqUrl.searchParams.get('lastSeq') || '-1', 10);
const poolKey = `${userLogin}:${tabId}`;
console.log('[WS-SERVER] Authenticated:', userLogin, 'tab:', tabId);
let entry = sessionPool.get(poolKey);
if (entry) {
debug('[WS-SERVER] Existing pool entry for', poolKey);
// Reattach to existing pool entry
if (entry.ws && entry.ws !== ws && entry.ws.readyState === WebSocket.OPEN) {
entry.ws.close(4002, 'Replaced by new connection');
}
if (entry.ttlTimer) {
clearTimeout(entry.ttlTimer);
entry.ttlTimer = null;
}
entry.ws = ws;
// Replay only messages the client hasn't seen (based on sequence numbers).
// Mark each replayed message so the client can suppress duplicate notifications
// (the server already sent a push notification while the client was unreachable).
const buffer = entry.messageBuffer.splice(0);
for (const msg of buffer) {
const msgSeq = typeof msg.seq === 'number' ? msg.seq : -1;
if (msgSeq > lastSeq && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ ...msg, replayed: true }));
}
}
debug('[WS-SERVER] Sending session_reconnected to', poolKey, 'hasSession:', !!entry.session);
poolSend(entry, {
type: 'session_reconnected',
user: userLogin,
hasSession: !!entry.session,
isProcessing: entry.isProcessing,
});
// Restore chat history from persisted state so the UI is populated
try {
const persistedState = await chatStateStore.load(userLogin, tabId);
if (persistedState && persistedState.messages.length > 0) {
poolSend(entry, {
type: 'cold_resume',
messages: persistedState.messages,
model: persistedState.model,
mode: persistedState.mode,
sdkSessionId: persistedState.sdkSessionId,
});
}
} catch (err) {
console.error('[WS-SERVER] Warm reconnect history load failed:', err);
}
// Re-send pending prompts so the user can respond on the new connection
if (entry.pendingUserInputPrompt && entry.userInputResolve) {
poolSend(entry, entry.pendingUserInputPrompt);
}
for (const prompt of entry.pendingPermissionPrompts.values()) {
poolSend(entry, prompt);
}
} else {
// Create new pool entry — enforce per-user session cap
if (countUserSessions(userLogin) >= config.maxSessionsPerUser) {
debug('[WS-SERVER] Session cap reached for', userLogin, '— evicting oldest');
await evictOldestUserSession(userLogin);
}
debug('[WS-SERVER] New pool entry for', poolKey);
const client = createCopilotClient(githubToken, config.copilotConfigDir);
entry = createPoolEntry(client, ws);
sessionPool.set(poolKey, entry);
// Load persisted state BEFORE sending connected so the client gets
// sdkSessionId in a single message and can decide immediately
// whether to resume or create a new session (no timer/delay needed).
let persistedState: Awaited<ReturnType<typeof chatStateStore.load>> = null;
try {
persistedState = await chatStateStore.load(userLogin, tabId);
} catch (err) {
console.error('[WS-SERVER] Cold resume load failed:', err);
}
const hasPersistedState = !!(persistedState && persistedState.messages.length > 0);
debug('[WS-SERVER] Sending connected to', poolKey, 'persisted:', hasPersistedState);
poolSend(entry, {
type: 'connected',
user: userLogin,
sdkSessionId: hasPersistedState ? persistedState!.sdkSessionId : null,
hasPersistedState,
});
// Send full chat history for UI restoration
if (hasPersistedState) {
poolSend(entry, {
type: 'cold_resume',
messages: persistedState!.messages,
model: persistedState!.model,
mode: persistedState!.mode,
sdkSessionId: persistedState!.sdkSessionId,
});
}
}
// Capture entry reference for this connection's handlers
const connectionEntry = entry;
ws.on('close', (code: number, reason: Buffer) => {
console.log('[WS-SERVER] Disconnected:', poolKey, 'code:', code);
if (connectionEntry.ws === ws) {
connectionEntry.ws = null;
connectionEntry.ttlTimer = setTimeout(async () => {
// Re-verify the connection wasn't re-attached during the TTL window
if (connectionEntry.ws !== null) return;
await destroyPoolEntry(connectionEntry);
sessionPool.delete(poolKey);
}, config.sessionPoolTtl);
}
});
// WS rate limiting: sliding window per connection for user-initiated messages
const rateLimitWindow: number[] = [];
ws.on('message', async (raw) => {
try {
const msg = JSON.parse(raw.toString());
debug('[WS-SERVER] Message from', userLogin, ':', msg.type);
if (!msg.type || !VALID_MESSAGE_TYPES.has(msg.type)) {
poolSend(connectionEntry, { type: 'error', message: 'Unknown message type' });
return;
}
// Handle client-side heartbeat
if (msg.type === 'ping') {
connectionEntry.lastPingAt = Date.now();
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'pong' }));
}
return;
}
// Rate limit user-initiated message types
if (RATE_LIMITED_TYPES.has(msg.type)) {
const now = Date.now();
// Prune expired entries
while (rateLimitWindow.length > 0 && rateLimitWindow[0] <= now - WS_RATE_LIMIT_WINDOW_MS) {
rateLimitWindow.shift();
}
if (rateLimitWindow.length >= WS_RATE_LIMIT_MAX) {
poolSend(connectionEntry, { type: 'error', message: 'Rate limit exceeded — please slow down' });
return;
}
rateLimitWindow.push(now);
}
const handler = messageHandlers[msg.type];
if (handler) {
const ctx: MessageContext = { connectionEntry, githubToken, userLogin, poolKey, ws };
await handler(msg, ctx);
}
} catch (err: any) {
console.error('WS message error:', err.message);
connectionEntry.isProcessing = false;
const errMsg = err?.message || 'An internal error occurred';
const isTimeout = typeof errMsg === 'string' && errMsg.toLowerCase().includes('timeout');
poolSend(connectionEntry, {
type: 'error',
message: isTimeout
? `Request timed out. The model took too long to respond — try again or start a new session. (${errMsg})`
: errMsg,
});
}
});
ws.on('error', (err) => {
console.error('WS error:', err.message);
});
});
}