peer-by-ip 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/LICENSE +22 -0
- package/README.md +317 -0
- package/dist/bin/peerjs.js +3 -0
- package/dist/bin/peerjs.js.map +1 -0
- package/dist/index.cjs +856 -0
- package/dist/index.cjs.map +1 -0
- package/dist/module.mjs +850 -0
- package/dist/module.mjs.map +1 -0
- package/dist/peer.d.ts +66 -0
- package/dist/peer.d.ts.map +1 -0
- package/package.json +110 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Copyright (c) 2013 Michelle Bu and Eric Zhang, http://peerjs.com
|
|
2
|
+
|
|
3
|
+
(The MIT License)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
6
|
+
a copy of this software and associated documentation files (the
|
|
7
|
+
"Software"), to deal in the Software without restriction, including
|
|
8
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
|
9
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
|
10
|
+
permit persons to whom the Software is furnished to do so, subject to
|
|
11
|
+
the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be
|
|
14
|
+
included in all copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
17
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
18
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
19
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
20
|
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
21
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
22
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
[](https://travis-ci.org/peers/peerjs-server)
|
|
2
|
+

|
|
3
|
+

|
|
4
|
+
[](https://www.npmjs.com/package/peer)
|
|
5
|
+
[](https://www.npmjs.com/package/peer)
|
|
6
|
+
[](https://hub.docker.com/r/peerjs/peerjs-server)
|
|
7
|
+
|
|
8
|
+
# PeerServer: A server for PeerJS
|
|
9
|
+
|
|
10
|
+
PeerServer helps establishing connections between PeerJS clients. Data is not proxied through the server.
|
|
11
|
+
|
|
12
|
+
Run your own server on Gitpod!
|
|
13
|
+
|
|
14
|
+
[](https://gitpod.io/#https://github.com/peers/peerjs-server)
|
|
15
|
+
|
|
16
|
+
### [https://peerjs.com](https://peerjs.com)
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
### Run server
|
|
21
|
+
|
|
22
|
+
#### Natively
|
|
23
|
+
|
|
24
|
+
If you don't want to develop anything, just enter few commands below.
|
|
25
|
+
|
|
26
|
+
1. Install the package globally:
|
|
27
|
+
```sh
|
|
28
|
+
$ npm install peer -g
|
|
29
|
+
```
|
|
30
|
+
2. Run the server:
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
$ peerjs --port 9000 --key peerjs --path /myapp
|
|
34
|
+
|
|
35
|
+
Started PeerServer on ::, port: 9000, path: /myapp (v. 0.3.2)
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
3. Check it: http://127.0.0.1:9000/myapp It should returns JSON with name, description and website fields.
|
|
39
|
+
|
|
40
|
+
#### Docker
|
|
41
|
+
|
|
42
|
+
Also, you can use Docker image to run a new container:
|
|
43
|
+
|
|
44
|
+
```sh
|
|
45
|
+
$ docker run -p 9000:9000 -d peerjs/peerjs-server
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
##### Kubernetes
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
$ kubectl run peerjs-server --image=peerjs/peerjs-server --port 9000 --expose -- --port 9000 --path /myapp
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### Create a custom server:
|
|
55
|
+
|
|
56
|
+
If you have your own server, you can attach PeerServer.
|
|
57
|
+
|
|
58
|
+
1. Install the package:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
# $ cd your-project-path
|
|
62
|
+
|
|
63
|
+
# with npm
|
|
64
|
+
$ npm install peer
|
|
65
|
+
|
|
66
|
+
# with yarn
|
|
67
|
+
$ yarn add peer
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
2. Use PeerServer object to create a new server:
|
|
71
|
+
|
|
72
|
+
```javascript
|
|
73
|
+
const { PeerServer } = require("peer");
|
|
74
|
+
|
|
75
|
+
const peerServer = PeerServer({ port: 9000, path: "/myapp" });
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
3. Check it: http://127.0.0.1:9000/myapp It should returns JSON with name, description and website fields.
|
|
79
|
+
|
|
80
|
+
### Connecting to the server from client PeerJS:
|
|
81
|
+
|
|
82
|
+
```html
|
|
83
|
+
<script>
|
|
84
|
+
const peer = new Peer("someid", {
|
|
85
|
+
host: "localhost",
|
|
86
|
+
port: 9000,
|
|
87
|
+
path: "/myapp",
|
|
88
|
+
});
|
|
89
|
+
</script>
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Config / CLI options
|
|
93
|
+
|
|
94
|
+
You can provide config object to `PeerServer` function or specify options for `peerjs` CLI.
|
|
95
|
+
|
|
96
|
+
| CLI option | JS option | Description | Required | Default |
|
|
97
|
+
| ------------------------ | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------: | :--------: |
|
|
98
|
+
| `--port, -p` | `port` | Port to listen (number) | **Yes** | |
|
|
99
|
+
| `--key, -k` | `key` | Connection key (string). Client must provide it to call API methods | No | `"peerjs"` |
|
|
100
|
+
| `--path` | `path` | Path (string). The server responds for requests to the root URL + path. **E.g.** Set the `path` to `/myapp` and run server on 9000 port via `peerjs --port 9000 --path /myapp` Then open http://127.0.0.1:9000/myapp - you should see a JSON reponse. | No | `"/"` |
|
|
101
|
+
| `--proxied` | `proxied` | Set `true` if PeerServer stays behind a reverse proxy (boolean) | No | `false` |
|
|
102
|
+
| `--expire_timeout, -t` | `expire_timeout` | The amount of time after which a message sent will expire, the sender will then receive a `EXPIRE` message (milliseconds). | No | `5000` |
|
|
103
|
+
| `--alive_timeout` | `alive_timeout` | Timeout for broken connection (milliseconds). If the server doesn't receive any data from client (includes `pong` messages), the client's connection will be destroyed. | No | `60000` |
|
|
104
|
+
| `--concurrent_limit, -c` | `concurrent_limit` | Maximum number of clients' connections to WebSocket server (number) | No | `5000` |
|
|
105
|
+
| `--sslkey` | `sslkey` | Path to SSL key (string) | No | |
|
|
106
|
+
| `--sslcert` | `sslcert` | Path to SSL certificate (string) | No | |
|
|
107
|
+
| `--allow_discovery` | `allow_discovery` | Allow to use GET `/peers` http API method to get an array of ids of all connected clients (boolean) | No | |
|
|
108
|
+
| `--cors` | `corsOptions` | The CORS origins that can access this server |
|
|
109
|
+
| | `generateClientId` | A function which generate random client IDs when calling `/id` API method (`() => string`) | No | `uuid/v4` |
|
|
110
|
+
|
|
111
|
+
## Using HTTPS
|
|
112
|
+
|
|
113
|
+
Simply pass in PEM-encoded certificate and key.
|
|
114
|
+
|
|
115
|
+
```javascript
|
|
116
|
+
const fs = require("fs");
|
|
117
|
+
const { PeerServer } = require("peer");
|
|
118
|
+
|
|
119
|
+
const peerServer = PeerServer({
|
|
120
|
+
port: 9000,
|
|
121
|
+
ssl: {
|
|
122
|
+
key: fs.readFileSync("/path/to/your/ssl/key/here.key"),
|
|
123
|
+
cert: fs.readFileSync("/path/to/your/ssl/certificate/here.crt"),
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
You can also pass any other [SSL options accepted by https.createServer](https://nodejs.org/api/https.html#https_https_createserver_options_requestlistenerfrom), such as `SNICallback:
|
|
129
|
+
|
|
130
|
+
```javascript
|
|
131
|
+
const fs = require("fs");
|
|
132
|
+
const { PeerServer } = require("peer");
|
|
133
|
+
|
|
134
|
+
const peerServer = PeerServer({
|
|
135
|
+
port: 9000,
|
|
136
|
+
ssl: {
|
|
137
|
+
SNICallback: (servername, cb) => {
|
|
138
|
+
// your code here ....
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## Running PeerServer behind a reverse proxy
|
|
145
|
+
|
|
146
|
+
Make sure to set the `proxied` option, otherwise IP based limiting will fail.
|
|
147
|
+
The option is passed verbatim to the
|
|
148
|
+
[expressjs `trust proxy` setting](http://expressjs.com/4x/api.html#app-settings)
|
|
149
|
+
if it is truthy.
|
|
150
|
+
|
|
151
|
+
```javascript
|
|
152
|
+
const { PeerServer } = require("peer");
|
|
153
|
+
|
|
154
|
+
const peerServer = PeerServer({
|
|
155
|
+
port: 9000,
|
|
156
|
+
path: "/myapp",
|
|
157
|
+
proxied: true,
|
|
158
|
+
});
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## Custom client ID generation
|
|
162
|
+
|
|
163
|
+
By default, PeerServer uses `uuid/v4` npm package to generate random client IDs.
|
|
164
|
+
|
|
165
|
+
You can set `generateClientId` option in config to specify a custom function to generate client IDs.
|
|
166
|
+
|
|
167
|
+
```javascript
|
|
168
|
+
const { PeerServer } = require("peer");
|
|
169
|
+
|
|
170
|
+
const customGenerationFunction = () =>
|
|
171
|
+
(Math.random().toString(36) + "0000000000000000000").substr(2, 16);
|
|
172
|
+
|
|
173
|
+
const peerServer = PeerServer({
|
|
174
|
+
port: 9000,
|
|
175
|
+
path: "/myapp",
|
|
176
|
+
generateClientId: customGenerationFunction,
|
|
177
|
+
});
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Open http://127.0.0.1:9000/myapp/peerjs/id to see a new random id.
|
|
181
|
+
|
|
182
|
+
## Combining with existing express app
|
|
183
|
+
|
|
184
|
+
```javascript
|
|
185
|
+
const express = require("express");
|
|
186
|
+
const { ExpressPeerServer } = require("peer");
|
|
187
|
+
|
|
188
|
+
const app = express();
|
|
189
|
+
|
|
190
|
+
app.get("/", (req, res, next) => res.send("Hello world!"));
|
|
191
|
+
|
|
192
|
+
// =======
|
|
193
|
+
|
|
194
|
+
const server = app.listen(9000);
|
|
195
|
+
|
|
196
|
+
const peerServer = ExpressPeerServer(server, {
|
|
197
|
+
path: "/myapp",
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
app.use("/peerjs", peerServer);
|
|
201
|
+
|
|
202
|
+
// == OR ==
|
|
203
|
+
|
|
204
|
+
const http = require("http");
|
|
205
|
+
|
|
206
|
+
const server = http.createServer(app);
|
|
207
|
+
const peerServer = ExpressPeerServer(server, {
|
|
208
|
+
debug: true,
|
|
209
|
+
path: "/myapp",
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
app.use("/peerjs", peerServer);
|
|
213
|
+
|
|
214
|
+
server.listen(9000);
|
|
215
|
+
|
|
216
|
+
// ========
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Open the browser and check http://127.0.0.1:9000/peerjs/myapp
|
|
220
|
+
|
|
221
|
+
## Events
|
|
222
|
+
|
|
223
|
+
The `'connection'` event is emitted when a peer connects to the server.
|
|
224
|
+
|
|
225
|
+
```javascript
|
|
226
|
+
peerServer.on('connection', (client) => { ... });
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
The `'disconnect'` event is emitted when a peer disconnects from the server or
|
|
230
|
+
when the peer can no longer be reached.
|
|
231
|
+
|
|
232
|
+
```javascript
|
|
233
|
+
peerServer.on('disconnect', (client) => { ... });
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
## HTTP API
|
|
237
|
+
|
|
238
|
+
Read [/src/api/README.md](src/api/README.md)
|
|
239
|
+
|
|
240
|
+
## Running tests
|
|
241
|
+
|
|
242
|
+
```sh
|
|
243
|
+
$ npm test
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
## Running in Google App Engine
|
|
248
|
+
|
|
249
|
+
Google App Engine will create an HTTPS certificate for you automatically,
|
|
250
|
+
making this by far the easiest way to deploy PeerJS in the Google Cloud
|
|
251
|
+
Platform.
|
|
252
|
+
|
|
253
|
+
1. Create a `package.json` file for GAE to read:
|
|
254
|
+
|
|
255
|
+
```sh
|
|
256
|
+
echo "{}" > package.json
|
|
257
|
+
npm install express@latest peer@latest
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
2. Create an `app.yaml` file to configure the GAE application.
|
|
261
|
+
|
|
262
|
+
```yaml
|
|
263
|
+
runtime: nodejs
|
|
264
|
+
|
|
265
|
+
# Flex environment required for WebSocket support, which is required for PeerJS.
|
|
266
|
+
env: flex
|
|
267
|
+
|
|
268
|
+
# Limit resources to one instance, one CPU, very little memory or disk.
|
|
269
|
+
manual_scaling:
|
|
270
|
+
instances: 1
|
|
271
|
+
resources:
|
|
272
|
+
cpu: 1
|
|
273
|
+
memory_gb: 0.5
|
|
274
|
+
disk_size_gb: 0.5
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
3. Create `server.js` (which node will run by default for the `start` script):
|
|
278
|
+
|
|
279
|
+
```js
|
|
280
|
+
const express = require("express");
|
|
281
|
+
const { ExpressPeerServer } = require("peer");
|
|
282
|
+
const app = express();
|
|
283
|
+
|
|
284
|
+
app.enable("trust proxy");
|
|
285
|
+
|
|
286
|
+
const PORT = process.env.PORT || 9000;
|
|
287
|
+
const server = app.listen(PORT, () => {
|
|
288
|
+
console.log(`App listening on port ${PORT}`);
|
|
289
|
+
console.log("Press Ctrl+C to quit.");
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
const peerServer = ExpressPeerServer(server, {
|
|
293
|
+
path: "/",
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
app.use("/", peerServer);
|
|
297
|
+
|
|
298
|
+
module.exports = app;
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
4. Deploy to an existing GAE project (assuming you are already logged in via
|
|
302
|
+
`gcloud`), replacing `YOUR-PROJECT-ID-HERE` with your particular project ID:
|
|
303
|
+
|
|
304
|
+
```sh
|
|
305
|
+
gcloud app deploy --project=YOUR-PROJECT-ID-HERE --promote --quiet app.yaml
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
## Privacy
|
|
309
|
+
|
|
310
|
+
See [PRIVACY.md](https://github.com/peers/peerjs-server/blob/master/PRIVACY.md)
|
|
311
|
+
|
|
312
|
+
## Problems?
|
|
313
|
+
|
|
314
|
+
Discuss PeerJS on our Discord community:
|
|
315
|
+
https://discord.gg/Ud2PvAtK37
|
|
316
|
+
|
|
317
|
+
Please post any bugs as a Github issue.
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import e from"node:path";import t from"node:fs";import s from"yargs";import{hideBin as r}from"yargs/helpers";import i from"express";import n from"node:http";import o from"node:https";import{randomUUID as a}from"node:crypto";import{EventEmitter as l}from"node:events";import{WebSocketServer as d}from"ws";import c from"cors";var h,g,u={host:"::",port:9e3,expire_timeout:5e3,alive_timeout:9e4,key:"peerjs",path:"/",concurrent_limit:5e3,allow_discovery:!1,proxied:!1,cleanup_out_msgs:1e3,corsOptions:{origin:!0}};class p{getLastReadAt(){return this.lastReadAt}addMessage(e){this.messages.push(e)}readMessage(){if(this.messages.length>0)return this.lastReadAt=new Date().getTime(),this.messages.shift()}getMessages(){return this.messages}constructor(){this.lastReadAt=new Date().getTime(),this.messages=[]}}class m{getClientsIds(){return[...this.clients.keys()]}getClientById(e){return this.clients.get(e)}getClientsIdsWithQueue(){return[...this.messageQueues.keys()]}setClient(e,t){this.clients.set(t,e);let s=e.getIpAddress();if(s){let r=this.clientsByIp.get(s);r||(r=new Map,this.clientsByIp.set(s,r)),r.set(t,e)}}removeClientById(e){let t=this.getClientById(e);if(!t)return!1;let s=t.getIpAddress();if(s){let t=this.clientsByIp.get(s);t&&(t.delete(e),0===t.size&&this.clientsByIp.delete(s))}return this.clients.delete(e),!0}getMessageQueueById(e){return this.messageQueues.get(e)}addMessageToQueue(e,t){this.getMessageQueueById(e)||this.messageQueues.set(e,new p),this.getMessageQueueById(e)?.addMessage(t)}clearMessageQueue(e){this.messageQueues.delete(e)}generateClientId(e){let t=e||a,s=t();for(;this.getClientById(s);)s=t();return s}getClientsByIp(e){return this.clientsByIp.get(e)}getAllIpGroups(){return this.clientsByIp}constructor(){this.clients=new Map,this.messageQueues=new Map,this.clientsByIp=new Map}}class y{constructor({realm:e,config:t,checkInterval:s=300,onClose:r}){this.timeoutId=null,this.realm=e,this.config=t,this.onClose=r,this.checkInterval=s}start(){this.timeoutId&&clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.checkConnections(),this.timeoutId=null,this.start()},this.checkInterval)}stop(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}checkConnections(){let e=this.realm.getClientsIds(),t=new Date().getTime(),{alive_timeout:s}=this.config;for(let r of e){let e=this.realm.getClientById(r);if(e&&!(t-e.getLastPing()<s))try{e.getSocket()?.close()}finally{this.realm.clearMessageQueue(r),this.realm.removeClientById(r),e.setSocket(null),this.onClose?.(e)}}}}var I=((h={}).INVALID_KEY="Invalid key provided",h.INVALID_TOKEN="Invalid token provided",h.INVALID_WS_PARAMETERS="No id, token, or key supplied to websocket server",h.CONNECTION_LIMIT_EXCEED="Server has reached its concurrent user limit",h),f=((g={}).OPEN="OPEN",g.LEAVE="LEAVE",g.CANDIDATE="CANDIDATE",g.OFFER="OFFER",g.ANSWER="ANSWER",g.EXPIRE="EXPIRE",g.HEARTBEAT="HEARTBEAT",g.ID_TAKEN="ID-TAKEN",g.ERROR="ERROR",g.PEER_JOINED_IP_GROUP="PEER-JOINED-IP-GROUP",g.PEER_LEFT_IP_GROUP="PEER-LEFT-IP-GROUP",g);class E{constructor({realm:e,config:t,messageHandler:s}){this.timeoutId=null,this.realm=e,this.config=t,this.messageHandler=s}startMessagesExpiration(){this.timeoutId&&clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.pruneOutstanding(),this.timeoutId=null,this.startMessagesExpiration()},this.config.cleanup_out_msgs)}stopMessagesExpiration(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}pruneOutstanding(){let e=this.realm.getClientsIdsWithQueue(),t=new Date().getTime(),s=this.config.expire_timeout,r={};for(let i of e){let e=this.realm.getMessageQueueById(i);if(!(!e||t-e.getLastReadAt()<s)){for(let t of e.getMessages()){let e=`${t.src}_${t.dst}`;r[e]||(this.messageHandler.handle(void 0,{type:f.EXPIRE,src:t.dst,dst:t.src}),r[e]=!0)}this.realm.clearMessageQueue(i)}}}}class S{constructor({id:e,token:t}){this.socket=null,this.lastPing=new Date().getTime(),this.ipAddress="",this.alias="",this.id=e,this.token=t}getId(){return this.id}getToken(){return this.token}getSocket(){return this.socket}setSocket(e){this.socket=e}getLastPing(){return this.lastPing}setLastPing(e){this.lastPing=e}getIpAddress(){return this.ipAddress}setIpAddress(e){this.ipAddress=e}getAlias(){return this.alias}setAlias(e){this.alias=e}send(e){this.socket?.send(JSON.stringify(e))}}let k=["Bright","Great","Smart","Swift","Bold","Calm","Cool","Warm","Happy","Lucky","Noble","Proud","Quick","Witty","Brave","Cheerful","Daring","Elegant","Fancy","Gentle","Jolly","Keen","Lively","Merry","Polite","Shiny","Stellar","Talented","Vibrant","Wise","Silly","Funky","Zany","Goofy","Wobbly","Glittery","Bouncy","Pickled","Sneaky","Nerdy","Fluffy","Spicy","Crispy","Snazzy","Quirky","Cheeky","Giggly","Breezy","Slippery"],A=["Banana","Cherry","Apple","Orange","Grape","Mango","Peach","Lemon","Melon","Berry","Pear","Plum","Kiwi","Lime","Papaya","Apricot","Fig","Coconut","Avocado","Dragon","Phoenix","Tiger","Eagle","Lion","Wolf","Bear","Hawk","Falcon","Panda","Noodle","Unicorn","Tofu","Pickle","Marshmallow","Wombat","RubberDuck","Taco","Waffle","Bubble","Squid","Hippo","Muffin","Nacho","Ginger","Squirrel","Penguin","Turtle","Otter","Dumpling"];class v extends l{constructor({server:e,realm:t,config:s}){super(),this.setMaxListeners(0),this.realm=t,this.config=s;let r=this.config.path;this.path=`${r}${r.endsWith("/")?"":"/"}peerjs`;let i={path:this.path,server:e};this.socketServer=s.createWebSocketServer?s.createWebSocketServer(i):new d(i),this.socketServer.on("connection",(e,t)=>{this._onSocketConnection(e,t)}),this.socketServer.on("error",e=>{this._onSocketError(e)})}_onSocketConnection(e,t){e.on("error",e=>{this._onSocketError(e)});let s=t.headers["x-forwarded-for"],r=t.socket.remoteAddress??"unknown";if(s){let e=(Array.isArray(s)?s[0]??"":s).split(",")[0];e&&(r=e.trim())}let{searchParams:i}=new URL(t.url??"","https://peerjs"),{id:n,token:o,key:a}=Object.fromEntries(i.entries());if(!n||!o||!a)return void this._sendErrorAndClose(e,I.INVALID_WS_PARAMETERS);if(a!==this.config.key)return void this._sendErrorAndClose(e,I.INVALID_KEY);let l=this.realm.getClientById(n);if(l){if(o!==l.getToken()){e.send(JSON.stringify({type:f.ID_TAKEN,payload:{msg:"ID is taken"}})),e.close();return}this._configureWS(e,l);return}this._registerClient({socket:e,id:n,token:o,ip:r})}_onSocketError(e){this.emit("error",e)}_registerClient({socket:e,id:t,token:s,ip:r}){let i,n;if(this.realm.getClientsIds().length>=this.config.concurrent_limit)return void this._sendErrorAndClose(e,I.CONNECTION_LIMIT_EXCEED);let o=new S({id:t,token:s});o.setIpAddress(r),o.setAlias((i=k[Math.floor(Math.random()*k.length)],n=A[Math.floor(Math.random()*A.length)],`${i} ${n}`)),this.realm.setClient(o,t),e.send(JSON.stringify({type:f.OPEN})),this._configureWS(e,o),this._notifyIpGroup(r,o.getId(),{type:f.PEER_JOINED_IP_GROUP,payload:{id:o.getId(),alias:o.getAlias(),ip:r}})}_configureWS(e,t){t.setSocket(e),e.on("close",()=>{if(t.getSocket()===e){let e=t.getIpAddress(),s=t.getId(),r=t.getAlias();this.realm.removeClientById(s),e&&this._notifyIpGroup(e,s,{type:f.PEER_LEFT_IP_GROUP,payload:{id:s,alias:r,ip:e}}),this.emit("close",t)}}),e.on("message",e=>{try{let s=JSON.parse(e.toString());s.src=t.getId(),this.emit("message",t,s)}catch(e){this.emit("error",e)}}),this.emit("connection",t)}_sendErrorAndClose(e,t){e.send(JSON.stringify({type:f.ERROR,payload:{msg:t}})),e.close()}_notifyIpGroup(e,t,s){let r=this.realm.getClientsByIp(e);if(r)for(let[e,i]of r){if(e===t)continue;let r=i.getSocket();if(r&&1===r.readyState)try{r.send(JSON.stringify(s))}catch(e){}}}}class _{registerHandler(e,t){this.handlers.has(e)||this.handlers.set(e,t)}handle(e,t){let{type:s}=t,r=this.handlers.get(s);return!!r&&r(e,t)}constructor(){this.handlers=new Map}}class R{constructor(e,t=new _){this.handlersRegistry=t;let s=(({realm:e})=>{let t=(s,r)=>{let i=r.type,n=r.src,o=r.dst,a=e.getClientById(o);if(a){let i=a.getSocket();try{if(i){let e=JSON.stringify(r);i.send(e)}else throw Error("Peer dead")}catch(r){i?i.close():e.removeClientById(a.getId()),t(s,{type:f.LEAVE,src:o,dst:n})}}else![f.LEAVE,f.EXPIRE].includes(i)&&o?e.addMessageToQueue(o,r):i!==f.LEAVE||o||e.removeClientById(n);return!0};return t})({realm:e}),r=(e,{type:t,src:r,dst:i,payload:n})=>s(e,{type:t,src:r,dst:i,payload:n});this.handlersRegistry.registerHandler(f.HEARTBEAT,(e,t)=>(e=>{if(e){let t=new Date().getTime();e.setLastPing(t)}return!0})(e)),this.handlersRegistry.registerHandler(f.OFFER,r),this.handlersRegistry.registerHandler(f.ANSWER,r),this.handlersRegistry.registerHandler(f.CANDIDATE,r),this.handlersRegistry.registerHandler(f.LEAVE,r),this.handlersRegistry.registerHandler(f.EXPIRE,r)}handle(e,t){return this.handlersRegistry.handle(e,t)}}var C={};C=JSON.parse('{"name":"PeerJS Server","description":"A server side element to broker connections between PeerJS clients.","website":"https://peerjs.com/"}');let P=s(r(process.argv)),O=!!process.env.PORT,T=P.usage("Usage: $0").wrap(Math.min(98,P.terminalWidth())).options({expire_timeout:{demandOption:!1,alias:"t",describe:"timeout (milliseconds)",default:5e3},concurrent_limit:{demandOption:!1,alias:"c",describe:"concurrent limit",default:5e3},alive_timeout:{demandOption:!1,describe:"broken connection check timeout (milliseconds)",default:6e4},key:{demandOption:!1,alias:"k",describe:"connection key",default:"peerjs"},sslkey:{type:"string",demandOption:!1,describe:"path to SSL key"},sslcert:{type:"string",demandOption:!1,describe:"path to SSL certificate"},host:{type:"string",demandOption:!1,alias:"H",describe:"host"},port:{type:"number",demandOption:!O,alias:"p",describe:"port"},path:{type:"string",demandOption:!1,describe:"custom path",default:process.env.PEERSERVER_PATH??"/"},allow_discovery:{type:"boolean",demandOption:!1,describe:"allow discovery of peers"},proxied:{type:"boolean",demandOption:!1,describe:"Set true if PeerServer stays behind a reverse proxy",default:!1},cors:{type:"string",array:!0,describe:"Set the list of CORS origins"}}).boolean("allow_discovery").parseSync();if(T.port||(T.port=parseInt(process.env.PORT)),T.cors){let e=1===T.cors.length&&"*"===T.cors[0]?"*":T.cors;T.corsOptions={origin:e}}process.on("uncaughtException",function(e){console.error("Error: "+e.toString())}),(T.sslkey??T.sslcert)&&(T.sslkey&&T.sslcert?T.ssl={key:t.readFileSync(e.resolve(T.sslkey)),cert:t.readFileSync(e.resolve(T.sslcert))}:(console.error("Warning: PeerServer will not run because either the key or the certificate has not been provided."),process.exit(1)));let w=T.path,M=function(t={},s){var r,a;let l,d,h,g=i(),p={...u,...t},I=p.port,f=p.host,{ssl:S,...k}=p;S&&Object.keys(S).length?(l=o.createServer(S,g),p=k):l=n.createServer(g),l.setMaxListeners(0);let A=(r=l,a=p,d=i(),(h={...u,...a}).proxied&&d.set("trust proxy","false"!==h.proxied&&!!h.proxied),d.on("mount",()=>{if(!r)throw Error("Server is not passed to constructor - can't start PeerServer");(({app:t,server:s,options:r})=>{let n=new m,o=new R(n),a=(({config:e,realm:t,corsOptions:s})=>{let r=i.Router();return r.use(c(s)),r.get("/",(e,t)=>{var s;t.send((s=C)&&s.__esModule?s.default:s)}),r.use("/:key",(({config:e,realm:t})=>{let s=i.Router();return s.get("/id",(s,r)=>{r.contentType("html"),r.send(t.generateClientId(e.generateClientId))}),s.get("/peers",(s,r)=>{if(e.allow_discovery){let e=t.getClientsIds();return r.send(e)}return r.sendStatus(401)}),s.get("/by-ip",(s,r)=>{if(e.allow_discovery){let e=s.headers["x-forwarded-for"],i=s.socket.remoteAddress??"unknown";if(e){let t=(Array.isArray(e)?e[0]??"":e).split(",")[0];t&&(i=t.trim())}let n=t.getClientsByIp(i);if(!n)return r.send([]);let o=Array.from(n.values()).map(e=>({id:e.getId(),alias:e.getAlias()}));return r.send(o)}return r.sendStatus(401)}),s.get("/groups",(s,r)=>{if(e.allow_discovery){let e={};for(let[s,r]of Array.from(t.getAllIpGroups().entries()))e[s]=Array.from(r.values()).map(e=>({id:e.getId(),alias:e.getAlias()}));return r.send(e)}return r.sendStatus(401)}),s})({config:e,realm:t})),r})({config:r,realm:n,corsOptions:r.corsOptions}),l=new E({realm:n,config:r,messageHandler:o}),d=new y({realm:n,config:r,onClose:e=>{t.emit("disconnect",e)}});t.use(r.path,a);let h=new v({server:s,realm:n,config:{...r,path:e.posix.join(t.path(),r.path,"/")}});h.on("connection",e=>{let s=n.getMessageQueueById(e.getId());if(s){let t;for(;t=s.readMessage();)o.handle(e,t);n.clearMessageQueue(e.getId())}t.emit("connection",e)}),h.on("message",(e,s)=>{t.emit("message",e,s),o.handle(e,s)}),h.on("close",e=>{t.emit("disconnect",e)}),h.on("error",e=>{t.emit("error",e)}),l.startMessagesExpiration(),d.start()})({app:d,server:r,options:h})}),d);return g.use(A),l.listen(I,f,()=>s?.(l)),A}(T,e=>{let{address:t,port:s}=e.address();console.log("Started PeerServer on %s, port: %s, path: %s",t,s,w||"/");let r=()=>{e.close(()=>{console.log("Http server closed."),process.exit(0)})};process.on("SIGINT",r),process.on("SIGTERM",r)});M.on("connection",e=>{console.log(`Client connected: ${e.getId()}`)}),M.on("disconnect",e=>{console.log(`Client disconnected: ${e.getId()}`)});
|
|
3
|
+
//# sourceMappingURL=peerjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"mappings":";A,O,M,W,A,Q,M,S,A,Q,M,O,A,mB,M,e,A,Q,M,S,A,Q,M,W,A,Q,M,Y,A,sB,M,a,A,wB,M,a,A,2B,M,I,A,Q,M,M,CGqCA,IMrCY,EAOA,EN8BZ,EAd+B,CAC9B,KAAM,KACN,KAAM,IACN,eAAgB,IAChB,cAAe,IACf,IAAK,SACL,KAAM,IACN,iBAAkB,IAClB,gBAAiB,CAAA,EACjB,QAAS,CAAA,EACT,iBAAkB,IAClB,YAAa,CAAE,OAAQ,CAAA,CAAK,CAC7B,CGvBO,OAAM,EAIL,eAAwB,CAC9B,OAAO,IAAI,CAAC,UAAU,AACvB,CAEO,WAAW,CAAiB,CAAQ,CAC1C,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,EACpB,CAEO,aAAoC,CAC1C,GAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAG,EAE1B,OADA,IAAI,CAAC,UAAU,CAAG,IAAI,OAAO,OAAO,GAC7B,IAAI,CAAC,QAAQ,CAAC,KAAK,EAI5B,CAEO,aAA0B,CAChC,OAAO,IAAI,CAAC,QAAQ,AACrB,C,a,CAtBQ,IAAA,CAAA,UAAA,CAAqB,IAAI,OAAO,OAAO,GAC9B,IAAA,CAAA,QAAA,CAAuB,EAAE,A,CAsB3C,CDNO,MAAM,EAKL,eAA0B,CAChC,MAAO,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,AAChC,CAEO,cAAc,CAAgB,CAAuB,CAC3D,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EACzB,CAEO,wBAAmC,CACzC,MAAO,IAAI,IAAI,CAAC,aAAa,CAAC,IAAI,GAAG,AAC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AK,SAAS,CAAC,GAClC,CACD,CClFA,IAAM,EAAa,CAClB,SACA,QACA,QACA,QACA,OACA,OACA,OACA,OACA,QACA,QACA,QACA,QACA,QACA,QACA,QACA,WACA,SACA,UACA,QACA,SACA,QACA,OACA,SACA,QACA,SACA,QACA,UACA,WACA,UACA,OAEA,QACA,QACA,OACA,QACA,SACA,WACA,SACA,UACA,SACA,QACA,SACA,QACA,SACA,SACA,SACA,SACA,SACA,SACA,WACA,CAEK,EAAQ,CACb,SACA,SACA,QACA,SACA,QACA,QACA,QACA,QACA,QACA,QACA,OACA,OACA,OACA,OACA,SACA,UACA,MACA,UACA,UACA,SACA,UACA,QACA,QACA,OACA,OACA,OACA,OACA,SACA,QAEA,SACA,UACA,OACA,SACA,cACA,SACA,aACA,OACA,SACA,SACA,QACA,QACA,SACA,QACA,SACA,WACA,UACA,SACA,QACA,WACA,AF/EM,OAAM,UAAwB,EAMpC,YAAY,CAAA,OACX,CAAM,CAAA,MACN,CAAK,CAAA,OACL,CAAM,CAKN,CAAE,CACF,KAAK,GAEL,IAAI,CAAC,eAAe,CAAC,GAErB,IAAI,CAAC,KAAK,CAAG,EACb,IAAI,CAAC,MAAM,CAAG,EAEd,IAAM,EAAO,IAAI,CAAC,MAAM,CAAC,IAAI,AAC7B,CAAA,IAAI,CAAC,IAAI,CAAG,GAAG,IAAO,EAAK,QAAQ,CAAC,KAAO,GAAK,WAAe,CAE/D,IAAM,EAAmC,CACxC,KAAM,IAAI,CAAC,IAAI,CACf,OAAA,CACD,CAEA,CAAA,IAAI,CAAC,YAAY,CAAG,EAAO,qBAAqB,CAC7C,EAAO,qBAAqB,CAAC,GAC7B,IAAI,EAAO,GAEd,IAAI,CAAC,YAAY,CAAC,EAAE,CAAC,aAAc,CAAC,EAAQ,KAC3C,IAAI,CAAC,mBAAmB,CAAC,EAAQ,EAClC,GACA,IAAI,CAAC,YAAY,CAAC,EAAE,CAAC,QAAS,AAAC,IAC9B,IAAI,CAAC,cAAc,CAAC,EAC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,EAAI,IAAI,CAAC,aAAc,EACxB,GAEA,EAAI,EAAE,CAAC,QAAS,AAAC,IAChB,EAAI,IAAI,CAAC,QAAS,EACnB,GAEA,EAAe,uBAAuB,GACtC,EAAuB,KAAK,EAC7B,CAAA,EF3DiB,CAAE,IAAA,EAAK,OAAA,EAAQ,QAAS,CAAW,EACnD,GAEO,GAoCP,OAJA,EAAI,GAAG,CAAC,GAER,EAAO,MAAM,CAAC,EAAM,EAAM,IAAM,IAAW,IAEpC,CACR,ED6C0B,EAAM,AAAC,IAChC,GAAM,CAAE,QAAS,CAAI,CAAA,KAAE,CAAI,CAAE,CAAG,EAAO,OAAO,GAE9C,QAAQ,GAAG,CACV,+CACA,EACA,EACA,GAAY,KAGb,IAAM,EAAc,KACnB,EAAO,KAAK,CAAC,KACZ,QAAQ,GAAG,CAAC,uBAEZ,QAAQ,IAAI,CAAC,EACd,EACD,EAEA,QAAQ,EAAE,CAAC,SAAU,GACrB,QAAQ,EAAE,CAAC,UAAW,EACvB,GAEA,EAAO,EAAE,CAAC,aAAc,AAAC,IACxB,QAAQ,GAAG,CAAC,CAAC,kBAAkB,EAAE,EAAO,KAAK,GAAA,CAAI,CAClD,GAEA,EAAO,EAAE,CAAC,aAAc,AAAC,IACxB,QAAQ,GAAG,CAAC,CAAC,qBAAqB,EAAE,EAAO,KAAK,GAAA,CAAI,CACrD","sources":["<anon>","bin/peerjs.ts","src/index.ts","src/config/index.ts","src/instance.ts","src/models/realm.ts","src/models/messageQueue.ts","src/services/checkBrokenConnections/index.ts","src/services/messagesExpire/index.ts","src/enums.ts","src/services/webSocketServer/index.ts","src/models/client.ts","src/utils/aliasGenerator.ts","src/messageHandler/index.ts","src/messageHandler/handlers/index.ts","src/messageHandler/handlers/heartbeat/index.ts","src/messageHandler/handlers/transmission/index.ts","src/messageHandler/handlersRegistry.ts","src/api/index.ts","app.json","src/api/v1/public/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport $7BbP7$nodepath from \"node:path\";\nimport $7BbP7$nodefs from \"node:fs\";\nimport $7BbP7$yargs from \"yargs\";\nimport {hideBin as $7BbP7$hideBin} from \"yargs/helpers\";\nimport $7BbP7$express from \"express\";\nimport $7BbP7$nodehttp from \"node:http\";\nimport $7BbP7$nodehttps from \"node:https\";\nimport {randomUUID as $7BbP7$randomUUID} from \"node:crypto\";\nimport {EventEmitter as $7BbP7$EventEmitter} from \"node:events\";\nimport {WebSocketServer as $7BbP7$WebSocketServer} from \"ws\";\nimport $7BbP7$cors from \"cors\";\n\n\nfunction $parcel$interopDefault(a) {\n return a && a.__esModule ? a.default : a;\n}\nvar $3809f3d53201df9f$exports = {};\n\n\n\n\n\n\n\nconst $aeb1147dec1b7a02$var$defaultConfig = {\n host: \"::\",\n port: 9000,\n expire_timeout: 5000,\n alive_timeout: 90000,\n key: \"peerjs\",\n path: \"/\",\n concurrent_limit: 5000,\n allow_discovery: false,\n proxied: false,\n cleanup_out_msgs: 1000,\n corsOptions: {\n origin: true\n }\n};\nvar $aeb1147dec1b7a02$export$2e2bcd8739ae039 = $aeb1147dec1b7a02$var$defaultConfig;\n\n\n\nclass $2c42eaf0ccc66758$export$eb4c623330d4cbcc {\n getLastReadAt() {\n return this.lastReadAt;\n }\n addMessage(message) {\n this.messages.push(message);\n }\n readMessage() {\n if (this.messages.length > 0) {\n this.lastReadAt = new Date().getTime();\n return this.messages.shift();\n }\n return undefined;\n }\n getMessages() {\n return this.messages;\n }\n constructor(){\n this.lastReadAt = new Date().getTime();\n this.messages = [];\n }\n}\n\n\n\nclass $0a339ca52e0451c9$export$3ee29d34e33d9116 {\n getClientsIds() {\n return [\n ...this.clients.keys()\n ];\n }\n getClientById(clientId) {\n return this.clients.get(clientId);\n }\n getClientsIdsWithQueue() {\n return [\n ...this.messageQueues.keys()\n ];\n }\n setClient(client, id) {\n this.clients.set(id, client);\n // Add to IP-based grouping\n const ip = client.getIpAddress();\n if (ip) {\n let ipGroup = this.clientsByIp.get(ip);\n if (!ipGroup) {\n ipGroup = new Map();\n this.clientsByIp.set(ip, ipGroup);\n }\n ipGroup.set(id, client);\n }\n }\n removeClientById(id) {\n const client = this.getClientById(id);\n if (!client) return false;\n // Remove from IP-based grouping\n const ip = client.getIpAddress();\n if (ip) {\n const ipGroup = this.clientsByIp.get(ip);\n if (ipGroup) {\n ipGroup.delete(id);\n if (ipGroup.size === 0) this.clientsByIp.delete(ip);\n }\n }\n this.clients.delete(id);\n return true;\n }\n getMessageQueueById(id) {\n return this.messageQueues.get(id);\n }\n addMessageToQueue(id, message) {\n if (!this.getMessageQueueById(id)) this.messageQueues.set(id, new (0, $2c42eaf0ccc66758$export$eb4c623330d4cbcc)());\n this.getMessageQueueById(id)?.addMessage(message);\n }\n clearMessageQueue(id) {\n this.messageQueues.delete(id);\n }\n generateClientId(generateClientId) {\n const generateId = generateClientId ? generateClientId : (0, $7BbP7$randomUUID);\n let clientId = generateId();\n while(this.getClientById(clientId))clientId = generateId();\n return clientId;\n }\n getClientsByIp(ipAddress) {\n return this.clientsByIp.get(ipAddress);\n }\n getAllIpGroups() {\n return this.clientsByIp;\n }\n constructor(){\n this.clients = new Map();\n this.messageQueues = new Map();\n this.clientsByIp = new Map();\n }\n}\n\n\nconst $6840aafc61c9abd6$var$DEFAULT_CHECK_INTERVAL = 300;\nclass $6840aafc61c9abd6$export$6fa53df6b5b88df7 {\n constructor({ realm: realm, config: config, checkInterval: checkInterval = $6840aafc61c9abd6$var$DEFAULT_CHECK_INTERVAL, onClose: onClose }){\n this.timeoutId = null;\n this.realm = realm;\n this.config = config;\n this.onClose = onClose;\n this.checkInterval = checkInterval;\n }\n start() {\n if (this.timeoutId) clearTimeout(this.timeoutId);\n this.timeoutId = setTimeout(()=>{\n this.checkConnections();\n this.timeoutId = null;\n this.start();\n }, this.checkInterval);\n }\n stop() {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId);\n this.timeoutId = null;\n }\n }\n checkConnections() {\n const clientsIds = this.realm.getClientsIds();\n const now = new Date().getTime();\n const { alive_timeout: aliveTimeout } = this.config;\n for (const clientId of clientsIds){\n const client = this.realm.getClientById(clientId);\n if (!client) continue;\n const timeSinceLastPing = now - client.getLastPing();\n if (timeSinceLastPing < aliveTimeout) continue;\n try {\n client.getSocket()?.close();\n } finally{\n this.realm.clearMessageQueue(clientId);\n this.realm.removeClientById(clientId);\n client.setSocket(null);\n this.onClose?.(client);\n }\n }\n }\n}\n\n\nvar $d461d7260b6fc353$export$b8e9cd941e8016ac = /*#__PURE__*/ function(Errors) {\n Errors[\"INVALID_KEY\"] = \"Invalid key provided\";\n Errors[\"INVALID_TOKEN\"] = \"Invalid token provided\";\n Errors[\"INVALID_WS_PARAMETERS\"] = \"No id, token, or key supplied to websocket server\";\n Errors[\"CONNECTION_LIMIT_EXCEED\"] = \"Server has reached its concurrent user limit\";\n return Errors;\n}({});\nvar $d461d7260b6fc353$export$80edbf15fa61a4db = /*#__PURE__*/ function(MessageType) {\n MessageType[\"OPEN\"] = \"OPEN\";\n MessageType[\"LEAVE\"] = \"LEAVE\";\n MessageType[\"CANDIDATE\"] = \"CANDIDATE\";\n MessageType[\"OFFER\"] = \"OFFER\";\n MessageType[\"ANSWER\"] = \"ANSWER\";\n MessageType[\"EXPIRE\"] = \"EXPIRE\";\n MessageType[\"HEARTBEAT\"] = \"HEARTBEAT\";\n MessageType[\"ID_TAKEN\"] = \"ID-TAKEN\";\n MessageType[\"ERROR\"] = \"ERROR\";\n MessageType[\"PEER_JOINED_IP_GROUP\"] = \"PEER-JOINED-IP-GROUP\";\n MessageType[\"PEER_LEFT_IP_GROUP\"] = \"PEER-LEFT-IP-GROUP\";\n return MessageType;\n}({});\n\n\nclass $c97baf9b78981954$export$a13b411d0e88b1af {\n constructor({ realm: realm, config: config, messageHandler: messageHandler }){\n this.timeoutId = null;\n this.realm = realm;\n this.config = config;\n this.messageHandler = messageHandler;\n }\n startMessagesExpiration() {\n if (this.timeoutId) clearTimeout(this.timeoutId);\n // Clean up outstanding messages\n this.timeoutId = setTimeout(()=>{\n this.pruneOutstanding();\n this.timeoutId = null;\n this.startMessagesExpiration();\n }, this.config.cleanup_out_msgs);\n }\n stopMessagesExpiration() {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId);\n this.timeoutId = null;\n }\n }\n pruneOutstanding() {\n const destinationClientsIds = this.realm.getClientsIdsWithQueue();\n const now = new Date().getTime();\n const maxDiff = this.config.expire_timeout;\n const seen = {};\n for (const destinationClientId of destinationClientsIds){\n const messageQueue = this.realm.getMessageQueueById(destinationClientId);\n if (!messageQueue) continue;\n const lastReadDiff = now - messageQueue.getLastReadAt();\n if (lastReadDiff < maxDiff) continue;\n const messages = messageQueue.getMessages();\n for (const message of messages){\n const seenKey = `${message.src}_${message.dst}`;\n if (!seen[seenKey]) {\n this.messageHandler.handle(undefined, {\n type: (0, $d461d7260b6fc353$export$80edbf15fa61a4db).EXPIRE,\n src: message.dst,\n dst: message.src\n });\n seen[seenKey] = true;\n }\n }\n this.realm.clearMessageQueue(destinationClientId);\n }\n }\n}\n\n\n\n\nclass $d09fcb6ab78a3f48$export$1f2bb630327ac4b6 {\n constructor({ id: id, token: token }){\n this.socket = null;\n this.lastPing = new Date().getTime();\n this.ipAddress = \"\";\n this.alias = \"\";\n this.id = id;\n this.token = token;\n }\n getId() {\n return this.id;\n }\n getToken() {\n return this.token;\n }\n getSocket() {\n return this.socket;\n }\n setSocket(socket) {\n this.socket = socket;\n }\n getLastPing() {\n return this.lastPing;\n }\n setLastPing(lastPing) {\n this.lastPing = lastPing;\n }\n getIpAddress() {\n return this.ipAddress;\n }\n setIpAddress(ip) {\n this.ipAddress = ip;\n }\n getAlias() {\n return this.alias;\n }\n setAlias(alias) {\n this.alias = alias;\n }\n send(data) {\n this.socket?.send(JSON.stringify(data));\n }\n}\n\n\n\nconst $e99ba8b80c5ab00c$var$adjectives = [\n \"Bright\",\n \"Great\",\n \"Smart\",\n \"Swift\",\n \"Bold\",\n \"Calm\",\n \"Cool\",\n \"Warm\",\n \"Happy\",\n \"Lucky\",\n \"Noble\",\n \"Proud\",\n \"Quick\",\n \"Witty\",\n \"Brave\",\n \"Cheerful\",\n \"Daring\",\n \"Elegant\",\n \"Fancy\",\n \"Gentle\",\n \"Jolly\",\n \"Keen\",\n \"Lively\",\n \"Merry\",\n \"Polite\",\n \"Shiny\",\n \"Stellar\",\n \"Talented\",\n \"Vibrant\",\n \"Wise\",\n // Funny additions\n \"Silly\",\n \"Funky\",\n \"Zany\",\n \"Goofy\",\n \"Wobbly\",\n \"Glittery\",\n \"Bouncy\",\n \"Pickled\",\n \"Sneaky\",\n \"Nerdy\",\n \"Fluffy\",\n \"Spicy\",\n \"Crispy\",\n \"Snazzy\",\n \"Quirky\",\n \"Cheeky\",\n \"Giggly\",\n \"Breezy\",\n \"Slippery\"\n];\nconst $e99ba8b80c5ab00c$var$nouns = [\n \"Banana\",\n \"Cherry\",\n \"Apple\",\n \"Orange\",\n \"Grape\",\n \"Mango\",\n \"Peach\",\n \"Lemon\",\n \"Melon\",\n \"Berry\",\n \"Pear\",\n \"Plum\",\n \"Kiwi\",\n \"Lime\",\n \"Papaya\",\n \"Apricot\",\n \"Fig\",\n \"Coconut\",\n \"Avocado\",\n \"Dragon\",\n \"Phoenix\",\n \"Tiger\",\n \"Eagle\",\n \"Lion\",\n \"Wolf\",\n \"Bear\",\n \"Hawk\",\n \"Falcon\",\n \"Panda\",\n // Funny additions\n \"Noodle\",\n \"Unicorn\",\n \"Tofu\",\n \"Pickle\",\n \"Marshmallow\",\n \"Wombat\",\n \"RubberDuck\",\n \"Taco\",\n \"Waffle\",\n \"Bubble\",\n \"Squid\",\n \"Hippo\",\n \"Muffin\",\n \"Nacho\",\n \"Ginger\",\n \"Squirrel\",\n \"Penguin\",\n \"Turtle\",\n \"Otter\",\n \"Dumpling\"\n];\nfunction $e99ba8b80c5ab00c$export$65b9416602f2db62() {\n const adjective = $e99ba8b80c5ab00c$var$adjectives[Math.floor(Math.random() * $e99ba8b80c5ab00c$var$adjectives.length)];\n const noun = $e99ba8b80c5ab00c$var$nouns[Math.floor(Math.random() * $e99ba8b80c5ab00c$var$nouns.length)];\n return `${adjective} ${noun}`;\n}\n\n\nconst $4ae24f8b3b7cf7b0$var$WS_PATH = \"peerjs\";\nclass $4ae24f8b3b7cf7b0$export$f47674b57e51ee3b extends (0, $7BbP7$EventEmitter) {\n constructor({ server: server, realm: realm, config: config }){\n super();\n this.setMaxListeners(0);\n this.realm = realm;\n this.config = config;\n const path = this.config.path;\n this.path = `${path}${path.endsWith(\"/\") ? \"\" : \"/\"}${$4ae24f8b3b7cf7b0$var$WS_PATH}`;\n const options = {\n path: this.path,\n server: server\n };\n this.socketServer = config.createWebSocketServer ? config.createWebSocketServer(options) : new (0, $7BbP7$WebSocketServer)(options);\n this.socketServer.on(\"connection\", (socket, req)=>{\n this._onSocketConnection(socket, req);\n });\n this.socketServer.on(\"error\", (error)=>{\n this._onSocketError(error);\n });\n }\n _onSocketConnection(socket, req) {\n // An unhandled socket error might crash the server. Handle it first.\n socket.on(\"error\", (error)=>{\n this._onSocketError(error);\n });\n // Extract IP address (handle proxied requests)\n const forwardedFor = req.headers[\"x-forwarded-for\"];\n let ip = req.socket.remoteAddress ?? \"unknown\";\n if (forwardedFor) {\n const forwardedIp = Array.isArray(forwardedFor) ? forwardedFor[0] ?? \"\" : forwardedFor;\n const firstIp = forwardedIp.split(\",\")[0];\n if (firstIp) ip = firstIp.trim();\n }\n // We are only interested in the query, the base url is therefore not relevant\n const { searchParams: searchParams } = new URL(req.url ?? \"\", \"https://peerjs\");\n const { id: id, token: token, key: key } = Object.fromEntries(searchParams.entries());\n if (!id || !token || !key) {\n this._sendErrorAndClose(socket, (0, $d461d7260b6fc353$export$b8e9cd941e8016ac).INVALID_WS_PARAMETERS);\n return;\n }\n if (key !== this.config.key) {\n this._sendErrorAndClose(socket, (0, $d461d7260b6fc353$export$b8e9cd941e8016ac).INVALID_KEY);\n return;\n }\n const client = this.realm.getClientById(id);\n if (client) {\n if (token !== client.getToken()) {\n // ID-taken, invalid token\n socket.send(JSON.stringify({\n type: (0, $d461d7260b6fc353$export$80edbf15fa61a4db).ID_TAKEN,\n payload: {\n msg: \"ID is taken\"\n }\n }));\n socket.close();\n return;\n }\n this._configureWS(socket, client);\n return;\n }\n this._registerClient({\n socket: socket,\n id: id,\n token: token,\n ip: ip\n });\n }\n _onSocketError(error) {\n // handle error\n this.emit(\"error\", error);\n }\n _registerClient({ socket: socket, id: id, token: token, ip: ip }) {\n // Check concurrent limit\n const clientsCount = this.realm.getClientsIds().length;\n if (clientsCount >= this.config.concurrent_limit) {\n this._sendErrorAndClose(socket, (0, $d461d7260b6fc353$export$b8e9cd941e8016ac).CONNECTION_LIMIT_EXCEED);\n return;\n }\n const newClient = new (0, $d09fcb6ab78a3f48$export$1f2bb630327ac4b6)({\n id: id,\n token: token\n });\n newClient.setIpAddress(ip);\n newClient.setAlias((0, $e99ba8b80c5ab00c$export$65b9416602f2db62)());\n this.realm.setClient(newClient, id);\n socket.send(JSON.stringify({\n type: (0, $d461d7260b6fc353$export$80edbf15fa61a4db).OPEN\n }));\n this._configureWS(socket, newClient);\n // Notify other clients in the same IP group about the new peer\n this._notifyIpGroup(ip, newClient.getId(), {\n type: (0, $d461d7260b6fc353$export$80edbf15fa61a4db).PEER_JOINED_IP_GROUP,\n payload: {\n id: newClient.getId(),\n alias: newClient.getAlias(),\n ip: ip\n }\n });\n }\n _configureWS(socket, client) {\n client.setSocket(socket);\n // Cleanup after a socket closes.\n socket.on(\"close\", ()=>{\n if (client.getSocket() === socket) {\n const clientIp = client.getIpAddress();\n const clientId = client.getId();\n const clientAlias = client.getAlias();\n this.realm.removeClientById(clientId);\n // Notify other clients in the same IP group about the peer leaving\n if (clientIp) this._notifyIpGroup(clientIp, clientId, {\n type: (0, $d461d7260b6fc353$export$80edbf15fa61a4db).PEER_LEFT_IP_GROUP,\n payload: {\n id: clientId,\n alias: clientAlias,\n ip: clientIp\n }\n });\n this.emit(\"close\", client);\n }\n });\n // Handle messages from peers.\n socket.on(\"message\", (data)=>{\n try {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n const message = JSON.parse(data.toString());\n message.src = client.getId();\n this.emit(\"message\", client, message);\n } catch (e) {\n this.emit(\"error\", e);\n }\n });\n this.emit(\"connection\", client);\n }\n _sendErrorAndClose(socket, msg) {\n socket.send(JSON.stringify({\n type: (0, $d461d7260b6fc353$export$80edbf15fa61a4db).ERROR,\n payload: {\n msg: msg\n }\n }));\n socket.close();\n }\n /**\n\t * Notify all clients in the same IP group about a peer event\n\t * @param ip - The IP address of the group\n\t * @param excludeClientId - Client ID to exclude from notification (usually the one triggering the event)\n\t * @param message - The message to send\n\t */ _notifyIpGroup(ip, excludeClientId, message) {\n const ipGroup = this.realm.getClientsByIp(ip);\n if (!ipGroup) return;\n for (const [clientId, client] of ipGroup){\n // Don't notify the client that triggered the event\n if (clientId === excludeClientId) continue;\n const socket = client.getSocket();\n if (socket && socket.readyState === 1) // WebSocket.OPEN = 1\n try {\n socket.send(JSON.stringify(message));\n } catch (e) {\n // Ignore send errors for now\n }\n }\n }\n}\n\n\n\nconst $c523c19e3fc944a1$export$65302b915833a46d = (client)=>{\n if (client) {\n const nowTime = new Date().getTime();\n client.setLastPing(nowTime);\n }\n return true;\n};\n\n\n\nconst $879e80f95ec634eb$export$809c011ea942310 = ({ realm: realm })=>{\n const handle = (client, message)=>{\n const type = message.type;\n const srcId = message.src;\n const dstId = message.dst;\n const destinationClient = realm.getClientById(dstId);\n // User is connected!\n if (destinationClient) {\n const socket = destinationClient.getSocket();\n try {\n if (socket) {\n const data = JSON.stringify(message);\n socket.send(data);\n } else // Neither socket no res available. Peer dead?\n throw new Error(\"Peer dead\");\n } catch (e) {\n // This happens when a peer disconnects without closing connections and\n // the associated WebSocket has not closed.\n // Tell other side to stop trying.\n if (socket) socket.close();\n else realm.removeClientById(destinationClient.getId());\n handle(client, {\n type: (0, $d461d7260b6fc353$export$80edbf15fa61a4db).LEAVE,\n src: dstId,\n dst: srcId\n });\n }\n } else {\n // Wait for this client to connect/reconnect (XHR) for important\n // messages.\n const ignoredTypes = [\n (0, $d461d7260b6fc353$export$80edbf15fa61a4db).LEAVE,\n (0, $d461d7260b6fc353$export$80edbf15fa61a4db).EXPIRE\n ];\n if (!ignoredTypes.includes(type) && dstId) realm.addMessageToQueue(dstId, message);\n else if (type === (0, $d461d7260b6fc353$export$80edbf15fa61a4db).LEAVE && !dstId) realm.removeClientById(srcId);\n }\n return true;\n };\n return handle;\n};\n\n\n\n\nclass $df0509eaca4ae82c$export$cfe4a96645b0bbcf {\n registerHandler(messageType, handler) {\n if (this.handlers.has(messageType)) return;\n this.handlers.set(messageType, handler);\n }\n handle(client, message) {\n const { type: type } = message;\n const handler = this.handlers.get(type);\n if (!handler) return false;\n return handler(client, message);\n }\n constructor(){\n this.handlers = new Map();\n }\n}\n\n\nclass $3089a9bad51bbb04$export$3deceafe0aaeaa95 {\n constructor(realm, handlersRegistry = new (0, $df0509eaca4ae82c$export$cfe4a96645b0bbcf)()){\n this.handlersRegistry = handlersRegistry;\n const transmissionHandler = (0, $879e80f95ec634eb$export$809c011ea942310)({\n realm: realm\n });\n const heartbeatHandler = (0, $c523c19e3fc944a1$export$65302b915833a46d);\n const handleTransmission = (client, { type: type, src: src, dst: dst, payload: payload })=>{\n return transmissionHandler(client, {\n type: type,\n src: src,\n dst: dst,\n payload: payload\n });\n };\n const handleHeartbeat = (client, message)=>heartbeatHandler(client, message);\n this.handlersRegistry.registerHandler((0, $d461d7260b6fc353$export$80edbf15fa61a4db).HEARTBEAT, handleHeartbeat);\n this.handlersRegistry.registerHandler((0, $d461d7260b6fc353$export$80edbf15fa61a4db).OFFER, handleTransmission);\n this.handlersRegistry.registerHandler((0, $d461d7260b6fc353$export$80edbf15fa61a4db).ANSWER, handleTransmission);\n this.handlersRegistry.registerHandler((0, $d461d7260b6fc353$export$80edbf15fa61a4db).CANDIDATE, handleTransmission);\n this.handlersRegistry.registerHandler((0, $d461d7260b6fc353$export$80edbf15fa61a4db).LEAVE, handleTransmission);\n this.handlersRegistry.registerHandler((0, $d461d7260b6fc353$export$80edbf15fa61a4db).EXPIRE, handleTransmission);\n }\n handle(client, message) {\n return this.handlersRegistry.handle(client, message);\n }\n}\n\n\n\n\nvar $264fdbd7932d14df$exports = {};\n$264fdbd7932d14df$exports = JSON.parse(\"{\\\"name\\\":\\\"PeerJS Server\\\",\\\"description\\\":\\\"A server side element to broker connections between PeerJS clients.\\\",\\\"website\\\":\\\"https://peerjs.com/\\\"}\");\n\n\n\nvar $6910ff2a5db5006f$export$2e2bcd8739ae039 = ({ config: config, realm: realm })=>{\n const app = (0, $7BbP7$express).Router();\n // Retrieve guaranteed random ID.\n app.get(\"/id\", (_, res)=>{\n res.contentType(\"html\");\n res.send(realm.generateClientId(config.generateClientId));\n });\n // Get a list of all peers for a key, enabled by the `allowDiscovery` flag.\n app.get(\"/peers\", (_, res)=>{\n if (config.allow_discovery) {\n const clientsIds = realm.getClientsIds();\n return res.send(clientsIds);\n }\n return res.sendStatus(401);\n });\n // Get all peers from the same IP as the requesting client\n app.get(\"/by-ip\", (req, res)=>{\n if (config.allow_discovery) {\n // Extract client's IP address from request\n const forwardedFor = req.headers[\"x-forwarded-for\"];\n let clientIp = req.socket.remoteAddress ?? \"unknown\";\n if (forwardedFor) {\n const forwardedIp = Array.isArray(forwardedFor) ? forwardedFor[0] ?? \"\" : forwardedFor;\n const firstIp = forwardedIp.split(\",\")[0];\n if (firstIp) clientIp = firstIp.trim();\n }\n const ipGroup = realm.getClientsByIp(clientIp);\n if (!ipGroup) return res.send([]);\n const peers = Array.from(ipGroup.values()).map((client)=>({\n id: client.getId(),\n alias: client.getAlias()\n }));\n return res.send(peers);\n }\n return res.sendStatus(401);\n });\n // Get all IP groups (admin/debugging endpoint)\n app.get(\"/groups\", (_, res)=>{\n if (config.allow_discovery) {\n const result = {};\n const ipGroups = Array.from(realm.getAllIpGroups().entries());\n for (const [ip, clients] of ipGroups)result[ip] = Array.from(clients.values()).map((client)=>({\n id: client.getId(),\n alias: client.getAlias()\n }));\n return res.send(result);\n }\n return res.sendStatus(401);\n });\n return app;\n};\n\n\nconst $69f9994c6ebd6802$export$bf71da7aebe9ddc1 = ({ config: config, realm: realm, corsOptions: corsOptions })=>{\n const app = (0, $7BbP7$express).Router();\n app.use((0, $7BbP7$cors)(corsOptions));\n app.get(\"/\", (_, res)=>{\n res.send((0, (/*@__PURE__*/$parcel$interopDefault($264fdbd7932d14df$exports))));\n });\n app.use(\"/:key\", (0, $6910ff2a5db5006f$export$2e2bcd8739ae039)({\n config: config,\n realm: realm\n }));\n return app;\n};\n\n\nconst $e7d4fd16baa81890$export$99152e8d49ca4e7d = ({ app: app, server: server, options: options })=>{\n const config = options;\n const realm = new (0, $0a339ca52e0451c9$export$3ee29d34e33d9116)();\n const messageHandler = new (0, $3089a9bad51bbb04$export$3deceafe0aaeaa95)(realm);\n const api = (0, $69f9994c6ebd6802$export$bf71da7aebe9ddc1)({\n config: config,\n realm: realm,\n corsOptions: options.corsOptions\n });\n const messagesExpire = new (0, $c97baf9b78981954$export$a13b411d0e88b1af)({\n realm: realm,\n config: config,\n messageHandler: messageHandler\n });\n const checkBrokenConnections = new (0, $6840aafc61c9abd6$export$6fa53df6b5b88df7)({\n realm: realm,\n config: config,\n onClose: (client)=>{\n app.emit(\"disconnect\", client);\n }\n });\n app.use(options.path, api);\n //use mountpath for WS server\n const customConfig = {\n ...config,\n path: (0, $7BbP7$nodepath).posix.join(app.path(), options.path, \"/\")\n };\n const wss = new (0, $4ae24f8b3b7cf7b0$export$f47674b57e51ee3b)({\n server: server,\n realm: realm,\n config: customConfig\n });\n wss.on(\"connection\", (client)=>{\n const messageQueue = realm.getMessageQueueById(client.getId());\n if (messageQueue) {\n let message;\n while(message = messageQueue.readMessage())messageHandler.handle(client, message);\n realm.clearMessageQueue(client.getId());\n }\n app.emit(\"connection\", client);\n });\n wss.on(\"message\", (client, message)=>{\n app.emit(\"message\", client, message);\n messageHandler.handle(client, message);\n });\n wss.on(\"close\", (client)=>{\n app.emit(\"disconnect\", client);\n });\n wss.on(\"error\", (error)=>{\n app.emit(\"error\", error);\n });\n messagesExpire.startMessagesExpiration();\n checkBrokenConnections.start();\n};\n\n\nfunction $0fe9c43b5c368182$export$8c57434a18c696c9(server, options) {\n const app = (0, $7BbP7$express)();\n const newOptions = {\n ...(0, $aeb1147dec1b7a02$export$2e2bcd8739ae039),\n ...options\n };\n if (newOptions.proxied) app.set(\"trust proxy\", newOptions.proxied === \"false\" ? false : !!newOptions.proxied);\n app.on(\"mount\", ()=>{\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!server) throw new Error(\"Server is not passed to constructor - can't start PeerServer\");\n (0, $e7d4fd16baa81890$export$99152e8d49ca4e7d)({\n app: app,\n server: server,\n options: newOptions\n });\n });\n return app;\n}\nfunction $0fe9c43b5c368182$export$f99d31af51f48b1e(options = {}, callback) {\n const app = (0, $7BbP7$express)();\n let newOptions = {\n ...(0, $aeb1147dec1b7a02$export$2e2bcd8739ae039),\n ...options\n };\n const port = newOptions.port;\n const host = newOptions.host;\n let server;\n const { ssl: ssl, ...restOptions } = newOptions;\n if (ssl && Object.keys(ssl).length) {\n server = (0, $7BbP7$nodehttps).createServer(ssl, app);\n newOptions = restOptions;\n } else server = (0, $7BbP7$nodehttp).createServer(app);\n // Increase max listeners to prevent warning when multiple services attach listeners\n server.setMaxListeners(0);\n const peerjs = $0fe9c43b5c368182$export$8c57434a18c696c9(server, newOptions);\n app.use(peerjs);\n server.listen(port, host, ()=>callback?.(server));\n return peerjs;\n}\n\n\nconst $3809f3d53201df9f$var$optimistUsageLength = 98;\nconst $3809f3d53201df9f$var$y = (0, $7BbP7$yargs)((0, $7BbP7$hideBin)(process.argv));\nconst $3809f3d53201df9f$var$portEnvIsSet = !!process.env[\"PORT\"];\nconst $3809f3d53201df9f$var$opts = $3809f3d53201df9f$var$y.usage(\"Usage: $0\").wrap(Math.min($3809f3d53201df9f$var$optimistUsageLength, $3809f3d53201df9f$var$y.terminalWidth())).options({\n expire_timeout: {\n demandOption: false,\n alias: \"t\",\n describe: \"timeout (milliseconds)\",\n default: 5000\n },\n concurrent_limit: {\n demandOption: false,\n alias: \"c\",\n describe: \"concurrent limit\",\n default: 5000\n },\n alive_timeout: {\n demandOption: false,\n describe: \"broken connection check timeout (milliseconds)\",\n default: 60000\n },\n key: {\n demandOption: false,\n alias: \"k\",\n describe: \"connection key\",\n default: \"peerjs\"\n },\n sslkey: {\n type: \"string\",\n demandOption: false,\n describe: \"path to SSL key\"\n },\n sslcert: {\n type: \"string\",\n demandOption: false,\n describe: \"path to SSL certificate\"\n },\n host: {\n type: \"string\",\n demandOption: false,\n alias: \"H\",\n describe: \"host\"\n },\n port: {\n type: \"number\",\n demandOption: !$3809f3d53201df9f$var$portEnvIsSet,\n alias: \"p\",\n describe: \"port\"\n },\n path: {\n type: \"string\",\n demandOption: false,\n describe: \"custom path\",\n default: process.env[\"PEERSERVER_PATH\"] ?? \"/\"\n },\n allow_discovery: {\n type: \"boolean\",\n demandOption: false,\n describe: \"allow discovery of peers\"\n },\n proxied: {\n type: \"boolean\",\n demandOption: false,\n describe: \"Set true if PeerServer stays behind a reverse proxy\",\n default: false\n },\n cors: {\n type: \"string\",\n array: true,\n describe: \"Set the list of CORS origins\"\n }\n}).boolean(\"allow_discovery\").parseSync();\nif (!$3809f3d53201df9f$var$opts.port) // .port is only not set if the PORT env var is set\n// eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n$3809f3d53201df9f$var$opts.port = parseInt(process.env[\"PORT\"]);\nif ($3809f3d53201df9f$var$opts.cors) {\n // Handle '*' for all origins, otherwise use the array of origins\n const origin = $3809f3d53201df9f$var$opts.cors.length === 1 && $3809f3d53201df9f$var$opts.cors[0] === '*' ? '*' : $3809f3d53201df9f$var$opts.cors;\n $3809f3d53201df9f$var$opts[\"corsOptions\"] = {\n origin: origin\n };\n}\nprocess.on(\"uncaughtException\", function(e) {\n console.error(\"Error: \" + e.toString());\n});\nif ($3809f3d53201df9f$var$opts.sslkey ?? $3809f3d53201df9f$var$opts.sslcert) {\n if ($3809f3d53201df9f$var$opts.sslkey && $3809f3d53201df9f$var$opts.sslcert) $3809f3d53201df9f$var$opts[\"ssl\"] = {\n key: (0, $7BbP7$nodefs).readFileSync((0, $7BbP7$nodepath).resolve($3809f3d53201df9f$var$opts.sslkey)),\n cert: (0, $7BbP7$nodefs).readFileSync((0, $7BbP7$nodepath).resolve($3809f3d53201df9f$var$opts.sslcert))\n };\n else {\n console.error(\"Warning: PeerServer will not run because either the key or the certificate has not been provided.\");\n process.exit(1);\n }\n}\nconst $3809f3d53201df9f$var$userPath = $3809f3d53201df9f$var$opts.path;\nconst $3809f3d53201df9f$var$server = (0, $0fe9c43b5c368182$export$f99d31af51f48b1e)($3809f3d53201df9f$var$opts, (server)=>{\n const { address: host, port: port } = server.address();\n console.log(\"Started PeerServer on %s, port: %s, path: %s\", host, port, $3809f3d53201df9f$var$userPath || \"/\");\n const shutdownApp = ()=>{\n server.close(()=>{\n console.log(\"Http server closed.\");\n process.exit(0);\n });\n };\n process.on(\"SIGINT\", shutdownApp);\n process.on(\"SIGTERM\", shutdownApp);\n});\n$3809f3d53201df9f$var$server.on(\"connection\", (client)=>{\n console.log(`Client connected: ${client.getId()}`);\n});\n$3809f3d53201df9f$var$server.on(\"disconnect\", (client)=>{\n console.log(`Client disconnected: ${client.getId()}`);\n});\n\n\n//# sourceMappingURL=peerjs.js.map\n","#!/usr/bin/env node\n\nimport path from \"node:path\";\nimport fs from \"node:fs\";\nconst optimistUsageLength = 98;\nimport yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport { PeerServer } from \"../src/index.ts\";\nimport type { AddressInfo } from \"node:net\";\nimport type { CorsOptions } from \"cors\";\n\nconst y = yargs(hideBin(process.argv));\n\nconst portEnvIsSet = !!process.env[\"PORT\"];\n\nconst opts = y\n\t.usage(\"Usage: $0\")\n\t.wrap(Math.min(optimistUsageLength, y.terminalWidth()))\n\t.options({\n\t\texpire_timeout: {\n\t\t\tdemandOption: false,\n\t\t\talias: \"t\",\n\t\t\tdescribe: \"timeout (milliseconds)\",\n\t\t\tdefault: 5000,\n\t\t},\n\t\tconcurrent_limit: {\n\t\t\tdemandOption: false,\n\t\t\talias: \"c\",\n\t\t\tdescribe: \"concurrent limit\",\n\t\t\tdefault: 5000,\n\t\t},\n\t\talive_timeout: {\n\t\t\tdemandOption: false,\n\t\t\tdescribe: \"broken connection check timeout (milliseconds)\",\n\t\t\tdefault: 60000,\n\t\t},\n\t\tkey: {\n\t\t\tdemandOption: false,\n\t\t\talias: \"k\",\n\t\t\tdescribe: \"connection key\",\n\t\t\tdefault: \"peerjs\",\n\t\t},\n\t\tsslkey: {\n\t\t\ttype: \"string\",\n\t\t\tdemandOption: false,\n\t\t\tdescribe: \"path to SSL key\",\n\t\t},\n\t\tsslcert: {\n\t\t\ttype: \"string\",\n\t\t\tdemandOption: false,\n\t\t\tdescribe: \"path to SSL certificate\",\n\t\t},\n\t\thost: {\n\t\t\ttype: \"string\",\n\t\t\tdemandOption: false,\n\t\t\talias: \"H\",\n\t\t\tdescribe: \"host\",\n\t\t},\n\t\tport: {\n\t\t\ttype: \"number\",\n\t\t\tdemandOption: !portEnvIsSet,\n\t\t\talias: \"p\",\n\t\t\tdescribe: \"port\",\n\t\t},\n\t\tpath: {\n\t\t\ttype: \"string\",\n\t\t\tdemandOption: false,\n\t\t\tdescribe: \"custom path\",\n\t\t\tdefault: process.env[\"PEERSERVER_PATH\"] ?? \"/\",\n\t\t},\n\t\tallow_discovery: {\n\t\t\ttype: \"boolean\",\n\t\t\tdemandOption: false,\n\t\t\tdescribe: \"allow discovery of peers\",\n\t\t},\n\t\tproxied: {\n\t\t\ttype: \"boolean\",\n\t\t\tdemandOption: false,\n\t\t\tdescribe: \"Set true if PeerServer stays behind a reverse proxy\",\n\t\t\tdefault: false,\n\t\t},\n\t\tcors: {\n\t\t\ttype: \"string\",\n\t\t\tarray: true,\n\t\t\tdescribe: \"Set the list of CORS origins\",\n\t\t},\n\t})\n\t.boolean(\"allow_discovery\")\n\t.parseSync();\n\nif (!opts.port) {\n\t// .port is only not set if the PORT env var is set\n\t// eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n\topts.port = parseInt(process.env[\"PORT\"]!);\n}\nif (opts.cors) {\n\t// Handle '*' for all origins, otherwise use the array of origins\n\tconst origin = opts.cors.length === 1 && opts.cors[0] === '*' \n\t\t? '*' \n\t\t: opts.cors;\n\t\n\topts[\"corsOptions\"] = {\n\t\torigin: origin,\n\t} satisfies CorsOptions;\n}\nprocess.on(\"uncaughtException\", function (e) {\n\tconsole.error(\"Error: \" + e.toString());\n});\n\nif (opts.sslkey ?? opts.sslcert) {\n\tif (opts.sslkey && opts.sslcert) {\n\t\topts[\"ssl\"] = {\n\t\t\tkey: fs.readFileSync(path.resolve(opts.sslkey)),\n\t\t\tcert: fs.readFileSync(path.resolve(opts.sslcert)),\n\t\t};\n\t} else {\n\t\tconsole.error(\n\t\t\t\"Warning: PeerServer will not run because either \" +\n\t\t\t\t\"the key or the certificate has not been provided.\",\n\t\t);\n\t\tprocess.exit(1);\n\t}\n}\n\nconst userPath = opts.path;\nconst server = PeerServer(opts, (server) => {\n\tconst { address: host, port } = server.address() as AddressInfo;\n\n\tconsole.log(\n\t\t\"Started PeerServer on %s, port: %s, path: %s\",\n\t\thost,\n\t\tport,\n\t\tuserPath || \"/\",\n\t);\n\n\tconst shutdownApp = () => {\n\t\tserver.close(() => {\n\t\t\tconsole.log(\"Http server closed.\");\n\n\t\t\tprocess.exit(0);\n\t\t});\n\t};\n\n\tprocess.on(\"SIGINT\", shutdownApp);\n\tprocess.on(\"SIGTERM\", shutdownApp);\n});\n\nserver.on(\"connection\", (client) => {\n\tconsole.log(`Client connected: ${client.getId()}`);\n});\n\nserver.on(\"disconnect\", (client) => {\n\tconsole.log(`Client disconnected: ${client.getId()}`);\n});\n","import express, { type Express } from \"express\";\nimport http from \"node:http\";\nimport https from \"node:https\";\n\nimport type { IConfig } from \"./config/index.ts\";\nimport defaultConfig from \"./config/index.ts\";\nimport type { PeerServerEvents } from \"./instance.ts\";\nimport { createInstance } from \"./instance.ts\";\nimport type { IClient } from \"./models/client.ts\";\nimport type { IMessage } from \"./models/message.ts\";\n\nexport type { MessageType } from \"./enums.ts\";\nexport type { IConfig, PeerServerEvents, IClient, IMessage };\n\nfunction ExpressPeerServer(\n\tserver: https.Server | http.Server,\n\toptions?: Partial<IConfig>,\n) {\n\tconst app = express();\n\n\tconst newOptions: IConfig = {\n\t\t...defaultConfig,\n\t\t...options,\n\t};\n\n\tif (newOptions.proxied) {\n\t\tapp.set(\n\t\t\t\"trust proxy\",\n\t\t\tnewOptions.proxied === \"false\" ? false : !!newOptions.proxied,\n\t\t);\n\t}\n\n\tapp.on(\"mount\", () => {\n\t\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n\t\tif (!server) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Server is not passed to constructor - \" + \"can't start PeerServer\",\n\t\t\t);\n\t\t}\n\n\t\tcreateInstance({ app, server, options: newOptions });\n\t});\n\n\treturn app as Express & PeerServerEvents;\n}\n\nfunction PeerServer(\n\toptions: Partial<IConfig> = {},\n\tcallback?: (server: https.Server | http.Server) => void,\n) {\n\tconst app = express();\n\n\tlet newOptions: IConfig = {\n\t\t...defaultConfig,\n\t\t...options,\n\t};\n\n\tconst port = newOptions.port;\n\tconst host = newOptions.host;\n\n\tlet server: https.Server | http.Server;\n\n\tconst { ssl, ...restOptions } = newOptions;\n\tif (ssl && Object.keys(ssl).length) {\n\t\tserver = https.createServer(ssl, app);\n\n\t\tnewOptions = restOptions;\n\t} else {\n\t\tserver = http.createServer(app);\n\t}\n\n\t// Increase max listeners to prevent warning when multiple services attach listeners\n\tserver.setMaxListeners(0);\n\n\tconst peerjs = ExpressPeerServer(server, newOptions);\n\tapp.use(peerjs);\n\n\tserver.listen(port, host, () => callback?.(server));\n\n\treturn peerjs;\n}\n\nexport { ExpressPeerServer, PeerServer };\n","import type { WebSocketServer, ServerOptions } from \"ws\";\nimport type { CorsOptions } from \"cors\";\n\nexport interface IConfig {\n\treadonly host: string;\n\treadonly port: number;\n\treadonly expire_timeout: number;\n\treadonly alive_timeout: number;\n\treadonly key: string;\n\treadonly path: string;\n\treadonly concurrent_limit: number;\n\treadonly allow_discovery: boolean;\n\treadonly proxied: boolean | string;\n\treadonly cleanup_out_msgs: number;\n\treadonly ssl?: {\n\t\tkey: string;\n\t\tcert: string;\n\t};\n\treadonly generateClientId?: () => string;\n\treadonly createWebSocketServer?: (options: ServerOptions) => WebSocketServer;\n\treadonly corsOptions: CorsOptions;\n}\n\nconst defaultConfig: IConfig = {\n\thost: \"::\",\n\tport: 9000,\n\texpire_timeout: 5000,\n\talive_timeout: 90000,\n\tkey: \"peerjs\",\n\tpath: \"/\",\n\tconcurrent_limit: 5000,\n\tallow_discovery: false,\n\tproxied: false,\n\tcleanup_out_msgs: 1000,\n\tcorsOptions: { origin: true },\n};\n\nexport default defaultConfig;\n","import type express from \"express\";\nimport type { Server as HttpServer } from \"node:http\";\nimport type { Server as HttpsServer } from \"node:https\";\nimport path from \"node:path\";\nimport type { IRealm } from \"./models/realm.ts\";\nimport { Realm } from \"./models/realm.ts\";\nimport { CheckBrokenConnections } from \"./services/checkBrokenConnections/index.ts\";\nimport type { IMessagesExpire } from \"./services/messagesExpire/index.ts\";\nimport { MessagesExpire } from \"./services/messagesExpire/index.ts\";\nimport type { IWebSocketServer } from \"./services/webSocketServer/index.ts\";\nimport { WebSocketServer } from \"./services/webSocketServer/index.ts\";\nimport { MessageHandler } from \"./messageHandler/index.ts\";\nimport { Api } from \"./api/index.ts\";\nimport type { IClient } from \"./models/client.ts\";\nimport type { IMessage } from \"./models/message.ts\";\nimport type { IConfig } from \"./config/index.ts\";\n\nexport interface PeerServerEvents {\n\ton(event: \"connection\", listener: (client: IClient) => void): this;\n\ton(\n\t\tevent: \"message\",\n\t\tlistener: (client: IClient, message: IMessage) => void,\n\t): this;\n\t// eslint-disable-next-line @typescript-eslint/unified-signatures\n\ton(event: \"disconnect\", listener: (client: IClient) => void): this;\n\ton(event: \"error\", listener: (client: Error) => void): this;\n}\n\nexport const createInstance = ({\n\tapp,\n\tserver,\n\toptions,\n}: {\n\tapp: express.Application;\n\tserver: HttpServer | HttpsServer;\n\toptions: IConfig;\n}): void => {\n\tconst config = options;\n\tconst realm: IRealm = new Realm();\n\tconst messageHandler = new MessageHandler(realm);\n\n\tconst api = Api({ config, realm, corsOptions: options.corsOptions });\n\tconst messagesExpire: IMessagesExpire = new MessagesExpire({\n\t\trealm,\n\t\tconfig,\n\t\tmessageHandler,\n\t});\n\tconst checkBrokenConnections = new CheckBrokenConnections({\n\t\trealm,\n\t\tconfig,\n\t\tonClose: (client) => {\n\t\t\tapp.emit(\"disconnect\", client);\n\t\t},\n\t});\n\n\tapp.use(options.path, api);\n\n\t//use mountpath for WS server\n\tconst customConfig = {\n\t\t...config,\n\t\tpath: path.posix.join(app.path(), options.path, \"/\"),\n\t};\n\n\tconst wss: IWebSocketServer = new WebSocketServer({\n\t\tserver,\n\t\trealm,\n\t\tconfig: customConfig,\n\t});\n\n\twss.on(\"connection\", (client: IClient) => {\n\t\tconst messageQueue = realm.getMessageQueueById(client.getId());\n\n\t\tif (messageQueue) {\n\t\t\tlet message: IMessage | undefined;\n\n\t\t\twhile ((message = messageQueue.readMessage())) {\n\t\t\t\tmessageHandler.handle(client, message);\n\t\t\t}\n\t\t\trealm.clearMessageQueue(client.getId());\n\t\t}\n\n\t\tapp.emit(\"connection\", client);\n\t});\n\n\twss.on(\"message\", (client: IClient, message: IMessage) => {\n\t\tapp.emit(\"message\", client, message);\n\t\tmessageHandler.handle(client, message);\n\t});\n\n\twss.on(\"close\", (client: IClient) => {\n\t\tapp.emit(\"disconnect\", client);\n\t});\n\n\twss.on(\"error\", (error: Error) => {\n\t\tapp.emit(\"error\", error);\n\t});\n\n\tmessagesExpire.startMessagesExpiration();\n\tcheckBrokenConnections.start();\n};\n","import type { IMessageQueue } from \"./messageQueue.ts\";\nimport { MessageQueue } from \"./messageQueue.ts\";\nimport { randomUUID } from \"node:crypto\";\nimport type { IClient } from \"./client.ts\";\nimport type { IMessage } from \"./message.ts\";\n\nexport interface IRealm {\n\tgetClientsIds(): string[];\n\n\tgetClientById(clientId: string): IClient | undefined;\n\n\tgetClientsIdsWithQueue(): string[];\n\n\tsetClient(client: IClient, id: string): void;\n\n\tremoveClientById(id: string): boolean;\n\n\tgetMessageQueueById(id: string): IMessageQueue | undefined;\n\n\taddMessageToQueue(id: string, message: IMessage): void;\n\n\tclearMessageQueue(id: string): void;\n\n\tgenerateClientId(generateClientId?: () => string): string;\n\n\tgetClientsByIp(ipAddress: string): Map<string, IClient> | undefined;\n\n\tgetAllIpGroups(): Map<string, Map<string, IClient>>;\n}\n\nexport class Realm implements IRealm {\n\tprivate readonly clients = new Map<string, IClient>();\n\tprivate readonly messageQueues = new Map<string, IMessageQueue>();\n\tprivate readonly clientsByIp = new Map<string, Map<string, IClient>>();\n\n\tpublic getClientsIds(): string[] {\n\t\treturn [...this.clients.keys()];\n\t}\n\n\tpublic getClientById(clientId: string): IClient | undefined {\n\t\treturn this.clients.get(clientId);\n\t}\n\n\tpublic getClientsIdsWithQueue(): string[] {\n\t\treturn [...this.messageQueues.keys()];\n\t}\n\n\tpublic setClient(client: IClient, id: string): void {\n\t\tthis.clients.set(id, client);\n\n\t\t// Add to IP-based grouping\n\t\tconst ip = client.getIpAddress();\n\t\tif (ip) {\n\t\t\tlet ipGroup = this.clientsByIp.get(ip);\n\t\t\tif (!ipGroup) {\n\t\t\t\tipGroup = new Map();\n\t\t\t\tthis.clientsByIp.set(ip, ipGroup);\n\t\t\t}\n\t\t\tipGroup.set(id, client);\n\t\t}\n\t}\n\n\tpublic removeClientById(id: string): boolean {\n\t\tconst client = this.getClientById(id);\n\n\t\tif (!client) return false;\n\n\t\t// Remove from IP-based grouping\n\t\tconst ip = client.getIpAddress();\n\t\tif (ip) {\n\t\t\tconst ipGroup = this.clientsByIp.get(ip);\n\t\t\tif (ipGroup) {\n\t\t\t\tipGroup.delete(id);\n\t\t\t\tif (ipGroup.size === 0) {\n\t\t\t\t\tthis.clientsByIp.delete(ip);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.clients.delete(id);\n\n\t\treturn true;\n\t}\n\n\tpublic getMessageQueueById(id: string): IMessageQueue | undefined {\n\t\treturn this.messageQueues.get(id);\n\t}\n\n\tpublic addMessageToQueue(id: string, message: IMessage): void {\n\t\tif (!this.getMessageQueueById(id)) {\n\t\t\tthis.messageQueues.set(id, new MessageQueue());\n\t\t}\n\n\t\tthis.getMessageQueueById(id)?.addMessage(message);\n\t}\n\n\tpublic clearMessageQueue(id: string): void {\n\t\tthis.messageQueues.delete(id);\n\t}\n\n\tpublic generateClientId(generateClientId?: () => string): string {\n\t\tconst generateId = generateClientId ? generateClientId : randomUUID;\n\n\t\tlet clientId = generateId();\n\n\t\twhile (this.getClientById(clientId)) {\n\t\t\tclientId = generateId();\n\t\t}\n\n\t\treturn clientId;\n\t}\n\n\tpublic getClientsByIp(ipAddress: string): Map<string, IClient> | undefined {\n\t\treturn this.clientsByIp.get(ipAddress);\n\t}\n\n\tpublic getAllIpGroups(): Map<string, Map<string, IClient>> {\n\t\treturn this.clientsByIp;\n\t}\n}\n","import type { IMessage } from \"./message.ts\";\n\nexport interface IMessageQueue {\n\tgetLastReadAt(): number;\n\n\taddMessage(message: IMessage): void;\n\n\treadMessage(): IMessage | undefined;\n\n\tgetMessages(): IMessage[];\n}\n\nexport class MessageQueue implements IMessageQueue {\n\tprivate lastReadAt: number = new Date().getTime();\n\tprivate readonly messages: IMessage[] = [];\n\n\tpublic getLastReadAt(): number {\n\t\treturn this.lastReadAt;\n\t}\n\n\tpublic addMessage(message: IMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\tpublic readMessage(): IMessage | undefined {\n\t\tif (this.messages.length > 0) {\n\t\t\tthis.lastReadAt = new Date().getTime();\n\t\t\treturn this.messages.shift();\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tpublic getMessages(): IMessage[] {\n\t\treturn this.messages;\n\t}\n}\n","import type { IConfig } from \"../../config/index.ts\";\nimport type { IClient } from \"../../models/client.ts\";\nimport type { IRealm } from \"../../models/realm.ts\";\n\nconst DEFAULT_CHECK_INTERVAL = 300;\n\ntype CustomConfig = Pick<IConfig, \"alive_timeout\">;\n\nexport class CheckBrokenConnections {\n\tpublic readonly checkInterval: number;\n\tprivate timeoutId: NodeJS.Timeout | null = null;\n\tprivate readonly realm: IRealm;\n\tprivate readonly config: CustomConfig;\n\tprivate readonly onClose?: (client: IClient) => void;\n\n\tconstructor({\n\t\trealm,\n\t\tconfig,\n\t\tcheckInterval = DEFAULT_CHECK_INTERVAL,\n\t\tonClose,\n\t}: {\n\t\trealm: IRealm;\n\t\tconfig: CustomConfig;\n\t\tcheckInterval?: number;\n\t\tonClose?: (client: IClient) => void;\n\t}) {\n\t\tthis.realm = realm;\n\t\tthis.config = config;\n\t\tthis.onClose = onClose;\n\t\tthis.checkInterval = checkInterval;\n\t}\n\n\tpublic start(): void {\n\t\tif (this.timeoutId) {\n\t\t\tclearTimeout(this.timeoutId);\n\t\t}\n\n\t\tthis.timeoutId = setTimeout(() => {\n\t\t\tthis.checkConnections();\n\n\t\t\tthis.timeoutId = null;\n\n\t\t\tthis.start();\n\t\t}, this.checkInterval);\n\t}\n\n\tpublic stop(): void {\n\t\tif (this.timeoutId) {\n\t\t\tclearTimeout(this.timeoutId);\n\t\t\tthis.timeoutId = null;\n\t\t}\n\t}\n\n\tprivate checkConnections(): void {\n\t\tconst clientsIds = this.realm.getClientsIds();\n\n\t\tconst now = new Date().getTime();\n\t\tconst { alive_timeout: aliveTimeout } = this.config;\n\n\t\tfor (const clientId of clientsIds) {\n\t\t\tconst client = this.realm.getClientById(clientId);\n\n\t\t\tif (!client) continue;\n\n\t\t\tconst timeSinceLastPing = now - client.getLastPing();\n\n\t\t\tif (timeSinceLastPing < aliveTimeout) continue;\n\n\t\t\ttry {\n\t\t\t\tclient.getSocket()?.close();\n\t\t\t} finally {\n\t\t\t\tthis.realm.clearMessageQueue(clientId);\n\t\t\t\tthis.realm.removeClientById(clientId);\n\n\t\t\t\tclient.setSocket(null);\n\n\t\t\t\tthis.onClose?.(client);\n\t\t\t}\n\t\t}\n\t}\n}\n","import { MessageType } from \"../../enums.ts\";\nimport type { IConfig } from \"../../config/index.ts\";\nimport type { IMessageHandler } from \"../../messageHandler/index.ts\";\nimport type { IRealm } from \"../../models/realm.ts\";\n\nexport interface IMessagesExpire {\n\tstartMessagesExpiration(): void;\n\tstopMessagesExpiration(): void;\n}\n\ntype CustomConfig = Pick<IConfig, \"cleanup_out_msgs\" | \"expire_timeout\">;\n\nexport class MessagesExpire implements IMessagesExpire {\n\tprivate readonly realm: IRealm;\n\tprivate readonly config: CustomConfig;\n\tprivate readonly messageHandler: IMessageHandler;\n\n\tprivate timeoutId: NodeJS.Timeout | null = null;\n\n\tconstructor({\n\t\trealm,\n\t\tconfig,\n\t\tmessageHandler,\n\t}: {\n\t\trealm: IRealm;\n\t\tconfig: CustomConfig;\n\t\tmessageHandler: IMessageHandler;\n\t}) {\n\t\tthis.realm = realm;\n\t\tthis.config = config;\n\t\tthis.messageHandler = messageHandler;\n\t}\n\n\tpublic startMessagesExpiration(): void {\n\t\tif (this.timeoutId) {\n\t\t\tclearTimeout(this.timeoutId);\n\t\t}\n\n\t\t// Clean up outstanding messages\n\t\tthis.timeoutId = setTimeout(() => {\n\t\t\tthis.pruneOutstanding();\n\n\t\t\tthis.timeoutId = null;\n\n\t\t\tthis.startMessagesExpiration();\n\t\t}, this.config.cleanup_out_msgs);\n\t}\n\n\tpublic stopMessagesExpiration(): void {\n\t\tif (this.timeoutId) {\n\t\t\tclearTimeout(this.timeoutId);\n\t\t\tthis.timeoutId = null;\n\t\t}\n\t}\n\n\tprivate pruneOutstanding(): void {\n\t\tconst destinationClientsIds = this.realm.getClientsIdsWithQueue();\n\n\t\tconst now = new Date().getTime();\n\t\tconst maxDiff = this.config.expire_timeout;\n\n\t\tconst seen: Record<string, boolean> = {};\n\n\t\tfor (const destinationClientId of destinationClientsIds) {\n\t\t\tconst messageQueue = this.realm.getMessageQueueById(destinationClientId);\n\n\t\t\tif (!messageQueue) continue;\n\n\t\t\tconst lastReadDiff = now - messageQueue.getLastReadAt();\n\n\t\t\tif (lastReadDiff < maxDiff) continue;\n\n\t\t\tconst messages = messageQueue.getMessages();\n\n\t\t\tfor (const message of messages) {\n\t\t\t\tconst seenKey = `${message.src}_${message.dst}`;\n\n\t\t\t\tif (!seen[seenKey]) {\n\t\t\t\t\tthis.messageHandler.handle(undefined, {\n\t\t\t\t\t\ttype: MessageType.EXPIRE,\n\t\t\t\t\t\tsrc: message.dst,\n\t\t\t\t\t\tdst: message.src,\n\t\t\t\t\t});\n\n\t\t\t\t\tseen[seenKey] = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.realm.clearMessageQueue(destinationClientId);\n\t\t}\n\t}\n}\n","export enum Errors {\n\tINVALID_KEY = \"Invalid key provided\",\n\tINVALID_TOKEN = \"Invalid token provided\",\n\tINVALID_WS_PARAMETERS = \"No id, token, or key supplied to websocket server\",\n\tCONNECTION_LIMIT_EXCEED = \"Server has reached its concurrent user limit\",\n}\n\nexport enum MessageType {\n\tOPEN = \"OPEN\",\n\tLEAVE = \"LEAVE\",\n\tCANDIDATE = \"CANDIDATE\",\n\tOFFER = \"OFFER\",\n\tANSWER = \"ANSWER\",\n\tEXPIRE = \"EXPIRE\",\n\tHEARTBEAT = \"HEARTBEAT\",\n\tID_TAKEN = \"ID-TAKEN\",\n\tERROR = \"ERROR\",\n\tPEER_JOINED_IP_GROUP = \"PEER-JOINED-IP-GROUP\",\n\tPEER_LEFT_IP_GROUP = \"PEER-LEFT-IP-GROUP\",\n}\n","import { EventEmitter } from \"node:events\";\nimport type { IncomingMessage } from \"node:http\";\nimport type WebSocket from \"ws\";\nimport { Errors, MessageType } from \"../../enums.ts\";\nimport type { IClient } from \"../../models/client.ts\";\nimport { Client } from \"../../models/client.ts\";\nimport type { IConfig } from \"../../config/index.ts\";\nimport type { IRealm } from \"../../models/realm.ts\";\nimport { WebSocketServer as Server } from \"ws\";\nimport type { Server as HttpServer } from \"node:http\";\nimport type { Server as HttpsServer } from \"node:https\";\nimport { IMessage } from \"../../models/message.js\";\nimport { generateAlias } from \"../../utils/aliasGenerator.ts\";\n\nexport interface IWebSocketServer extends EventEmitter {\n\treadonly path: string;\n}\n\ntype CustomConfig = Pick<\n\tIConfig,\n\t\"path\" | \"key\" | \"concurrent_limit\" | \"createWebSocketServer\"\n>;\n\nconst WS_PATH = \"peerjs\";\n\nexport class WebSocketServer extends EventEmitter implements IWebSocketServer {\n\tpublic readonly path: string;\n\tprivate readonly realm: IRealm;\n\tprivate readonly config: CustomConfig;\n\tpublic readonly socketServer: Server;\n\n\tconstructor({\n\t\tserver,\n\t\trealm,\n\t\tconfig,\n\t}: {\n\t\tserver: HttpServer | HttpsServer;\n\t\trealm: IRealm;\n\t\tconfig: CustomConfig;\n\t}) {\n\t\tsuper();\n\n\t\tthis.setMaxListeners(0);\n\n\t\tthis.realm = realm;\n\t\tthis.config = config;\n\n\t\tconst path = this.config.path;\n\t\tthis.path = `${path}${path.endsWith(\"/\") ? \"\" : \"/\"}${WS_PATH}`;\n\n\t\tconst options: WebSocket.ServerOptions = {\n\t\t\tpath: this.path,\n\t\t\tserver,\n\t\t};\n\n\t\tthis.socketServer = config.createWebSocketServer\n\t\t\t? config.createWebSocketServer(options)\n\t\t\t: new Server(options);\n\n\t\tthis.socketServer.on(\"connection\", (socket, req) => {\n\t\t\tthis._onSocketConnection(socket, req);\n\t\t});\n\t\tthis.socketServer.on(\"error\", (error: Error) => {\n\t\t\tthis._onSocketError(error);\n\t\t});\n\t}\n\n\tprivate _onSocketConnection(socket: WebSocket, req: IncomingMessage): void {\n\t\t// An unhandled socket error might crash the server. Handle it first.\n\t\tsocket.on(\"error\", (error) => {\n\t\t\tthis._onSocketError(error);\n\t\t});\n\n\t\t// Extract IP address (handle proxied requests)\n\t\tconst forwardedFor = req.headers[\"x-forwarded-for\"];\n\t\tlet ip = req.socket.remoteAddress ?? \"unknown\";\n\t\t\n\t\tif (forwardedFor) {\n\t\t\tconst forwardedIp = Array.isArray(forwardedFor) \n\t\t\t\t? forwardedFor[0] ?? \"\"\n\t\t\t\t: forwardedFor;\n\t\t\tconst firstIp = forwardedIp.split(\",\")[0];\n\t\t\tif (firstIp) {\n\t\t\t\tip = firstIp.trim();\n\t\t\t}\n\t\t}\n\n\t\t// We are only interested in the query, the base url is therefore not relevant\n\t\tconst { searchParams } = new URL(req.url ?? \"\", \"https://peerjs\");\n\t\tconst { id, token, key } = Object.fromEntries(searchParams.entries());\n\n\t\tif (!id || !token || !key) {\n\t\t\tthis._sendErrorAndClose(socket, Errors.INVALID_WS_PARAMETERS);\n\t\t\treturn;\n\t\t}\n\n\t\tif (key !== this.config.key) {\n\t\t\tthis._sendErrorAndClose(socket, Errors.INVALID_KEY);\n\t\t\treturn;\n\t\t}\n\n\t\tconst client = this.realm.getClientById(id);\n\n\t\tif (client) {\n\t\t\tif (token !== client.getToken()) {\n\t\t\t\t// ID-taken, invalid token\n\t\t\t\tsocket.send(\n\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\ttype: MessageType.ID_TAKEN,\n\t\t\t\t\t\tpayload: { msg: \"ID is taken\" },\n\t\t\t\t\t}),\n\t\t\t\t);\n\n\t\t\t\tsocket.close();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis._configureWS(socket, client);\n\t\t\treturn;\n\t\t}\n\n\t\tthis._registerClient({ socket, id, token, ip });\n\t}\n\n\tprivate _onSocketError(error: Error): void {\n\t\t// handle error\n\t\tthis.emit(\"error\", error);\n\t}\n\n\tprivate _registerClient({\n\t\tsocket,\n\t\tid,\n\t\ttoken,\n\t\tip,\n\t}: {\n\t\tsocket: WebSocket;\n\t\tid: string;\n\t\ttoken: string;\n\t\tip: string;\n\t}): void {\n\t\t// Check concurrent limit\n\t\tconst clientsCount = this.realm.getClientsIds().length;\n\n\t\tif (clientsCount >= this.config.concurrent_limit) {\n\t\t\tthis._sendErrorAndClose(socket, Errors.CONNECTION_LIMIT_EXCEED);\n\t\t\treturn;\n\t\t}\n\n\t\tconst newClient: IClient = new Client({ id, token });\n\t\tnewClient.setIpAddress(ip);\n\t\tnewClient.setAlias(generateAlias());\n\t\tthis.realm.setClient(newClient, id);\n\t\tsocket.send(JSON.stringify({ type: MessageType.OPEN }));\n\n\t\tthis._configureWS(socket, newClient);\n\n\t\t// Notify other clients in the same IP group about the new peer\n\t\tthis._notifyIpGroup(ip, newClient.getId(), {\n\t\t\ttype: MessageType.PEER_JOINED_IP_GROUP,\n\t\t\tpayload: {\n\t\t\t\tid: newClient.getId(),\n\t\t\t\talias: newClient.getAlias(),\n\t\t\t\tip: ip,\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate _configureWS(socket: WebSocket, client: IClient): void {\n\t\tclient.setSocket(socket);\n\n\t\t// Cleanup after a socket closes.\n\t\tsocket.on(\"close\", () => {\n\t\t\tif (client.getSocket() === socket) {\n\t\t\t\tconst clientIp = client.getIpAddress();\n\t\t\t\tconst clientId = client.getId();\n\t\t\t\tconst clientAlias = client.getAlias();\n\n\t\t\t\tthis.realm.removeClientById(clientId);\n\n\t\t\t\t// Notify other clients in the same IP group about the peer leaving\n\t\t\t\tif (clientIp) {\n\t\t\t\t\tthis._notifyIpGroup(clientIp, clientId, {\n\t\t\t\t\t\ttype: MessageType.PEER_LEFT_IP_GROUP,\n\t\t\t\t\t\tpayload: {\n\t\t\t\t\t\t\tid: clientId,\n\t\t\t\t\t\t\talias: clientAlias,\n\t\t\t\t\t\t\tip: clientIp,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tthis.emit(\"close\", client);\n\t\t\t}\n\t\t});\n\n\t\t// Handle messages from peers.\n\t\tsocket.on(\"message\", (data) => {\n\t\t\ttry {\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-base-to-string\n\t\t\t\tconst message = JSON.parse(data.toString()) as Writable<IMessage>;\n\n\t\t\t\tmessage.src = client.getId();\n\n\t\t\t\tthis.emit(\"message\", client, message);\n\t\t\t} catch (e) {\n\t\t\t\tthis.emit(\"error\", e);\n\t\t\t}\n\t\t});\n\n\t\tthis.emit(\"connection\", client);\n\t}\n\n\tprivate _sendErrorAndClose(socket: WebSocket, msg: Errors): void {\n\t\tsocket.send(\n\t\t\tJSON.stringify({\n\t\t\t\ttype: MessageType.ERROR,\n\t\t\t\tpayload: { msg },\n\t\t\t}),\n\t\t);\n\n\t\tsocket.close();\n\t}\n\n\t/**\n\t * Notify all clients in the same IP group about a peer event\n\t * @param ip - The IP address of the group\n\t * @param excludeClientId - Client ID to exclude from notification (usually the one triggering the event)\n\t * @param message - The message to send\n\t */\n\tprivate _notifyIpGroup(\n\t\tip: string,\n\t\texcludeClientId: string,\n\t\tmessage: { type: MessageType; payload: unknown },\n\t): void {\n\t\tconst ipGroup = this.realm.getClientsByIp(ip);\n\t\tif (!ipGroup) return;\n\n\t\tfor (const [clientId, client] of ipGroup) {\n\t\t\t// Don't notify the client that triggered the event\n\t\t\tif (clientId === excludeClientId) continue;\n\n\t\t\tconst socket = client.getSocket();\n\t\t\tif (socket && socket.readyState === 1) {\n\t\t\t\t// WebSocket.OPEN = 1\n\t\t\t\ttry {\n\t\t\t\t\tsocket.send(JSON.stringify(message));\n\t\t\t\t} catch (e) {\n\t\t\t\t\t// Ignore send errors for now\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\ntype Writable<T> = {\n\t-readonly [K in keyof T]: T[K];\n};\n","import type WebSocket from \"ws\";\n\nexport interface IClient {\n\tgetId(): string;\n\n\tgetToken(): string;\n\n\tgetSocket(): WebSocket | null;\n\n\tsetSocket(socket: WebSocket | null): void;\n\n\tgetLastPing(): number;\n\n\tsetLastPing(lastPing: number): void;\n\n\tgetIpAddress(): string;\n\n\tsetIpAddress(ip: string): void;\n\n\tgetAlias(): string;\n\n\tsetAlias(alias: string): void;\n\n\tsend<T>(data: T): void;\n}\n\nexport class Client implements IClient {\n\tprivate readonly id: string;\n\tprivate readonly token: string;\n\tprivate socket: WebSocket | null = null;\n\tprivate lastPing: number = new Date().getTime();\n\tprivate ipAddress = \"\";\n\tprivate alias = \"\";\n\n\tconstructor({ id, token }: { id: string; token: string }) {\n\t\tthis.id = id;\n\t\tthis.token = token;\n\t}\n\n\tpublic getId(): string {\n\t\treturn this.id;\n\t}\n\n\tpublic getToken(): string {\n\t\treturn this.token;\n\t}\n\n\tpublic getSocket(): WebSocket | null {\n\t\treturn this.socket;\n\t}\n\n\tpublic setSocket(socket: WebSocket | null): void {\n\t\tthis.socket = socket;\n\t}\n\n\tpublic getLastPing(): number {\n\t\treturn this.lastPing;\n\t}\n\n\tpublic setLastPing(lastPing: number): void {\n\t\tthis.lastPing = lastPing;\n\t}\n\n\tpublic getIpAddress(): string {\n\t\treturn this.ipAddress;\n\t}\n\n\tpublic setIpAddress(ip: string): void {\n\t\tthis.ipAddress = ip;\n\t}\n\n\tpublic getAlias(): string {\n\t\treturn this.alias;\n\t}\n\n\tpublic setAlias(alias: string): void {\n\t\tthis.alias = alias;\n\t}\n\n\tpublic send<T>(data: T): void {\n\t\tthis.socket?.send(JSON.stringify(data));\n\t}\n}\n","const adjectives = [\n\t\"Bright\",\n\t\"Great\",\n\t\"Smart\",\n\t\"Swift\",\n\t\"Bold\",\n\t\"Calm\",\n\t\"Cool\",\n\t\"Warm\",\n\t\"Happy\",\n\t\"Lucky\",\n\t\"Noble\",\n\t\"Proud\",\n\t\"Quick\",\n\t\"Witty\",\n\t\"Brave\",\n\t\"Cheerful\",\n\t\"Daring\",\n\t\"Elegant\",\n\t\"Fancy\",\n\t\"Gentle\",\n\t\"Jolly\",\n\t\"Keen\",\n\t\"Lively\",\n\t\"Merry\",\n\t\"Polite\",\n\t\"Shiny\",\n\t\"Stellar\",\n\t\"Talented\",\n\t\"Vibrant\",\n\t\"Wise\",\n\t// Funny additions\n\t\"Silly\",\n\t\"Funky\",\n\t\"Zany\",\n\t\"Goofy\",\n\t\"Wobbly\",\n\t\"Glittery\",\n\t\"Bouncy\",\n\t\"Pickled\",\n\t\"Sneaky\",\n\t\"Nerdy\",\n\t\"Fluffy\",\n\t\"Spicy\",\n\t\"Crispy\",\n\t\"Snazzy\",\n\t\"Quirky\",\n\t\"Cheeky\",\n\t\"Giggly\",\n\t\"Breezy\",\n\t\"Slippery\",\n];\n\nconst nouns = [\n\t\"Banana\",\n\t\"Cherry\",\n\t\"Apple\",\n\t\"Orange\",\n\t\"Grape\",\n\t\"Mango\",\n\t\"Peach\",\n\t\"Lemon\",\n\t\"Melon\",\n\t\"Berry\",\n\t\"Pear\",\n\t\"Plum\",\n\t\"Kiwi\",\n\t\"Lime\",\n\t\"Papaya\",\n\t\"Apricot\",\n\t\"Fig\",\n\t\"Coconut\",\n\t\"Avocado\",\n\t\"Dragon\",\n\t\"Phoenix\",\n\t\"Tiger\",\n\t\"Eagle\",\n\t\"Lion\",\n\t\"Wolf\",\n\t\"Bear\",\n\t\"Hawk\",\n\t\"Falcon\",\n\t\"Panda\",\n\t// Funny additions\n\t\"Noodle\",\n\t\"Unicorn\",\n\t\"Tofu\",\n\t\"Pickle\",\n\t\"Marshmallow\",\n\t\"Wombat\",\n\t\"RubberDuck\",\n\t\"Taco\",\n\t\"Waffle\",\n\t\"Bubble\",\n\t\"Squid\",\n\t\"Hippo\",\n\t\"Muffin\",\n\t\"Nacho\",\n\t\"Ginger\",\n\t\"Squirrel\",\n\t\"Penguin\",\n\t\"Turtle\",\n\t\"Otter\",\n\t\"Dumpling\",\n];\n\n/**\n * Generates a random fun alias in the format \"Adjective Noun\"\n * Example: \"Bright Banana\", \"Smart Apple\", \"Great Cherry\"\n */\nexport function generateAlias(): string {\n\tconst adjective = adjectives[Math.floor(Math.random() * adjectives.length)];\n\tconst noun = nouns[Math.floor(Math.random() * nouns.length)];\n\treturn `${adjective} ${noun}`;\n}\n","import { MessageType } from \"../enums.ts\";\nimport { HeartbeatHandler, TransmissionHandler } from \"./handlers/index.ts\";\nimport type { IHandlersRegistry } from \"./handlersRegistry.ts\";\nimport { HandlersRegistry } from \"./handlersRegistry.ts\";\nimport type { IClient } from \"../models/client.ts\";\nimport type { IMessage } from \"../models/message.ts\";\nimport type { IRealm } from \"../models/realm.ts\";\nimport type { Handler } from \"./handler.ts\";\n\nexport interface IMessageHandler {\n\thandle(client: IClient | undefined, message: IMessage): boolean;\n}\n\nexport class MessageHandler implements IMessageHandler {\n\tconstructor(\n\t\trealm: IRealm,\n\t\tprivate readonly handlersRegistry: IHandlersRegistry = new HandlersRegistry(),\n\t) {\n\t\tconst transmissionHandler: Handler = TransmissionHandler({ realm });\n\t\tconst heartbeatHandler: Handler = HeartbeatHandler;\n\n\t\tconst handleTransmission: Handler = (\n\t\t\tclient: IClient | undefined,\n\t\t\t{ type, src, dst, payload }: IMessage,\n\t\t): boolean => {\n\t\t\treturn transmissionHandler(client, {\n\t\t\t\ttype,\n\t\t\t\tsrc,\n\t\t\t\tdst,\n\t\t\t\tpayload,\n\t\t\t});\n\t\t};\n\n\t\tconst handleHeartbeat = (client: IClient | undefined, message: IMessage) =>\n\t\t\theartbeatHandler(client, message);\n\n\t\tthis.handlersRegistry.registerHandler(\n\t\t\tMessageType.HEARTBEAT,\n\t\t\thandleHeartbeat,\n\t\t);\n\t\tthis.handlersRegistry.registerHandler(\n\t\t\tMessageType.OFFER,\n\t\t\thandleTransmission,\n\t\t);\n\t\tthis.handlersRegistry.registerHandler(\n\t\t\tMessageType.ANSWER,\n\t\t\thandleTransmission,\n\t\t);\n\t\tthis.handlersRegistry.registerHandler(\n\t\t\tMessageType.CANDIDATE,\n\t\t\thandleTransmission,\n\t\t);\n\t\tthis.handlersRegistry.registerHandler(\n\t\t\tMessageType.LEAVE,\n\t\t\thandleTransmission,\n\t\t);\n\t\tthis.handlersRegistry.registerHandler(\n\t\t\tMessageType.EXPIRE,\n\t\t\thandleTransmission,\n\t\t);\n\t}\n\n\tpublic handle(client: IClient | undefined, message: IMessage): boolean {\n\t\treturn this.handlersRegistry.handle(client, message);\n\t}\n}\n","export { HeartbeatHandler } from \"./heartbeat/index.ts\";\nexport { TransmissionHandler } from \"./transmission/index.ts\";\n","import type { IClient } from \"../../../models/client.ts\";\n\nexport const HeartbeatHandler = (client: IClient | undefined): boolean => {\n\tif (client) {\n\t\tconst nowTime = new Date().getTime();\n\t\tclient.setLastPing(nowTime);\n\t}\n\n\treturn true;\n};\n","import { MessageType } from \"../../../enums.ts\";\nimport type { IClient } from \"../../../models/client.ts\";\nimport type { IMessage } from \"../../../models/message.ts\";\nimport type { IRealm } from \"../../../models/realm.ts\";\n\nexport const TransmissionHandler = ({\n\trealm,\n}: {\n\trealm: IRealm;\n}): ((client: IClient | undefined, message: IMessage) => boolean) => {\n\tconst handle = (client: IClient | undefined, message: IMessage) => {\n\t\tconst type = message.type;\n\t\tconst srcId = message.src;\n\t\tconst dstId = message.dst;\n\n\t\tconst destinationClient = realm.getClientById(dstId);\n\n\t\t// User is connected!\n\t\tif (destinationClient) {\n\t\t\tconst socket = destinationClient.getSocket();\n\t\t\ttry {\n\t\t\t\tif (socket) {\n\t\t\t\t\tconst data = JSON.stringify(message);\n\n\t\t\t\t\tsocket.send(data);\n\t\t\t\t} else {\n\t\t\t\t\t// Neither socket no res available. Peer dead?\n\t\t\t\t\tthrow new Error(\"Peer dead\");\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\t// This happens when a peer disconnects without closing connections and\n\t\t\t\t// the associated WebSocket has not closed.\n\t\t\t\t// Tell other side to stop trying.\n\t\t\t\tif (socket) {\n\t\t\t\t\tsocket.close();\n\t\t\t\t} else {\n\t\t\t\t\trealm.removeClientById(destinationClient.getId());\n\t\t\t\t}\n\n\t\t\t\thandle(client, {\n\t\t\t\t\ttype: MessageType.LEAVE,\n\t\t\t\t\tsrc: dstId,\n\t\t\t\t\tdst: srcId,\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\t// Wait for this client to connect/reconnect (XHR) for important\n\t\t\t// messages.\n\t\t\tconst ignoredTypes = [MessageType.LEAVE, MessageType.EXPIRE];\n\n\t\t\tif (!ignoredTypes.includes(type) && dstId) {\n\t\t\t\trealm.addMessageToQueue(dstId, message);\n\t\t\t} else if (type === MessageType.LEAVE && !dstId) {\n\t\t\t\trealm.removeClientById(srcId);\n\t\t\t} else {\n\t\t\t\t// Unavailable destination specified with message LEAVE or EXPIRE\n\t\t\t\t// Ignore\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t};\n\n\treturn handle;\n};\n","import type { MessageType } from \"../enums.ts\";\nimport type { IClient } from \"../models/client.ts\";\nimport type { IMessage } from \"../models/message.ts\";\nimport type { Handler } from \"./handler.ts\";\n\nexport interface IHandlersRegistry {\n\tregisterHandler(messageType: MessageType, handler: Handler): void;\n\thandle(client: IClient | undefined, message: IMessage): boolean;\n}\n\nexport class HandlersRegistry implements IHandlersRegistry {\n\tprivate readonly handlers = new Map<MessageType, Handler>();\n\n\tpublic registerHandler(messageType: MessageType, handler: Handler): void {\n\t\tif (this.handlers.has(messageType)) return;\n\n\t\tthis.handlers.set(messageType, handler);\n\t}\n\n\tpublic handle(client: IClient | undefined, message: IMessage): boolean {\n\t\tconst { type } = message;\n\n\t\tconst handler = this.handlers.get(type);\n\n\t\tif (!handler) return false;\n\n\t\treturn handler(client, message);\n\t}\n}\n","import cors, { CorsOptions } from \"cors\";\nimport express from \"express\";\nimport publicContent from \"../../app.json\";\nimport PublicApi from \"./v1/public/index.ts\";\nimport type { IConfig } from \"../config/index.ts\";\nimport type { IRealm } from \"../models/realm.ts\";\n\nexport const Api = ({\n\tconfig,\n\trealm,\n\tcorsOptions,\n}: {\n\tconfig: IConfig;\n\trealm: IRealm;\n\tcorsOptions: CorsOptions;\n}): express.Router => {\n\tconst app = express.Router();\n\n\tapp.use(cors(corsOptions));\n\n\tapp.get(\"/\", (_, res) => {\n\t\tres.send(publicContent);\n\t});\n\n\tapp.use(\"/:key\", PublicApi({ config, realm }));\n\n\treturn app;\n};\n","{\n\t\"name\": \"PeerJS Server\",\n\t\"description\": \"A server side element to broker connections between PeerJS clients.\",\n\t\"website\": \"https://peerjs.com/\"\n}\n","import express from \"express\";\nimport type { IConfig } from \"../../../config/index.ts\";\nimport type { IRealm } from \"../../../models/realm.ts\";\n\nexport default ({\n\tconfig,\n\trealm,\n}: {\n\tconfig: IConfig;\n\trealm: IRealm;\n}): express.Router => {\n\tconst app = express.Router();\n\n\t// Retrieve guaranteed random ID.\n\tapp.get(\"/id\", (_, res: express.Response) => {\n\t\tres.contentType(\"html\");\n\t\tres.send(realm.generateClientId(config.generateClientId));\n\t});\n\n\t// Get a list of all peers for a key, enabled by the `allowDiscovery` flag.\n\tapp.get(\"/peers\", (_, res: express.Response) => {\n\t\tif (config.allow_discovery) {\n\t\t\tconst clientsIds = realm.getClientsIds();\n\n\t\t\treturn res.send(clientsIds);\n\t\t}\n\n\t\treturn res.sendStatus(401);\n\t});\n\n\t// Get all peers from the same IP as the requesting client\n\tapp.get(\"/by-ip\", (req: express.Request, res: express.Response) => {\n\t\tif (config.allow_discovery) {\n\t\t\t// Extract client's IP address from request\n\t\t\tconst forwardedFor = req.headers[\"x-forwarded-for\"];\n\t\t\tlet clientIp = req.socket.remoteAddress ?? \"unknown\";\n\t\t\t\n\t\t\tif (forwardedFor) {\n\t\t\t\tconst forwardedIp = Array.isArray(forwardedFor) \n\t\t\t\t\t? forwardedFor[0] ?? \"\"\n\t\t\t\t\t: forwardedFor;\n\t\t\t\tconst firstIp = forwardedIp.split(\",\")[0];\n\t\t\t\tif (firstIp) {\n\t\t\t\t\tclientIp = firstIp.trim();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst ipGroup = realm.getClientsByIp(clientIp);\n\n\t\t\tif (!ipGroup) {\n\t\t\t\treturn res.send([]);\n\t\t\t}\n\n\t\t\tconst peers = Array.from(ipGroup.values()).map((client) => ({\n\t\t\t\tid: client.getId(),\n\t\t\t\talias: client.getAlias(),\n\t\t\t}));\n\n\t\t\treturn res.send(peers);\n\t\t}\n\n\t\treturn res.sendStatus(401);\n\t});\n\n\t// Get all IP groups (admin/debugging endpoint)\n\tapp.get(\"/groups\", (_, res: express.Response) => {\n\t\tif (config.allow_discovery) {\n\t\t\tconst result: Record<string, { id: string; alias: string }[]> = {};\n\n\t\t\tconst ipGroups = Array.from(realm.getAllIpGroups().entries());\n\t\t\tfor (const [ip, clients] of ipGroups) {\n\t\t\t\tresult[ip] = Array.from(clients.values()).map((client) => ({\n\t\t\t\t\tid: client.getId(),\n\t\t\t\t\talias: client.getAlias(),\n\t\t\t\t}));\n\t\t\t}\n\n\t\t\treturn res.send(result);\n\t\t}\n\n\t\treturn res.sendStatus(401);\n\t});\n\n\treturn app;\n};\n"],"names":["$7BbP7$nodepath","$7BbP7$nodefs","$7BbP7$yargs","$7BbP7$hideBin","$7BbP7$express","$7BbP7$nodehttp","$7BbP7$nodehttps","$7BbP7$randomUUID","$7BbP7$EventEmitter","$7BbP7$WebSocketServer","$7BbP7$cors","Errors","MessageType","$aeb1147dec1b7a02$export$2e2bcd8739ae039","host","port","expire_timeout","alive_timeout","key","path","concurrent_limit","allow_discovery","proxied","cleanup_out_msgs","corsOptions","origin","$2c42eaf0ccc66758$export$eb4c623330d4cbcc","getLastReadAt","lastReadAt","addMessage","message","messages","push","readMessage","length","Date","getTime","shift","getMessages","$0a339ca52e0451c9$export$3ee29d34e33d9116","getClientsIds","clients","keys","getClientById","clientId","get","getClientsIdsWithQueue","messageQueues","setClient","client","id","set","ip","getIpAddress","ipGroup","clientsByIp","Map","removeClientById","delete","size","getMessageQueueById","addMessageToQueue","clearMessageQueue","generateClientId","generateId","getClientsByIp","ipAddress","getAllIpGroups","$6840aafc61c9abd6$export$6fa53df6b5b88df7","realm","config","checkInterval","onClose","timeoutId","start","clearTimeout","setTimeout","checkConnections","stop","clientsIds","now","aliveTimeout","timeSinceLastPing","getLastPing","getSocket","close","setSocket","$d461d7260b6fc353$export$b8e9cd941e8016ac","$d461d7260b6fc353$export$80edbf15fa61a4db","$c97baf9b78981954$export$a13b411d0e88b1af","messageHandler","startMessagesExpiration","pruneOutstanding","stopMessagesExpiration","destinationClientsIds","maxDiff","seen","destinationClientId","messageQueue","lastReadDiff","seenKey","src","dst","handle","undefined","type","EXPIRE","$d09fcb6ab78a3f48$export$1f2bb630327ac4b6","token","socket","lastPing","alias","getId","getToken","setLastPing","setIpAddress","getAlias","setAlias","send","data","JSON","stringify","$e99ba8b80c5ab00c$var$adjectives","$e99ba8b80c5ab00c$var$nouns","$4ae24f8b3b7cf7b0$export$f47674b57e51ee3b","server","setMaxListeners","endsWith","options","socketServer","createWebSocketServer","on","req","_onSocketConnection","error","_onSocketError","forwardedFor","headers","remoteAddress","firstIp","forwardedIp","Array","isArray","split","trim","searchParams","URL","url","Object","fromEntries","entries","_sendErrorAndClose","INVALID_WS_PARAMETERS","INVALID_KEY","ID_TAKEN","payload","msg","_configureWS","_registerClient","emit","adjective","noun","clientsCount","CONNECTION_LIMIT_EXCEED","newClient","Math","floor","random","OPEN","_notifyIpGroup","PEER_JOINED_IP_GROUP","clientIp","clientAlias","PEER_LEFT_IP_GROUP","parse","toString","e","ERROR","excludeClientId","readyState","$df0509eaca4ae82c$export$cfe4a96645b0bbcf","registerHandler","messageType","handler","handlers","has","$3089a9bad51bbb04$export$3deceafe0aaeaa95","handlersRegistry","transmissionHandler","srcId","dstId","destinationClient","Error","LEAVE","ignoredTypes","includes","handleTransmission","HEARTBEAT","heartbeatHandler","nowTime","OFFER","ANSWER","CANDIDATE","$264fdbd7932d14df$exports","$3809f3d53201df9f$var$y","process","argv","$3809f3d53201df9f$var$portEnvIsSet","env","$3809f3d53201df9f$var$opts","usage","wrap","min","terminalWidth","demandOption","describe","default","sslkey","sslcert","cors","array","boolean","parseSync","parseInt","console","readFileSync","resolve","cert","exit","$3809f3d53201df9f$var$userPath","$3809f3d53201df9f$var$server","callback","app","newOptions","ssl","restOptions","createServer","peerjs","api","Router","use","_","res","a","__esModule","contentType","sendStatus","peers","from","values","map","result","messagesExpire","checkBrokenConnections","wss","posix","join","listen","address","log","shutdownApp"],"version":3,"file":"peerjs.js.map","sourceRoot":"../../"}
|