Welcome to mirror list, hosted at ThFree Co, Russian Federation.

server.js « lib - github.com/webtorrent/webtorrent.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 7b980e44b805cfe9df4abe70ebaa442d7d25df18 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
const http = require('http')
const escapeHtml = require('escape-html')
const mime = require('mime')
const pump = require('pump')
const rangeParser = require('range-parser')
const queueMicrotask = require('queue-microtask')
const { Readable } = require('stream')

const keepAliveTime = 20000

class ServerBase {
  constructor (client, opts = {}) {
    this.client = client
    if (!opts.origin) opts.origin = '*' // allow all origins by default
    this.opts = opts
  }

  static serveIndexPage (res, torrents) {
    const listHtml = torrents
      .map(torrent => (
      `<li>
        <a href="${escapeHtml(torrent.infoHash)}">
          ${escapeHtml(torrent.name)}
        </a>
        (${escapeHtml(torrent.length)} bytes)
      </li>`
      ))
      .join('<br>')


    res.status = 200
    res.headers['Content-Type'] = 'text/html'
    res.body = getPageHTML(
      'WebTorrent',
        `<h1>WebTorrent</h1>
         <ol>${listHtml}</ol>`
    )

    return res
  }

  isOriginAllowed (req) {
    // When `origin` option is `false`, deny all cross-origin requests
    if (this.opts.origin === false) return false

    // The user allowed all origins
    if (this.opts.origin === '*') return true

    // Allow requests where the 'Origin' header matches the `opts.origin` setting
    return req.headers.origin === this.opts.origin
  }

  static serveMethodNotAllowed (res) {
    res.status = 405
    res.headers['Content-Type'] = 'text/html'

    res.body = getPageHTML(
      '405 - Method Not Allowed',
      '<h1>405 - Method Not Allowed</h1>'
    )

    return res
  }

  static serve404Page (res) {
    res.status = 404
    res.headers['Content-Type'] = 'text/html'

    res.body = getPageHTML(
      '404 - Not Found',
      '<h1>404 - Not Found</h1>'
    )
    return res
  }

  static serveTorrentPage (torrent, res) {
    const listHtml = torrent.files
      .map(file => (
    `<li>
      <a href="${torrent.infoHash}/${escapeHtml(file.path)}">
        ${escapeHtml(file.path)}
      </a>
      (${escapeHtml(file.length)} bytes)
    </li>`
      ))
      .join('<br>')


    res.status = 200
    res.headers['Content-Type'] = 'text/html'

    res.body = getPageHTML(
        `${escapeHtml(torrent.name)} - WebTorrent`,
        `<h1>${escapeHtml(torrent.name)}</h1>
        <ol>${listHtml}</ol>`
    )

    return res
  }

  static serveOptionsRequest (req, res) {
    res.status = 204 // no content
    res.headers['Access-Control-Max-Age'] = '600'
    res.headers['Access-Control-Allow-Methods'] = 'GET,HEAD'


    if (req.headers['access-control-request-headers']) {
      res.headers['Access-Control-Allow-Headers'] = req.headers['access-control-request-headers']
    }
    return res
  }

  static serveFile (file, req, res) {
    res.status = 200

    // Disable caching as data is local anyways
    res.headers.Expires = '0'
    res.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate, max-age=0'
    // Support range-requests
    res.headers['Accept-Ranges'] = 'bytes'
    res.headers['Content-Type'] = mime.getType(file.name) || 'application/octet-stream'
    // Support DLNA streaming
    res.headers['transferMode.dlna.org'] = 'Streaming'
    res.headers['contentFeatures.dlna.org'] = 'DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000'

    // Force the browser to download the file if if it's opened in a new tab
    // Set name of file (for "Save Page As..." dialog)
    if (req.destination === 'document') {
      res.headers['Content-Type'] = 'application/octet-stream'
      res.headers['Content-Disposition'] = `attachment; filename*=UTF-8''${encodeRFC5987(file.name)}`
      res.body = 'DOWNLOAD'
    } else {
      res.headers['Content-Disposition'] = `inline; filename*=UTF-8''${encodeRFC5987(file.name)}`
    }

    // `rangeParser` returns an array of ranges, or an error code (number) if
    // there was an error parsing the range.
    let range = rangeParser(file.length, req.headers.range || '')

    if (Array.isArray(range)) {
      res.status = 206 // indicates that range-request was understood

      // no support for multi-range request, just use the first range
      range = range[0]

      res.headers['Content-Range'] = `bytes ${range.start}-${range.end}/${file.length}`

      res.headers['Content-Length'] = range.end - range.start + 1
    } else {
      res.statusCode = 200
      range = null
      res.headers['Content-Length'] = file.length
    }


    const stream = req.method === 'GET' && file.createReadStream(range)

    let pipe = null
    if (stream) {
      file.emit('stream', { stream, req, file }, target => {
        pipe = pump(stream, target)
      })
    }
    res.body = pipe || stream
    return res
  }

