This repository has been archived by the owner on Jan 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
220 lines (187 loc) · 6.48 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
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
var express = require('express')
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser')
var expressValidator = require('express-validator')
var RateLimit = require('express-rate-limit')
var vhost = require('vhost')
var bytes = require('bytes')
var Hypercloud = require('./lib')
var customValidators = require('./lib/validators')
var customSanitizers = require('./lib/sanitizers')
var packageJson = require('./package.json')
module.exports = function (config) {
if (config.pm2) {
var pmx = require('pmx').init({
http: true, // HTTP routes logging (default: true)
ignore_routes: [], // Ignore http routes with this pattern (Default: [])
errors: true, // Exceptions logging (default: true)
custom_probes: true, // Auto expose JS Loop Latency and HTTP req/s as custom metrics
network: true, // Network monitoring at the application level
ports: true // Shows which ports your app is listening on (default: false)
})
}
addConfigHelpers(config)
var cloud = new Hypercloud(config)
cloud.version = packageJson.version
cloud.setupAdminUser()
var app = express()
app.cloud = cloud
app.config = config
app.approveDomains = approveDomains(config, cloud)
app.locals = {
session: false, // default session value
errors: false, // common default value
appInfo: {
version: packageJson.version,
brandname: config.brandname,
hostname: config.hostname,
port: config.port
}
}
app.use(cookieParser())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded())
app.use(expressValidator({ customValidators, customSanitizers }))
app.use(cloud.sessions.middleware())
if (config.rateLimiting) {
app.use(new RateLimit({windowMs: 1e3, max: 100, delayMs: 0})) // general rate limit
app.use('/v1/verify', actionLimiter(24, 'Too many accounts created from this IP, please try again after an hour'))
app.use('/v1/login', actionLimiter(1, 'Too many login attempts from this IP, please try again after an hour'))
}
// http gateway
// =
if (config.sites) {
var httpGatewayApp = express()
httpGatewayApp.get('/.well-known/dat', cloud.api.archiveFiles.getDNSFile)
httpGatewayApp.get('*', cloud.api.archiveFiles.getFile)
app.use(vhost('*.' + config.hostname, httpGatewayApp))
}
// service apis
// =
app.get('/', cloud.api.service.frontpage)
app.get('/v1/explore', cloud.api.service.explore)
// user & auth apis
// =
app.post('/v1/register', cloud.api.users.doRegister)
app.all('/v1/verify', cloud.api.users.verify)
app.get('/v1/account', cloud.api.users.getAccount)
app.post('/v1/account', cloud.api.users.updateAccount)
app.post('/v1/account/password', cloud.api.users.updateAccountPassword)
app.post('/v1/account/email', cloud.api.users.updateAccountEmail)
app.post('/v1/login', cloud.api.users.doLogin)
app.get('/v1/logout', cloud.api.users.doLogout)
app.post('/v1/forgot-password', cloud.api.users.doForgotPassword)
app.get('/v1/users/:username([^/]{3,})', cloud.api.users.get)
// archives apis
// =
app.post('/v1/archives/add', cloud.api.archives.add)
app.post('/v1/archives/remove', cloud.api.archives.remove)
app.get('/v1/archives/:key([0-9a-f]{64})', cloud.api.archives.get)
app.get('/v1/users/:username([^/]{3,})/:archivename', cloud.api.archives.getByName)
// admin apis
// =
app.get('/v1/admin/users', cloud.api.admin.listUsers)
app.get('/v1/admin/users/:id', cloud.api.admin.getUser)
app.post('/v1/admin/users/:id', cloud.api.admin.updateUser)
app.post('/v1/admin/users/:id/suspend', cloud.api.admin.suspendUser)
app.post('/v1/admin/users/:id/unsuspend', cloud.api.admin.unsuspendUser)
app.post('/v1/admin/users/:username/send-email', cloud.api.admin.sendEmail)
app.get('/v1/admin/archives/:key', cloud.api.admin.getArchive)
// (json) error-handling fallback
// =
app.use((err, req, res, next) => {
var contentType = req.accepts('json')
if (!contentType) {
return next()
}
// validation errors
if ('isEmpty' in err) {
return res.status(422).json({
message: 'There were errors in your submission',
invalidInputs: true,
details: err.mapped()
})
}
// common errors
if ('status' in err) {
res.status(err.status)
res.json(err.body)
return
}
// general uncaught error
console.error('[ERROR]', err)
res.status(500)
var error = {
message: 'Internal server error',
internalError: true
}
res.json(error)
})
// ui module handlers
// =
if (config.ui) {
app.use(require(config.ui)({cloud, config}))
}
// error handling
// =
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason)
})
// shutdown
// =
app.close = cloud.close.bind(cloud)
return app
}
function actionLimiter (perHour, message) {
return new RateLimit({
windowMs: perHour * 60 * 60 * 1000,
delayMs: 0,
max: 5, // start blocking after 5 requests
message
})
}
function addConfigHelpers (config) {
config.getUserDiskQuota = (userRecord) => {
return userRecord.diskQuota || bytes(config.defaultDiskUsageLimit)
}
config.getUserDiskQuotaPct = (userRecord) => {
return userRecord.diskUsage / config.getUserDiskQuota(userRecord)
}
}
function approveDomains (config, cloud) {
return async (options, certs, cb) => {
var {domain} = options
options.agreeTos = true
options.email = config.letsencrypt.email
// toplevel domain?
if (domain === config.hostname) {
return cb(null, {options, certs})
}
// try looking up the site
try {
var archiveName
var userName
var domainParts = domain.split('.')
if (config.sites === 'per-user') {
// make sure the user record exists
userName = domainParts[0]
await cloud.usersDB.getByUsername(userName)
return cb(null, {options, certs})
} else if (config.sites === 'per-archive') {
// make sure the user and archive records exists
if (domainParts.length === 3) {
userName = archiveName = domainParts[0]
} else {
archiveName = domainParts[0]
userName = domainParts[1]
}
let userRecord = await cloud.usersDB.getByUsername(userName)
let archiveRecord = userRecord.archives.find(a => a.name === archiveName)
if (archiveRecord) {
return cb(null, {options, certs})
}
}
} catch (e) {}
cb(new Error('Invalid domain'))
}
}