forked from JavaScriptSolidServer/JavaScriptSolidServer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket.js
More file actions
200 lines (175 loc) · 4.7 KB
/
Copy pathwebsocket.js
File metadata and controls
200 lines (175 loc) · 4.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
/**
* WebSocket Handler for Solid Notifications
*
* Implements the legacy "solid-0.1" protocol used by SolidOS/mashlib.
*
* Protocol:
* - Server sends: "protocol solid-0.1" on connect
* - Client sends: "sub <uri>" to subscribe
* - Server sends: "ack <uri>" to acknowledge
* - Server sends: "pub <uri>" when resource changes
*/
import { resourceEvents } from './events.js';
// Security limits
const MAX_SUBSCRIPTIONS_PER_CONNECTION = 100;
const MAX_URL_LENGTH = 2048;
// Track subscriptions: WebSocket -> Set<url>
const subscriptions = new Map();
// Reverse lookup: url -> Set<WebSocket>
const subscribers = new Map();
/**
* Handle new WebSocket connection
* @param {WebSocket} socket - The WebSocket connection
* @param {Request} request - The HTTP request
*/
export function handleWebSocket(socket, request) {
// Send protocol greeting
socket.send('protocol solid-0.1');
// Initialize subscription set for this socket
subscriptions.set(socket, new Set());
// Handle incoming messages
socket.on('message', (message) => {
const msg = message.toString().trim();
// Handle subscription request
if (msg.startsWith('sub ')) {
const url = msg.slice(4).trim();
if (url) {
// Security: validate URL length
if (url.length > MAX_URL_LENGTH) {
socket.send('error: URL too long');
return;
}
// Security: check subscription limit
const socketSubs = subscriptions.get(socket);
if (socketSubs && socketSubs.size >= MAX_SUBSCRIPTIONS_PER_CONNECTION) {
socket.send('error: Subscription limit exceeded');
return;
}
subscribe(socket, url);
socket.send(`ack ${url}`);
}
}
// Handle unsubscribe (optional extension)
if (msg.startsWith('unsub ')) {
const url = msg.slice(6).trim();
if (url) {
unsubscribe(socket, url);
}
}
});
// Clean up on close
socket.on('close', () => {
cleanup(socket);
});
// Clean up on error
socket.on('error', () => {
cleanup(socket);
});
}
/**
* Subscribe a socket to a resource URL
*/
function subscribe(socket, url) {
// Add to socket's subscriptions
const socketSubs = subscriptions.get(socket);
if (socketSubs) {
socketSubs.add(url);
}
// Add to URL's subscribers
if (!subscribers.has(url)) {
subscribers.set(url, new Set());
}
subscribers.get(url).add(socket);
}
/**
* Unsubscribe a socket from a resource URL
*/
function unsubscribe(socket, url) {
// Remove from socket's subscriptions
const socketSubs = subscriptions.get(socket);
if (socketSubs) {
socketSubs.delete(url);
}
// Remove from URL's subscribers
const urlSubs = subscribers.get(url);
if (urlSubs) {
urlSubs.delete(socket);
if (urlSubs.size === 0) {
subscribers.delete(url);
}
}
}
/**
* Clean up all subscriptions for a socket
*/
function cleanup(socket) {
const urls = subscriptions.get(socket);
if (urls) {
for (const url of urls) {
unsubscribe(socket, url);
}
}
subscriptions.delete(socket);
}
/**
* Broadcast a change notification to all subscribers of a URL
* Also notifies subscribers of parent containers
*/
export function broadcast(url) {
// Notify direct subscribers
notifySubscribers(url);
// Also notify container subscribers (parent directory)
// This allows subscribing to a container and getting notified of all child changes
const containerUrl = getParentContainer(url);
if (containerUrl && containerUrl !== url) {
notifySubscribers(containerUrl);
}
}
/**
* Send pub message to all subscribers of a URL
*/
function notifySubscribers(url) {
const subs = subscribers.get(url);
if (subs) {
const message = `pub ${url}`;
for (const socket of subs) {
if (socket.readyState === 1) { // WebSocket.OPEN
try {
socket.send(message);
} catch (e) {
// Socket may have closed, will be cleaned up on close event
}
}
}
}
}
/**
* Get parent container URL from a resource URL
*/
function getParentContainer(url) {
// Remove trailing slash if present
const normalized = url.endsWith('/') ? url.slice(0, -1) : url;
const lastSlash = normalized.lastIndexOf('/');
if (lastSlash > 0) {
return normalized.substring(0, lastSlash + 1);
}
return null;
}
/**
* Get count of active subscriptions (for monitoring)
*/
export function getSubscriptionCount() {
let count = 0;
for (const urls of subscriptions.values()) {
count += urls.size;
}
return count;
}
/**
* Get count of active connections (for monitoring)
*/
export function getConnectionCount() {
return subscriptions.size;
}
// Listen to resource change events and broadcast
resourceEvents.on('change', broadcast);