-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
file_server.js
81 lines (65 loc) · 2.14 KB
/
file_server.js
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
// TODO: move this to packages/core-file-server
const _ = require('lodash')
const debug = require('debug')('cypress:server:file_server')
const url = require('url')
const http = require('http')
const path = require('path')
const send = require('send')
const { httpUtils } = require('@packages/network')
const { allowDestroy } = require('./util/server_destroy')
const random = require('./util/random')
const networkFailures = require('./util/network_failures')
const onRequest = function (req, res, expectedToken, fileServerFolder) {
const token = req.headers['x-cypress-authorization']
if (token !== expectedToken) {
debug('authorization failed on file_server request %o', { reqUrl: req.url, expectedToken, token })
res.statusCode = 401
res.end()
return
}
const args = _.compact([
fileServerFolder,
req.url,
])
// strip off any query params from our req's url
// since we're pulling this from the file system
// it does not understand query params
// and make sure we decode the uri which swaps out
// %20 with white space
const file = decodeURI(url.parse(path.join(...args)).pathname)
res.setHeader('x-cypress-file-path', file)
return send(req, url.parse(req.url).pathname, {
root: path.resolve(fileServerFolder),
})
.on('error', (err) => {
res.setHeader('x-cypress-file-server-error', true)
res.setHeader('content-type', 'text/html')
res.statusCode = err.status
return res.end(networkFailures.get(file, err.status))
}).pipe(res)
}
module.exports = {
create (fileServerFolder) {
return new Promise(((resolve) => {
const token = random.id(64)
const srv = http.createServer(httpUtils.lenientOptions, (req, res) => {
return onRequest(req, res, token, encodeURIComponent(fileServerFolder))
})
allowDestroy(srv)
return srv.listen(0, '127.0.0.1', () => {
return resolve({
token,
port () {
return srv.address().port
},
address () {
return `http://localhost:${this.port()}`
},
close () {
return srv.destroyAsync()
},
})
})
}))
},
}