import fastify from 'fastify' import auth from 'basic-auth' import fastifyStatic from 'fastify-static' import path from 'path' import connectionsHandler from './connections' import configHandler from './config' import controlHandler from './control' import discordHandler from './discord' import messengerHandler from './messenger' import { Reply } from '../types/fastify' const log = logger.withScope('api') export default function runServer () { const app = fastify() app.register(fastifyStatic, { root: path.join(__dirname, '..', '..', 'node_modules'), prefix: '/node_modules/', decorateReply: false }) app.register(fastifyStatic, { root: path.join(__dirname, '..', '..', 'static'), prefix: '/static/' }) app.decorateReply('sendError', function (this: Reply, code: number, message: string) { this.code(code).send(new Error(message)) }) if (config.api.key) { app.addHook('preHandler', (request, reply, next) => { const { authorization } = request.headers if (!authorization) { reply.sendError(403, 'API key missing') return } if (!authorization.startsWith('Bearer ')) { reply.sendError(403, 'API key incorrect') return } const key = authorization.split(' ')[1] if (key !== config.api.key) { reply.sendError(403, 'API key incorrect') return } next() }) } else { app.addHook('preHandler', (request, reply, next) => { const send401 = () => reply .code(401) .header('WWW-Authenticate', 'Basic realm="Miscord API"') .header('Content-Type', 'text/html') .send('