  onRequest (req, cb) {
    let pathname = new URL(req.url, 'http://example.com').pathname
    pathname = pathname.slice(pathname.indexOf(this.pathname) + this.pathname.length + 1)

    const res = {
      headers: {
        // Prevent browser mime-type sniffing
        'X-Content-Type-Options': 'nosniff',
        // Defense-in-depth: Set a strict Content Security Policy to mitigate XSS
        'Content-Security-Policy': "base-uri 'none'; frame-ancestors 'none'; form-action 'none';"
      }
    }

    // Allow cross-origin requests (CORS)
    if (this.isOriginAllowed(req)) {
      res.headers['Access-Control-Allow-Origin'] = this.opts.origin === '*' ? '*' : req.headers.origin
    }

    if (pathname === 'favicon.ico') {
      return cb(ServerBase.serve404Page(res))
    }

    // Allow CORS requests to specify arbitrary headers, e.g. 'Range',
    // by responding to the OPTIONS preflight request with the specified
    // origin and requested headers.
    if (req.method === 'OPTIONS') {
      if (this.isOriginAllowed(req)) return cb(ServerBase.serveOptionsRequest(req, res))
      else return cb(ServerBase.serveMethodNotAllowed(res))
    }

    const onReady = () => {
      this.pendingReady.delete(onReady)
      cb(handleRequest())
    }

    const handleRequest = () => {
      if (pathname === '') {
        return ServerBase.serveIndexPage(res, this.client.torrents)
      }

      let [infoHash, ...filePath] = pathname.split('/')
      filePath = decodeURI(filePath.join('/'))

      const torrent = this.client.get(infoHash)
      if (!infoHash || !torrent) {
        return ServerBase.serve404Page(res)
      }

      if (!filePath) {
        return ServerBase.serveTorrentPage(torrent, res)
      }

      const file = torrent.files.find(file => file.path.replace(/\\/, '/') === filePath)
      if (!file) {
        return ServerBase.serve404Page(res)
      }
      return ServerBase.serveFile(file, req, res)
    }

    if (req.method === 'GET' || req.method === 'HEAD') {
      if (this.client.ready) {
        return cb(handleRequest())
      } else {
        this.pendingReady.add(onReady)
        this.client.once('ready', onReady)
        return
      }
    }

    return ServerBase.serveMethodNotAllowed(res)
  }

  close (cb = () => {}) {
    this.closed = true
    this.pendingReady.forEach(onReady => {
      this.client.removeListener('ready', onReady)
    })
    this.pendingReady.clear()
    queueMicrotask(cb)
  }

  destroy (cb = () => {}) {
    // Only call `server.close` if user has not called it already
    if (this.closed) queueMicrotask(cb)
    else this.close(cb)
    this.client = null
  }
}

class NodeServer extends ServerBase {
  constructor (client, opts) {
    super(client, opts)

    this.server = http.createServer()

    this.sockets = new Set()
    this.pendingReady = new Set()
    this.closed = false
    this.pathname = opts?.pathname || '/webtorrent'
  }

