uniwrtc 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.env.example ADDED
@@ -0,0 +1,8 @@
1
+ # UniWRTC Configuration Example
2
+ # Copy this file to .env and customize as needed
3
+
4
+ # Server port (default: 8080)
5
+ PORT=8080
6
+
7
+ # Optional: Enable debug logging
8
+ # DEBUG=true
@@ -0,0 +1,127 @@
1
+ # UniWRTC Cloudflare Deployment Guide
2
+
3
+ ## Prerequisites
4
+
5
+ 1. **Cloudflare Account** - Free tier is sufficient
6
+ 2. **Wrangler CLI** - Install: `npm install -g wrangler`
7
+ 3. **Node.js** - v16 or higher
8
+ 4. **Your Domain** - Domain must be on Cloudflare (e.g., `peer.ooo`)
9
+
10
+ ## Setup Steps
11
+
12
+ ### 1. Install Wrangler
13
+
14
+ ```bash
15
+ npm install -g wrangler
16
+ ```
17
+
18
+ ### 2. Authenticate with Cloudflare
19
+
20
+ ```bash
21
+ wrangler login
22
+ ```
23
+
24
+ This will open your browser to authorize the CLI.
25
+
26
+ ### 3. Update wrangler.toml
27
+
28
+ Replace the zone configuration with your domain:
29
+
30
+ ```toml
31
+ [env.production]
32
+ routes = [
33
+ { pattern = "signal.peer.ooo/*", zone_name = "peer.ooo" }
34
+ ]
35
+ ```
36
+
37
+ ### 4. Deploy to Cloudflare
38
+
39
+ ```bash
40
+ # Deploy to production
41
+ wrangler publish --env production
42
+
43
+ # Or deploy to staging first
44
+ wrangler publish
45
+ ```
46
+
47
+ ### 5. Access Your Signaling Server
48
+
49
+ Your server will be available at:
50
+ - **Production**: `https://signal.peer.ooo/`
51
+ - **Development**: `https://uniwrtc.<subdomain>.workers.dev/`
52
+
53
+ ## Using with UniWRTC Demo
54
+
55
+ Update the demo to use your Cloudflare endpoint:
56
+
57
+ ```javascript
58
+ // In demo.html or client
59
+ const serverUrl = 'https://signal.peer.ooo/';
60
+ const roomId = 'my-room';
61
+
62
+ const client = new UniWRTCClient(serverUrl, {
63
+ roomId: roomId,
64
+ customPeerId: 'optional-id'
65
+ });
66
+
67
+ await client.connect();
68
+ ```
69
+
70
+ ## How It Works
71
+
72
+ 1. **Durable Objects** - One per room, manages peer discovery
73
+ 2. **WebSocket** - Browsers connect for signaling
74
+ 3. **Signaling Only** - Offers/answers/ICE via Worker
75
+ 4. **P2P Data** - WebRTC data channels bypass Cloudflare
76
+ 5. **Free Tier** - Plenty of capacity for small deployments
77
+
78
+ ## Cost
79
+
80
+ - **Requests**: 100,000 free per day (signaling only)
81
+ - **Compute**: Included in free tier
82
+ - **Durable Objects**: ~$0.15/million operations (minimal for signaling)
83
+ - **Total**: Free to very low cost
84
+
85
+ ## Monitoring
86
+
87
+ Check deployment status:
88
+
89
+ ```bash
90
+ wrangler tail --env production
91
+ ```
92
+
93
+ View real-time logs from your Worker.
94
+
95
+ ## Local Development
96
+
97
+ Test locally before deploying:
98
+
99
+ ```bash
100
+ wrangler dev
101
+ ```
102
+
103
+ Your local server will run at `http://localhost:8787`
104
+
105
+ Update demo to test:
106
+ ```javascript
107
+ const serverUrl = 'http://localhost:8787/';
108
+ ```
109
+
110
+ ## Troubleshooting
111
+
112
+ **WebSocket errors**: Ensure your domain is on Cloudflare with SSL enabled
113
+
114
+ **Connection refused**: Check the Worker route pattern in `wrangler.toml`
115
+
116
+ **Durable Objects not found**: Run `wrangler publish` with migrations enabled
117
+
118
+ ## Next Steps
119
+
120
+ 1. Deploy the Worker
121
+ 2. Update demo.html to use your Cloudflare endpoint
122
+ 3. Test with multiple browsers
123
+ 4. Scale up!
124
+
125
+ ---
126
+
127
+ For more info: [Cloudflare Workers Docs](https://developers.cloudflare.com/workers/)
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Daniel Raeder
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,55 @@
1
+ # Quick Start - Deploy to Cloudflare in 30 seconds
2
+
3
+ ## Prerequisites
4
+ - Cloudflare account (free tier works)
5
+ - Your domain on Cloudflare
6
+ - Node.js installed
7
+
8
+ ## Deploy
9
+
10
+ ### macOS / Linux
11
+ ```bash
12
+ chmod +x deploy-cloudflare.sh
13
+ ./deploy-cloudflare.sh
14
+ ```
15
+
16
+ ### Windows
17
+ ```bash
18
+ deploy-cloudflare.bat
19
+ ```
20
+
21
+ ## What the script does:
22
+ 1. ✅ Checks Node.js and installs Wrangler
23
+ 2. ✅ Authenticates with Cloudflare
24
+ 3. ✅ Asks for your domain (e.g., `signal.peer.ooo`)
25
+ 4. ✅ Updates `wrangler.toml`
26
+ 5. ✅ Deploys to Cloudflare Workers
27
+ 6. ✅ Gives you the live URL
28
+
29
+ ## After deployment:
30
+
31
+ Update demo.html:
32
+ ```javascript
33
+ const serverUrl = 'https://signal.peer.ooo/'; // Your domain
34
+ ```
35
+
36
+ Then reload the demo and it will connect to your Cloudflare Workers signaling server! 🚀
37
+
38
+ ## Testing
39
+
40
+ Test the server:
41
+ ```bash
42
+ curl https://signal.peer.ooo/health
43
+ ```
44
+
45
+ View logs:
46
+ ```bash
47
+ wrangler tail --env production
48
+ ```
49
+
50
+ Local development:
51
+ ```bash
52
+ wrangler dev
53
+ ```
54
+
55
+ That's it! Your WebRTC signaling is now on Cloudflare! 🎉
package/README.md ADDED
@@ -0,0 +1,384 @@
1
+ # UniWRTC
2
+
3
+ A universal WebRTC signaling service that provides a simple and flexible WebSocket-based signaling server for WebRTC applications.
4
+
5
+ ## Features
6
+
7
+ - 🚀 **Simple WebSocket-based signaling** - Easy to integrate with any WebRTC application
8
+ - 🏠 **Room-based architecture** - Support for multiple rooms with isolated peer groups
9
+ - 🔌 **Flexible client library** - Ready-to-use JavaScript client for browser and Node.js
10
+ - 📡 **Real-time messaging** - Efficient message routing between peers
11
+ - 🔄 **Auto-reconnection** - Built-in reconnection logic for reliable connections
12
+ - 📊 **Health monitoring** - HTTP health check endpoint for monitoring
13
+ - 🎯 **Minimal dependencies** - Lightweight implementation using only the `ws` package
14
+
15
+ ## Quick Start
16
+
17
+ ### Installation
18
+
19
+ 1. Clone the repository:
20
+ ```bash
21
+ git clone https://github.com/draeder/UniWRTC.git
22
+ cd UniWRTC
23
+ ```
24
+
25
+ 2. Install dependencies:
26
+ ```bash
27
+ npm install
28
+ ```
29
+
30
+ 3. Start the server:
31
+ ```bash
32
+ npm start
33
+ ```
34
+
35
+ The signaling server will start on port 8080 by default.
36
+
37
+ ### Environment Configuration
38
+
39
+ Create a `.env` file based on `.env.example`:
40
+
41
+ ```bash
42
+ cp .env.example .env
43
+ ```
44
+
45
+ Configure the port:
46
+ ```
47
+ PORT=8080
48
+ ```
49
+
50
+ ### Try the Demo
51
+
52
+ Open `demo.html` in your web browser to try the interactive demo:
53
+
54
+ 1. Start the server with `npm start` (local signaling at `ws://localhost:8080`), **or** use the deployed Workers endpoint `wss://signal.peer.ooo`.
55
+ 2. Open `demo.html` in your browser.
56
+ 3. Click "Connect" to connect to the signaling server.
57
+ 4. Enter a room ID and click "Join Room".
58
+ 5. Open another browser window/tab with the same demo page.
59
+ 6. Join the same room to see peer connections in action and P2P data channels open.
60
+
61
+ ## Usage
62
+
63
+ ### Server API
64
+
65
+ The signaling server accepts WebSocket connections and supports the following message types:
66
+
67
+ #### Client → Server Messages
68
+
69
+ **Join a room:**
70
+ ```json
71
+ {
72
+ "type": "join",
73
+ "roomId": "room-123"
74
+ }
75
+ ```
76
+
77
+ **Leave a room:**
78
+ ```json
79
+ {
80
+ "type": "leave",
81
+ "roomId": "room-123"
82
+ }
83
+ ```
84
+
85
+ **Send WebRTC offer:**
86
+ ```json
87
+ {
88
+ "type": "offer",
89
+ "offer": { /* RTCSessionDescription */ },
90
+ "targetId": "peer-client-id",
91
+ "roomId": "room-123"
92
+ }
93
+ ```
94
+
95
+ **Send WebRTC answer:**
96
+ ```json
97
+ {
98
+ "type": "answer",
99
+ "answer": { /* RTCSessionDescription */ },
100
+ "targetId": "peer-client-id",
101
+ "roomId": "room-123"
102
+ }
103
+ ```
104
+
105
+ **Send ICE candidate:**
106
+ ```json
107
+ {
108
+ "type": "ice-candidate",
109
+ "candidate": { /* RTCIceCandidate */ },
110
+ "targetId": "peer-client-id",
111
+ "roomId": "room-123"
112
+ }
113
+ ```
114
+
115
+ **List available rooms:**
116
+ ```json
117
+ {
118
+ "type": "list-rooms"
119
+ }
120
+ ```
121
+
122
+ #### Server → Client Messages
123
+
124
+ **Welcome message (on connection):**
125
+ ```json
126
+ {
127
+ "type": "welcome",
128
+ "clientId": "abc123",
129
+ "message": "Connected to UniWRTC signaling server"
130
+ }
131
+ ```
132
+
133
+ **Room joined confirmation:**
134
+ ```json
135
+ {
136
+ "type": "joined",
137
+ "roomId": "room-123",
138
+ "clientId": "abc123",
139
+ "clients": ["xyz789", "def456"]
140
+ }
141
+ ```
142
+
143
+ **Peer joined notification:**
144
+ ```json
145
+ {
146
+ "type": "peer-joined",
147
+ "peerId": "new-peer-id",
148
+ "clientId": "new-peer-id"
149
+ }
150
+ ```
151
+
152
+ **Peer left notification:**
153
+ ```json
154
+ {
155
+ "type": "peer-left",
156
+ "peerId": "departed-peer-id",
157
+ "clientId": "departed-peer-id"
158
+ }
159
+ ```
160
+
161
+ ### Client Library Usage
162
+
163
+ The `client.js` library provides a convenient wrapper for the signaling protocol:
164
+
165
+ ```javascript
166
+ // Create a client instance
167
+ const client = new UniWRTCClient('ws://localhost:8080');
168
+
169
+ // Set up event handlers
170
+ client.on('connected', (data) => {
171
+ console.log('Connected with ID:', data.clientId);
172
+ });
173
+
174
+ client.on('joined', (data) => {
175
+ console.log('Joined room:', data.roomId);
176
+ console.log('Existing peers:', data.clients);
177
+ });
178
+
179
+ client.on('peer-joined', (data) => {
180
+ console.log('New peer joined:', data.peerId || data.clientId);
181
+ // Initiate WebRTC connection with new peer
182
+ });
183
+
184
+ client.on('offer', (data) => {
185
+ console.log('Received offer from:', data.peerId || data.senderId);
186
+ // Handle WebRTC offer
187
+ });
188
+
189
+ client.on('answer', (data) => {
190
+ console.log('Received answer from:', data.peerId || data.senderId);
191
+ // Handle WebRTC answer
192
+ });
193
+
194
+ client.on('ice-candidate', (data) => {
195
+ console.log('Received ICE candidate from:', data.peerId || data.senderId);
196
+ // Add ICE candidate to peer connection
197
+ });
198
+
199
+ // Connect to the server
200
+ await client.connect();
201
+
202
+ // Join a room
203
+ client.joinRoom('my-room');
204
+
205
+ // Send WebRTC signaling messages
206
+ client.sendOffer(offerObject, targetPeerId);
207
+ client.sendAnswer(answerObject, targetPeerId);
208
+ client.sendIceCandidate(candidateObject, targetPeerId);
209
+ ```
210
+
211
+ ### Integration Example
212
+
213
+ Here's a complete example of creating a WebRTC peer connection:
214
+
215
+ ```javascript
216
+ const client = new UniWRTCClient('ws://localhost:8080');
217
+ const peerConnections = new Map();
218
+
219
+ // ICE server configuration
220
+ const configuration = {
221
+ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
222
+ };
223
+
224
+ // Create peer connection
225
+ function createPeerConnection(peerId) {
226
+ const pc = new RTCPeerConnection(configuration);
227
+
228
+ pc.onicecandidate = (event) => {
229
+ if (event.candidate) {
230
+ client.sendIceCandidate(event.candidate, peerId);
231
+ }
232
+ };
233
+
234
+ pc.ontrack = (event) => {
235
+ // Handle incoming media stream
236
+ console.log('Received remote track');
237
+ };
238
+
239
+ peerConnections.set(peerId, pc);
240
+ return pc;
241
+ }
242
+
243
+ // Handle new peer
244
+ client.on('peer-joined', async (data) => {
245
+ const pc = createPeerConnection(data.clientId);
246
+
247
+ // Add local tracks
248
+ const stream = await navigator.mediaDevices.getUserMedia({
249
+ video: true,
250
+ audio: true
251
+ });
252
+ stream.getTracks().forEach(track => pc.addTrack(track, stream));
253
+
254
+ // Create and send offer
255
+ const offer = await pc.createOffer();
256
+ await pc.setLocalDescription(offer);
257
+ client.sendOffer(offer, data.clientId);
258
+ });
259
+
260
+ // Handle incoming offer
261
+ client.on('offer', async (data) => {
262
+ const pc = createPeerConnection(data.senderId);
263
+
264
+ await pc.setRemoteDescription(data.offer);
265
+ const answer = await pc.createAnswer();
266
+ await pc.setLocalDescription(answer);
267
+ client.sendAnswer(answer, data.senderId);
268
+ });
269
+
270
+ // Handle incoming answer
271
+ client.on('answer', async (data) => {
272
+ const pc = peerConnections.get(data.senderId);
273
+ if (pc) {
274
+ await pc.setRemoteDescription(data.answer);
275
+ }
276
+ });
277
+
278
+ // Handle ICE candidates
279
+ client.on('ice-candidate', async (data) => {
280
+ const pc = peerConnections.get(data.senderId);
281
+ if (pc) {
282
+ await pc.addIceCandidate(data.candidate);
283
+ }
284
+ });
285
+
286
+ // Connect and join room
287
+ await client.connect();
288
+ client.joinRoom('my-video-room');
289
+ ```
290
+
291
+ ## API Reference
292
+
293
+ ### UniWRTCClient
294
+
295
+ #### Constructor
296
+ ```javascript
297
+ new UniWRTCClient(serverUrl, options)
298
+ ```
299
+
300
+ **Parameters:**
301
+ - `serverUrl` (string): WebSocket URL of the signaling server
302
+ - `options` (object, optional):
303
+ - `autoReconnect` (boolean): Enable automatic reconnection (default: true)
304
+ - `reconnectDelay` (number): Delay between reconnection attempts in ms (default: 3000)
305
+
306
+ #### Methods
307
+
308
+ - `connect()`: Connect to the signaling server (returns Promise)
309
+ - `disconnect()`: Disconnect from the server
310
+ - `joinRoom(roomId)`: Join a specific room
311
+ - `leaveRoom()`: Leave the current room
312
+ - `sendOffer(offer, targetId)`: Send a WebRTC offer
313
+ - `sendAnswer(answer, targetId)`: Send a WebRTC answer
314
+ - `sendIceCandidate(candidate, targetId)`: Send an ICE candidate
315
+ - `listRooms()`: Request list of available rooms
316
+ - `on(event, handler)`: Register event handler
317
+ - `off(event, handler)`: Unregister event handler
318
+
319
+ #### Events
320
+
321
+ - `connected`: Fired when connected to the server
322
+ - `disconnected`: Fired when disconnected from the server
323
+ - `joined`: Fired when successfully joined a room
324
+ - `peer-joined`: Fired when another peer joins the room
325
+ - `peer-left`: Fired when a peer leaves the room
326
+ - `offer`: Fired when receiving a WebRTC offer
327
+ - `answer`: Fired when receiving a WebRTC answer
328
+ - `ice-candidate`: Fired when receiving an ICE candidate
329
+ - `room-list`: Fired when receiving the list of rooms
330
+ - `error`: Fired on error
331
+
332
+ ## Health Check
333
+
334
+ The server provides an HTTP health check endpoint:
335
+
336
+ ```bash
337
+ curl http://localhost:8080/health
338
+ ```
339
+
340
+ Response:
341
+ ```json
342
+ {
343
+ "status": "ok",
344
+ "connections": 5
345
+ }
346
+ ```
347
+
348
+ ## Architecture
349
+
350
+ ### Room Management
351
+
352
+ - Each room is identified by a unique room ID (string)
353
+ - Clients can join/leave rooms dynamically
354
+ - Messages can be sent to specific peers or broadcast to all peers in a room
355
+ - Empty rooms are automatically cleaned up
356
+
357
+ ### Message Flow
358
+
359
+ 1. Client connects via WebSocket
360
+ 2. Server assigns a unique client ID
361
+ 3. Client joins a room
362
+ 4. Server notifies existing peers about the new client
363
+ 5. Peers exchange WebRTC signaling messages through the server
364
+ 6. Server routes messages based on target ID or broadcasts to room
365
+
366
+ ## Security Considerations
367
+
368
+ This is a basic signaling server suitable for development and testing. For production use, consider:
369
+
370
+ - Adding authentication and authorization
371
+ - Implementing rate limiting
372
+ - Using TLS/WSS for encrypted connections
373
+ - Adding room access controls
374
+ - Implementing message validation
375
+ - Monitoring and logging
376
+ - Setting up CORS policies
377
+
378
+ ## License
379
+
380
+ MIT
381
+
382
+ ## Contributing
383
+
384
+ Contributions are welcome! Please feel free to submit a Pull Request.