@ciranda/dht-relay-http 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2026 Ciranda
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,140 @@
1
- # Temporary Holding Version
1
+ # dht-relay-http
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Relaying the Hyperswarm DHT over plain HTTP, for hosts that have nothing else.
4
+
5
+ A transport for [`@hyperswarm/dht-relay`](https://github.com/holepunchto/hyperswarm-dht-relay), next to its TCP and WebSocket ones. The relayed side sends frames with `POST` and receives them with a long-polling `GET`, through the HTTP client it is given, so it runs where an app gets no sockets at all, such as an Apple Watch, where only `URLSession` is allowed.
6
+
7
+ > [!NOTE]
8
+ > `@hyperswarm/dht-relay` was archived by Holepunch on 2026-10-15 and is marked experimental. This module works with its last release, 0.4.3, and will follow whatever replaces it.
9
+
10
+ ```
11
+ npm i @ciranda/dht-relay-http
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ On the relaying side:
17
+
18
+ ```js
19
+ const http = require('http')
20
+ const DHT = require('hyperdht')
21
+ const { relay } = require('@hyperswarm/dht-relay')
22
+ const Server = require('@ciranda/dht-relay-http/server')
23
+
24
+ const dht = new DHT()
25
+ const server = new Server((stream) => relay(dht, stream))
26
+
27
+ http.createServer((req, res) => server.handle(req, res)).listen(8080)
28
+ ```
29
+
30
+ On the relayed side:
31
+
32
+ ```js
33
+ const DHT = require('@hyperswarm/dht-relay')
34
+ const Stream = require('@ciranda/dht-relay-http')
35
+
36
+ const dht = new DHT(new Stream('https://relay.example.com', { fetch }), { custodial: false })
37
+ ```
38
+
39
+ Always pass `custodial: false`. The default of `@hyperswarm/dht-relay` sends the secret key of the client to the relay, which can then decrypt and sign everything as the client. With `custodial: false` the key stays on the client, Noise runs end to end, and the relay forwards ciphertext. It still sees the public keys, the topics and the address of the client.
40
+
41
+ The relayed side can connect to peers, not accept connections: `@hyperswarm/dht-relay` does not yet complete incoming connections without custody. Its 0.4.3 also passes the keep-alives of the remote peer to a client without custody as empty messages.
42
+
43
+ ### With URLSession
44
+
45
+ On Apple platforms, `URLSession` is all the stream needs. Bare gets it from [`bare-foundation`](https://github.com/holepunchto/bare-foundation), where it is proposed and not released yet:
46
+
47
+ ```js
48
+ const { URLSession, URLRequest } = require('bare-foundation')
49
+
50
+ function fetch(url, opts) {
51
+ return new Promise((resolve, reject) => {
52
+ const request = new URLRequest(url)
53
+
54
+ request.httpMethod = opts.method
55
+
56
+ for (const field in opts.headers) request.setValue(opts.headers[field], field)
57
+
58
+ if (opts.body) request.httpBody = opts.body
59
+
60
+ URLSession.shared
61
+ .dataTask(request, (err, response, data) => {
62
+ if (err) return reject(err)
63
+
64
+ resolve({
65
+ status: response.statusCode,
66
+ arrayBuffer: () =>
67
+ Promise.resolve(data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength))
68
+ })
69
+ })
70
+ .resume()
71
+ })
72
+ }
73
+ ```
74
+
75
+ `example.js` replicates a hypercore this way on a local testnet.
76
+
77
+ ## API
78
+
79
+ #### `const stream = new Stream(url, options)`
80
+
81
+ The relayed side. `options.fetch(url, { method, headers, body })` makes the requests and resolves to `{ status, arrayBuffer() }`. The `fetch` of Node and `bare-fetch` both do.
82
+
83
+ #### `const server = new Server(onstream[, options])`
84
+
85
+ The relaying side. `onstream(stream)` is called with a stream for every session a client opens.
86
+
87
+ Options include:
88
+
89
+ ```js
90
+ {
91
+ behindProxy: false, // Count sessions by the address the proxy put last in X-Forwarded-For
92
+ pollTimeout: 25000, // How long a poll is held, under the read timeout of any proxy in front
93
+ idleTimeout: 60000 // How long a session lives without a request
94
+ }
95
+ ```
96
+
97
+ #### `server.handle(req, res)`
98
+
99
+ Handle a request from `http` in Node or `bare-http1` in Bare.
100
+
101
+ #### `server.sessions`
102
+
103
+ The number of open sessions.
104
+
105
+ #### `server.destroy()`
106
+
107
+ Close every session.
108
+
109
+ ### CLI
110
+
111
+ ```sh
112
+ npm i -g @ciranda/dht-relay-http
113
+ dht-relay-http [--port 49443] [--host 0.0.0.0] [--behind-proxy]
114
+ ```
115
+
116
+ The relay speaks plain HTTP. Terminate TLS at a reverse proxy in front of it, such as Caddy or nginx, and pass `--behind-proxy`. Without TLS, anyone on the path sees which keys and topics a client asks for, and an Apple Watch only allows HTTPS anyway. The CLI logs how many sessions are open, never an address or a session.
117
+
118
+ With Caddy, which gets the certificate and sets `X-Forwarded-For`, that is one line next to the relay:
119
+
120
+ ```sh
121
+ dht-relay-http --host 127.0.0.1 --behind-proxy
122
+ caddy reverse-proxy --from relay.example.com --to 127.0.0.1:49443
123
+ ```
124
+
125
+ ## Protocol
126
+
127
+ Every request goes to the same URL. A session is named by 32 random bytes, sent as `Authorization: Bearer <hex>` and never in the URL, so it stays out of access logs.
128
+
129
+ - `POST` without a session opens one. The response body is its 32 bytes.
130
+ - `POST` with a session sends the frames in the body.
131
+ - `GET` returns the frames waiting for the client, or holds the request until some arrive, for up to `pollTimeout`.
132
+ - `DELETE` closes the session.
133
+
134
+ Bodies are `c.array(c.buffer)` from [`compact-encoding`](https://github.com/holepunchto/compact-encoding). Any status other than `200` ends the stream. Responses carry `Cache-Control: no-store`.
135
+
136
+ A session that falls 8 MiB behind is closed, a request body is at most 4 MiB, and an address has at most 8 sessions open.
137
+
138
+ ## License
139
+
140
+ Apache-2.0
package/bin.js ADDED
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env node
2
+
3
+ const http = require('http')
4
+ const DHT = require('hyperdht')
5
+ const { relay } = require('@hyperswarm/dht-relay')
6
+ const goodbye = require('graceful-goodbye')
7
+ const Server = require('./server')
8
+
9
+ const port = Number(arg('port')) || 49443
10
+ const host = arg('host') || undefined
11
+ const behindProxy = process.argv.includes('--behind-proxy')
12
+
13
+ const dht = new DHT()
14
+
15
+ const server = new Server(
16
+ (stream) => {
17
+ console.log('Session opened (' + server.sessions + ')')
18
+
19
+ stream.on('close', () => console.log('Session closed (' + server.sessions + ')'))
20
+
21
+ relay(dht, stream)
22
+ },
23
+ { behindProxy }
24
+ )
25
+
26
+ const http1 = http.createServer((req, res) => server.handle(req, res))
27
+
28
+ http1.listen(port, host, () => {
29
+ const { address, port } = http1.address()
30
+
31
+ console.log('Relay is listening on ' + address + ':' + port)
32
+ })
33
+
34
+ goodbye(async () => {
35
+ const closing = new Promise((resolve) => http1.close(resolve))
36
+
37
+ server.destroy()
38
+
39
+ await closing
40
+ await dht.destroy()
41
+ })
42
+
43
+ function arg(name) {
44
+ const i = process.argv.indexOf('--' + name)
45
+ if (i === -1 || i === process.argv.length - 1) return null
46
+ return process.argv[i + 1]
47
+ }
package/index.js ADDED
@@ -0,0 +1,90 @@
1
+ const { Duplex } = require('streamx')
2
+ const b4a = require('b4a')
3
+ const c = require('compact-encoding')
4
+
5
+ const frames = c.array(c.buffer)
6
+
7
+ const MAX_BATCH = 1024 * 1024 // Bytes of frames in one request
8
+
9
+ module.exports = class HTTPStream extends Duplex {
10
+ constructor(url, opts = {}) {
11
+ const { fetch } = opts
12
+
13
+ super()
14
+
15
+ this._url = url
16
+ this._fetch = fetch
17
+ this._session = null
18
+ this._closing = false
19
+ }
20
+
21
+ async _open(cb) {
22
+ try {
23
+ this._session = b4a.toString(await this._request('POST'), 'hex')
24
+ } catch (err) {
25
+ return cb(err)
26
+ }
27
+
28
+ cb(null)
29
+ }
30
+
31
+ async _read(cb) {
32
+ try {
33
+ for (const frame of c.decode(frames, await this._request('GET'))) this.push(frame)
34
+ } catch (err) {
35
+ return cb(err)
36
+ }
37
+
38
+ cb(null)
39
+ }
40
+
41
+ async _writev(batch, cb) {
42
+ try {
43
+ for (let i = 0, j = 0; i < batch.length; i = j) {
44
+ let size = 0
45
+
46
+ while (j < batch.length && (j === i || size + batch[j].byteLength <= MAX_BATCH)) {
47
+ size += batch[j++].byteLength
48
+ }
49
+
50
+ await this._request('POST', c.encode(frames, batch.slice(i, j)))
51
+ }
52
+ } catch (err) {
53
+ return cb(err)
54
+ }
55
+
56
+ cb(null)
57
+ }
58
+
59
+ _predestroy() {
60
+ this._close()
61
+ }
62
+
63
+ _destroy(cb) {
64
+ this._close()
65
+ cb(null)
66
+ }
67
+
68
+ _close() {
69
+ if (this._session === null || this._closing) return
70
+
71
+ this._closing = true
72
+ this._request('DELETE').catch(noop)
73
+ }
74
+
75
+ async _request(method, body) {
76
+ const headers = {}
77
+
78
+ if (this._session !== null) headers.authorization = 'Bearer ' + this._session
79
+ if (body) headers['content-type'] = 'application/octet-stream'
80
+
81
+ const res = await this._fetch(this._url, { method, headers, body })
82
+ const data = b4a.from(await res.arrayBuffer())
83
+
84
+ if (res.status !== 200) throw new Error('Relay responded with status ' + res.status)
85
+
86
+ return data
87
+ }
88
+ }
89
+
90
+ function noop() {}
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@ciranda/dht-relay-http",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Relaying the Hyperswarm DHT over plain HTTP, for hosts that have nothing else",
5
+ "exports": {
6
+ "./package": "./package.json",
7
+ ".": "./index.js",
8
+ "./server": "./server.js"
9
+ },
10
+ "bin": {
11
+ "dht-relay-http": "./bin.js"
12
+ },
13
+ "files": [
14
+ "index.js",
15
+ "server.js",
16
+ "bin.js",
17
+ "NOTICE"
18
+ ],
19
+ "imports": {
20
+ "http": {
21
+ "bare": "bare-http1",
22
+ "default": "http"
23
+ }
24
+ },
25
+ "scripts": {
26
+ "format": "prettier --write . && lunte --fix",
27
+ "lint": "prettier --check . && lunte",
28
+ "test": "npm run test:bare && npm run test:node",
29
+ "test:bare": "brittle-bare --coverage test.js",
30
+ "test:node": "brittle-node --coverage test.js"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/ciranda-dev/dht-relay-http.git"
35
+ },
36
+ "author": "Ciranda",
37
+ "license": "Apache-2.0",
38
+ "bugs": {
39
+ "url": "https://github.com/ciranda-dev/dht-relay-http/issues"
40
+ },
41
+ "homepage": "https://github.com/ciranda-dev/dht-relay-http#readme",
42
+ "dependencies": {
43
+ "@hyperswarm/dht-relay": "^0.4.3",
44
+ "b4a": "^1.9.0",
45
+ "compact-encoding": "^2.19.2",
46
+ "graceful-goodbye": "^1.3.3",
47
+ "hyperdht": "^6.36.0",
48
+ "sodium-universal": "^5.0.1",
49
+ "streamx": "^2.28.1"
50
+ },
51
+ "devDependencies": {
52
+ "bare-fetch": "^3.4.1",
53
+ "bare-http1": "^4.6.3",
54
+ "brittle": "^3.18.0",
55
+ "hypercore": "^11.40.3",
56
+ "hyperswarm": "^4.17.2",
57
+ "lunte": "^1.8.6",
58
+ "prettier": "^3.6.2",
59
+ "prettier-config-holepunch": "^2.0.0",
60
+ "test-tmp": "^1.4.0"
61
+ }
62
+ }
package/server.js ADDED
@@ -0,0 +1,206 @@
1
+ const { Duplex } = require('streamx')
2
+ const b4a = require('b4a')
3
+ const c = require('compact-encoding')
4
+ const sodium = require('sodium-universal')
5
+
6
+ const frames = c.array(c.buffer)
7
+
8
+ const MAX_BODY = 4 * 1024 * 1024 // Bytes in one request
9
+ const MAX_QUEUED = 8 * 1024 * 1024 // Bytes waiting for a session to poll
10
+ const MAX_SESSIONS = 8 // Sessions per address
11
+
12
+ const EMPTY = c.encode(frames, [])
13
+
14
+ module.exports = class HTTPServer {
15
+ constructor(onstream, opts = {}) {
16
+ const { behindProxy = false, pollTimeout = 25000, idleTimeout = 60000 } = opts
17
+
18
+ this._onstream = onstream
19
+ this._behindProxy = behindProxy
20
+ this._pollTimeout = pollTimeout
21
+ this._idleTimeout = idleTimeout
22
+ this._sessions = new Map()
23
+ this._addresses = new Map()
24
+ }
25
+
26
+ get sessions() {
27
+ return this._sessions.size
28
+ }
29
+
30
+ handle(req, res) {
31
+ res.setHeader('cache-control', 'no-store')
32
+
33
+ const { authorization } = req.headers
34
+
35
+ if (authorization === undefined) {
36
+ if (req.method === 'POST') return this._open(req, res)
37
+ return reply(res, 401)
38
+ }
39
+
40
+ const session = this._sessions.get(authorization.slice(7))
41
+
42
+ if (session === undefined) return reply(res, 404)
43
+
44
+ session._refresh()
45
+
46
+ switch (req.method) {
47
+ case 'GET':
48
+ return session._poll(res)
49
+ case 'POST':
50
+ return session._receive(req, res)
51
+ case 'DELETE':
52
+ session.destroy()
53
+ return reply(res, 200)
54
+ default:
55
+ return reply(res, 405)
56
+ }
57
+ }
58
+
59
+ destroy() {
60
+ for (const session of this._sessions.values()) session.destroy()
61
+ }
62
+
63
+ _open(req, res) {
64
+ const address = this._address(req)
65
+ const sessions = this._addresses.get(address) || 0
66
+
67
+ if (sessions >= MAX_SESSIONS) return reply(res, 429)
68
+
69
+ const id = b4a.allocUnsafe(32)
70
+ sodium.randombytes_buf(id)
71
+
72
+ const session = new HTTPSession(this, b4a.toString(id, 'hex'), address)
73
+
74
+ this._sessions.set(session._id, session)
75
+ this._addresses.set(address, sessions + 1)
76
+
77
+ this._onstream(session)
78
+
79
+ reply(res, 200, id)
80
+ }
81
+
82
+ _close(session) {
83
+ this._sessions.delete(session._id)
84
+
85
+ const sessions = this._addresses.get(session._address) - 1
86
+
87
+ if (sessions === 0) this._addresses.delete(session._address)
88
+ else this._addresses.set(session._address, sessions)
89
+ }
90
+
91
+ _address(req) {
92
+ if (this._behindProxy) {
93
+ const forwarded = req.headers['x-forwarded-for'] || ''
94
+
95
+ return forwarded.split(',').pop().trim()
96
+ }
97
+
98
+ return req.socket.remoteAddress
99
+ }
100
+ }
101
+
102
+ class HTTPSession extends Duplex {
103
+ constructor(server, id, address) {
104
+ super()
105
+
106
+ this._server = server
107
+ this._id = id
108
+ this._address = address
109
+ this._queue = []
110
+ this._queued = 0
111
+ this._polling = null
112
+ this._pollTimer = null
113
+ this._idleTimer = setTimeout(() => this.destroy(), server._idleTimeout)
114
+ }
115
+
116
+ _writev(batch, cb) {
117
+ for (const frame of batch) {
118
+ this._queue.push(frame)
119
+ this._queued += frame.byteLength
120
+ }
121
+
122
+ if (this._queued > MAX_QUEUED) return cb(new Error('Too many bytes queued'))
123
+
124
+ this._flush()
125
+
126
+ cb(null)
127
+ }
128
+
129
+ _destroy(cb) {
130
+ clearTimeout(this._idleTimer)
131
+ clearTimeout(this._pollTimer)
132
+
133
+ if (this._polling !== null) reply(this._polling, 410)
134
+
135
+ this._server._close(this)
136
+
137
+ cb(null)
138
+ }
139
+
140
+ _refresh() {
141
+ clearTimeout(this._idleTimer)
142
+ this._idleTimer = setTimeout(() => this.destroy(), this._server._idleTimeout)
143
+ }
144
+
145
+ _poll(res) {
146
+ if (this._polling !== null) this._end(EMPTY)
147
+
148
+ this._polling = res
149
+ this._pollTimer = setTimeout(() => this._end(EMPTY), this._server._pollTimeout)
150
+
151
+ this._flush()
152
+ }
153
+
154
+ _flush() {
155
+ if (this._polling === null || this._queue.length === 0) return
156
+
157
+ const data = c.encode(frames, this._queue)
158
+
159
+ this._queue = []
160
+ this._queued = 0
161
+
162
+ this._end(data)
163
+ }
164
+
165
+ _end(data) {
166
+ clearTimeout(this._pollTimer)
167
+
168
+ const res = this._polling
169
+ this._polling = null
170
+
171
+ reply(res, 200, data)
172
+ }
173
+
174
+ _receive(req, res) {
175
+ const chunks = []
176
+ let size = 0
177
+
178
+ req
179
+ .on('data', (data) => {
180
+ size += data.byteLength
181
+
182
+ if (size <= MAX_BODY) return chunks.push(data)
183
+
184
+ reply(res, 413)
185
+ req.destroy()
186
+ })
187
+ .on('end', () => {
188
+ let list
189
+
190
+ try {
191
+ list = c.decode(frames, b4a.concat(chunks))
192
+ } catch {
193
+ return reply(res, 400)
194
+ }
195
+
196
+ for (const frame of list) this.push(frame)
197
+
198
+ reply(res, 200)
199
+ })
200
+ }
201
+ }
202
+
203
+ function reply(res, status, data) {
204
+ res.statusCode = status
205
+ res.end(data)
206
+ }