  wrapRequest (req, res) {
    // If a 'hostname' string is specified, deny requests with a 'Host'
    // header that does not match the origin of the torrent server to prevent
    // DNS rebinding attacks.
    if (this.opts.hostname && req.headers.host !== `${this.opts.hostname}:${this.server.address().port}`) {
      return req.destroy()
    }

    if (!new URL(req.url, 'http://example.com').pathname.startsWith(this.pathname)) {
      return req.destroy()
    }

    this.onRequest(req, ({ status, headers, body }) => {
      res.writeHead(status, headers)

      if (body instanceof Readable) { // this is probably a bad way of checking? idk
        pump(body, res)
      } else {
        res.end(body)
      }
    })
  }

  onConnection (socket) {
    socket.setTimeout(36000000)
    this.sockets.add(socket)
    socket.once('close', () => {
      this.sockets.delete(socket)
    })
  }

  listen (...args) {
    this.closed = false
    this.server.on('connection', this.onConnection.bind(this))
    this.server.on('request', this.wrapRequest.bind(this))
    return this.server.listen(...args)
  }

  close (cb) {
    this.server.removeListener('connection', this.onConnection)
    this.server.removeListener('request', this.wrapRequest)
    this.server.close(cb)
    super.close()
  }

  destroy (cb) {
    this.sockets.forEach(socket => {
      socket.destroy()
    })
    super.destroy(cb)
  }
}

class BrowserServer extends ServerBase {
  constructor (client, opts) {
    super(client, opts)

    this.registration = opts.controller
    this.workerKeepAliveInterval = null
    this.workerPortCount = 0

    this.pathname = new URL(opts.controller.scope).pathname + 'webtorrent'

    navigator.serviceWorker.addEventListener('message', this.wrapRequest.bind(this))
    // test if browser supports cancelling sw Readable Streams
    fetch(`${this.pathname}/cancel/`).then(res => {
      res.body.cancel()
    })
  }

  wrapRequest (event) {
    const req = event.data

    if (!req?.type === 'webtorrent' || !req.url) return null

    const [port] = event.ports
    this.onRequest(req, ({ status, headers, body }) => {
      const asyncIterator = body instanceof Readable && body[Symbol.asyncIterator]()

      const cleanup = () => {
        port.onmessage = null
        if (body?.destroy) body.destroy()
        this.workerPortCount--
        if (!this.workerPortCount) {
          clearInterval(this.workerKeepAliveInterval)
          this.workerKeepAliveInterval = null
        }
      }

      port.onmessage = async msg => {
        if (msg.data) {
          let chunk
          try {
            chunk = (await asyncIterator.next()).value
          } catch (e) {
            // chunk is yet to be downloaded or it somehow failed, should this be logged?
          }
          port.postMessage(chunk)
          if (!chunk) cleanup()
          if (!this.workerKeepAliveInterval) {
            this.workerKeepAliveInterval = setInterval(() => fetch(`${this.pathname}/keepalive/`), keepAliveTime)
          }
        } else {
          cleanup()
        }
      }
      this.workerPortCount++
      port.postMessage({
        status,
        headers,
        body: asyncIterator ? 'STREAM' : body
      })
    })
  }

  close (cb) {
    navigator.serviceWorker.removeEventListener('message'.this.wrapRequest.bind(this))
    super.close(cb)
  }

  destroy (cb) {
    super.destroy(cb)
  }
}


// NOTE: Arguments must already be HTML-escaped
function getPageHTML (title, pageHtml) {
  return `
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>${title}</title>
      </head>
      <body>
        ${pageHtml}
      </body>
    </html>
  `
}

// From https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
function encodeRFC5987 (str) {
  return encodeURIComponent(str)
    // Note that although RFC3986 reserves "!", RFC5987 does not,
    // so we do not need to escape it
    .replace(/['()]/g, escape) // i.e., %27 %28 %29
    .replace(/\*/g, '%2A')
    // The following are not required for percent-encoding per RFC5987,
    // so we can allow for a little better readability over the wire: |`^
    .replace(/%(?:7C|60|5E)/g, unescape)
}

module.exports = { NodeServer, BrowserServer }