From c4ecf14395d5d370f7aa655e114bdc85ba790b72 Mon Sep 17 00:00:00 2001 From: Naomi Carrigan Date: Mon, 10 Feb 2025 19:48:32 -0800 Subject: [PATCH] feat: authenticate all requests --- src/modules/auth.ts | 24 ++++++++++++++++++++++++ src/server/serve.ts | 13 +++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 src/modules/auth.ts diff --git a/src/modules/auth.ts b/src/modules/auth.ts new file mode 100644 index 0000000..b86c06e --- /dev/null +++ b/src/modules/auth.ts @@ -0,0 +1,24 @@ +/** + * @copyright nhcarrigan + * @license Naomi's Public License + * @author Naomi Carrigan + */ + +import type { FastifyRequest } from "fastify"; + +/** + * Confirms that the auth header has been set to the correct + * token. + * @param request - The incoming Fastify request. + * @returns Whether the request is authenticated. + */ +export const auth = (request: FastifyRequest): boolean => { + if (request.headers.authorization === undefined) { + return false; + } + const token = request.headers.authorization; + if (token !== process.env.API_AUTH) { + return false; + } + return true; +}; diff --git a/src/server/serve.ts b/src/server/serve.ts index f3d5f57..ea610c5 100644 --- a/src/server/serve.ts +++ b/src/server/serve.ts @@ -6,6 +6,7 @@ import fastify from "fastify"; import { MsgType, type MatrixClient } from "matrix-js-sdk"; +import { auth } from "../modules/auth.js"; import { errorSchema } from "../schemas/errorSchema.js"; import { logSchema } from "../schemas/logSchema.js"; import { uptimeSchema } from "../schemas/uptimeSchema.js"; @@ -68,6 +69,10 @@ export const instantiateServer = (client: MatrixClient): void => { // eslint-disable-next-line @typescript-eslint/naming-convention -- Body must be capitalised for Fastify. server.post<{ Body: Log }>("/log", logSchema, async(request, response) => { + if (!auth(request)) { + await response.status(401).send({ success: false }); + return; + } const { application, level, message } = request.body; await client.sendMessage(process.env.MATRIX_ROOM_ID ?? "", { body: `**${application}** - *${level}*\n${message}`, @@ -84,6 +89,10 @@ export const instantiateServer = (client: MatrixClient): void => { "/error", errorSchema, async(request, response) => { + if (!auth(request)) { + await response.status(401).send({ success: false }); + return; + } const { application, context, stack, message } = request.body; await client.sendMessage(process.env.MATRIX_ROOM_ID ?? "", { body: `**${application}** - *Error in ${context}*\n${message}\n\`\`\`\n${stack}\n\`\`\``, @@ -101,6 +110,10 @@ export const instantiateServer = (client: MatrixClient): void => { "/uptime", uptimeSchema, async(request, response) => { + if (!auth(request)) { + await response.status(401).send({ success: false }); + return; + } const { application, message } = request.body; await client.sendMessage(process.env.MATRIX_ROOM_ID ?? "", { body: `${message}\n${application}`,