-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
63 lines (53 loc) · 2.05 KB
/
index.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
var http = require('http')
var accepts = require('accepts')
var parse = require('url').parse
module.exports = function (options) {
options = options || {}
// port to serve
var port = options.port
var host = options.host || 'localhost'
// strict-transport-security and cache-control
var STS = 'max-age=' + options.maxAge || '16070400'
if (options.includeSubDomains !== false) STS += '; includeSubDomains'
return http.createServer(function (req, res) {
var url = parse(req.url)
var location = 'https://' + (req.headers.host || host) + url.path
res.setHeader('Strict-Transport-Security', STS)
// these are generally browser requests,
// so let's not bother with a JSON response :D
var method = req.method
if (method === 'HEAD' || method === 'GET') {
res.statusCode = 301
res.setHeader('Location', location)
if (req.method === 'HEAD') return res.end()
if (accepts(req).types('html') === 'html') {
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.end('SSL is required. Redirecting to <a href="' + location + '">' + location + '</a>.')
} else {
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('SSL is required. Redirecting to ' + location + '.')
}
return
}
// these are non-HEAD/GET requests,
// so probably API requests.
res.statusCode = 403
switch (accepts(req).types('html', 'json')) {
case 'html':
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.end('SSL is required. Please try again at <a href="' + location + '">' + location + '</a>.')
return
case 'json':
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(JSON.stringify({
message: 'SSL is required. Please try again at ' + location + '.',
error: true,
status: 403,
}))
return
default:
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('SSL is required. Please try again at ' + location + '.')
}
}).listen(port)
}