filesafe/lolisafe.js

211 lines
7.4 KiB
JavaScript
Raw Normal View History

const config = require('./config')
const api = require('./routes/api')
const album = require('./routes/album')
const nojs = require('./routes/nojs')
const express = require('express')
const bodyParser = require('body-parser')
const clamd = require('clamdjs')
const db = require('knex')(config.database)
const fs = require('fs')
const helmet = require('helmet')
const nunjucks = require('nunjucks')
const RateLimit = require('express-rate-limit')
2018-12-03 09:18:52 +00:00
const readline = require('readline')
const safe = express()
// It appears to be best to catch these before doing anything else
2019-01-01 05:34:16 +00:00
// Probably before require() too, especially require('knex')(db), but nevermind
process.on('uncaughtException', error => {
console.error('Uncaught Exception:', error)
})
process.on('unhandledRejection', error => {
console.error('Unhandled Rejection (Promise):', error)
})
require('./database/db.js')(db)
2019-01-01 05:34:16 +00:00
// Check and create missing directories
fs.existsSync('./pages/custom') || fs.mkdirSync('./pages/custom')
fs.existsSync(`./${config.logsFolder}`) || fs.mkdirSync(`./${config.logsFolder}`)
fs.existsSync(`./${config.uploads.folder}`) || fs.mkdirSync(`./${config.uploads.folder}`)
fs.existsSync(`./${config.uploads.folder}/chunks`) || fs.mkdirSync(`./${config.uploads.folder}/chunks`)
fs.existsSync(`./${config.uploads.folder}/thumbs`) || fs.mkdirSync(`./${config.uploads.folder}/thumbs`)
fs.existsSync(`./${config.uploads.folder}/zips`) || fs.mkdirSync(`./${config.uploads.folder}/zips`)
safe.use(helmet())
if (config.trustProxy) safe.set('trust proxy', 1)
2018-10-09 19:52:41 +00:00
// https://mozilla.github.io/nunjucks/api.html#configure
nunjucks.configure('views', {
autoescape: true,
2018-10-09 19:52:41 +00:00
express: safe,
2019-01-01 05:34:16 +00:00
noCache: process.env.NODE_ENV === 'development'
})
safe.set('view engine', 'njk')
safe.enable('view cache')
const limiter = new RateLimit({ windowMs: 5000, max: 2 })
safe.use('/api/login/', limiter)
safe.use('/api/register/', limiter)
safe.use(bodyParser.urlencoded({ extended: true }))
safe.use(bodyParser.json())
2019-01-05 21:09:47 +00:00
if (config.cacheControl) {
safe.use('/', (req, res, next) => {
// max-age: 12 hours (aimed at the HTML pages themselves)
res.set('Cache-Control', 'public, max-age=43200, must-revalidate, proxy-revalidate, stale-while-revalidate=86400, stale-if-error=86400')
next()
})
const setHeaders = res => {
res.set('Access-Control-Allow-Origin', '*')
// max-age: 30 days
res.set('Cache-Control', 'public, max-age=2592000, must-revalidate, proxy-revalidate, immutable, stale-while-revalidate=86400, stale-if-error=604800')
}
if (config.serveFilesWithNode)
safe.use('/', express.static(config.uploads.folder, { setHeaders }))
2019-01-05 21:09:47 +00:00
safe.use('/', express.static('./public', { setHeaders }))
// Do NOT cache dynamic routes
safe.use(['/a', '/api', '/nojs'], (req, res, next) => {
2019-01-05 21:09:47 +00:00
res.set('Cache-Control', 'no-store')
next()
})
// But do cache album ZIPs
safe.use('/api/album/zip', (req, res, next) => {
setHeaders(res)
next()
})
2019-01-05 21:09:47 +00:00
} else {
if (config.serveFilesWithNode)
safe.use('/', express.static(config.uploads.folder))
safe.use('/', express.static('./public'))
}
safe.use('/', album)
safe.use('/', nojs)
safe.use('/api', api)
2017-01-14 06:01:23 +00:00
2018-12-20 12:25:41 +00:00
if (!Array.isArray(config.pages) || !config.pages.length) {
2018-12-20 14:43:31 +00:00
console.error('config.pages is not an array or is an empty array. This won\'t do!')
process.exit(1)
}
2018-12-20 12:25:41 +00:00
for (const page of config.pages)
if (fs.existsSync(`./pages/custom/${page}.html`)) {
safe.get(`/${page}`, (req, res, next) => res.sendFile(`${page}.html`, {
root: './pages/custom/'
}))
} else if (page === 'home') {
safe.get('/', (req, res, next) => res.render('home', {
maxSize: config.uploads.maxSize,
urlMaxSize: config.uploads.urlMaxSize,
urlDisclaimerMessage: config.uploads.urlDisclaimerMessage,
urlExtensionsFilterMode: config.uploads.urlExtensionsFilterMode,
urlExtensionsFilter: config.uploads.urlExtensionsFilter,
gitHash: safe.get('git-hash')
}))
} else if (page === 'faq') {
const fileLength = config.uploads.fileLength
safe.get('/faq', (req, res, next) => res.render('faq', {
whitelist: config.extensionsFilterMode === 'whitelist',
extensionsFilter: config.extensionsFilter,
fileLength,
tooShort: (fileLength.max - fileLength.default) > (fileLength.default - fileLength.min),
noJsMaxSize: parseInt(config.cloudflare.noJsMaxSize) < parseInt(config.uploads.maxSize),
chunkSize: config.uploads.chunkSize
}))
} else {
safe.get(`/${page}`, (req, res, next) => res.render(page))
}
safe.use((req, res, next) => {
res.status(404).sendFile(config.errorPages[404], { root: config.errorPages.rootDir })
2018-01-24 18:31:31 +00:00
})
safe.use((error, req, res, next) => {
console.error(error)
res.status(500).sendFile(config.errorPages[500], { root: config.errorPages.rootDir })
})
const start = async () => {
if (config.showGitHash) {
const gitHash = await new Promise((resolve, reject) => {
require('child_process').exec('git rev-parse HEAD', (error, stdout) => {
if (error) return reject(error)
resolve(stdout.replace(/\n$/, ''))
})
}).catch(console.error)
if (!gitHash) return
console.log(`Git commit: ${gitHash}`)
safe.set('git-hash', gitHash)
}
2019-01-01 05:34:16 +00:00
const scan = config.uploads.scan
if (scan && scan.enabled) {
const created = await new Promise(async (resolve, reject) => {
2019-01-01 05:34:16 +00:00
if (!scan.ip || !scan.port)
return reject(new Error('clamd IP or port is missing'))
2019-01-01 05:34:16 +00:00
const ping = await clamd.ping(scan.ip, scan.port).catch(reject)
if (!ping)
return reject(new Error('Could not ping clamd'))
2019-01-01 05:34:16 +00:00
const version = await clamd.version(scan.ip, scan.port).catch(reject)
console.log(`${scan.ip}:${scan.port} ${version}`)
const scanner = clamd.createScanner(scan.ip, scan.port)
safe.set('clam-scanner', scanner)
return resolve(true)
}).catch(error => console.error(error.toString()))
if (!created) return process.exit(1)
}
2018-12-04 13:35:49 +00:00
if (config.uploads.cacheFileIdentifiers) {
2018-12-03 09:18:52 +00:00
// Cache tree of uploads directory
process.stdout.write('Caching identifiers in uploads directory ...')
const setSize = await new Promise((resolve, reject) => {
const uploadsDir = `./${config.uploads.folder}`
fs.readdir(uploadsDir, (error, names) => {
if (error) return reject(error)
2018-12-03 09:18:52 +00:00
const set = new Set()
names.forEach(name => set.add(name.split('.')[0]))
safe.set('uploads-set', set)
resolve(set.size)
})
}).catch(error => console.error(error.toString()))
if (!setSize) return process.exit(1)
2018-12-03 09:18:52 +00:00
process.stdout.write(` ${setSize} OK!\n`)
}
2018-10-09 19:52:41 +00:00
safe.listen(config.port, () => {
console.log(`lolisafe started on port ${config.port}`)
2019-01-01 05:34:16 +00:00
// NODE_ENV=development yarn start
if (process.env.NODE_ENV === 'development') {
// Add readline interface to allow evaluating arbitrary JavaScript from console
readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: ''
}).on('line', line => {
try {
if (line === '.exit') process.exit(0)
// eslint-disable-next-line no-eval
process.stdout.write(`${require('util').inspect(eval(line), { depth: 0 })}\n`)
} catch (error) {
console.error(error.toString())
}
}).on('SIGINT', () => {
process.exit(0)
})
2019-01-01 05:34:16 +00:00
console.log('Development mode enabled (disabled nunjucks caching & enabled readline interface)')
2018-10-09 19:52:41 +00:00
}
})
}
start()