-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
103 lines (84 loc) · 2.06 KB
/
server.js
File metadata and controls
103 lines (84 loc) · 2.06 KB
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
const pino = require('pino')
const log = pino({ name: 'licensezero-server' })
log.info({ directory: process.env.DIRECTORY }, 'starting')
// Environment Variables
const requiredEnvironmentVariables = [
'DIRECTORY',
'NODE_ENV',
'PORT',
'PRIVATE_KEY',
'PUBLIC_KEY',
'REDIRECT'
]
if (process.env.NODE_ENV !== 'test') {
requiredEnvironmentVariables.push(
'SMTP_HOST',
'SMTP_PORT',
'SMTP_USER',
'SMTP_PASSWORD'
)
}
requiredEnvironmentVariables.forEach(key => {
if (!process.env[key]) {
log.error({ key }, 'missing environment variable')
process.exit(1)
}
})
const schemas = require('./schemas')
if (!schemas.validate.publicKey(process.env.PUBLIC_KEY)) {
log.error({ key: 'PUBLIC_KEY' }, 'invalid public key')
process.exit(1)
}
if (!schemas.validate.privateKey(process.env.PRIVATE_KEY)) {
log.error({ key: 'PRIVATE_KEY' }, 'invalid public key')
process.exit(1)
}
// HTTP Server
const requestHandler = require('./')(log)
const server = require('http').createServer(requestHandler)
// Trap signals.
process
.on('SIGTERM', logSignalAndShutDown)
.on('SIGQUIT', logSignalAndShutDown)
.on('SIGINT', logSignalAndShutDown)
.on('uncaughtException', exception => {
log.error(exception)
shutDown()
})
server.listen(process.env.PORT, function () {
const port = this.address().port
log.info({ port }, 'listening')
})
// Background Jobs
const schedule = require('node-schedule')
const jobs = require('./jobs')
const running = []
jobs.forEach(job => {
job(log, () => { /* pass */ })
const scheduled = schedule.scheduleJob('0 * * * *', () => {
job(log, () => { /* pass */ })
})
running.push(scheduled)
})
// Policy Enforcement
const policyLog = log.child({ subsystem: 'policy' })
require('./policy/enforce')(policyLog, error => {
if (error) {
policyLog.error(error)
shutDown()
}
})
// Shutdown
function logSignalAndShutDown () {
log.info('signal')
shutDown()
}
function shutDown () {
server.close(() => {
log.info('closed')
running.forEach(job => {
job.cancel()
})
process.exit()
})
}