feat: initial project prototype (#1)
Some checks failed
Node.js CI / Lint and Test (push) Has been cancelled

### Explanation

_No response_

### Issue

_No response_

### Attestations

- [x] I have read and agree to the [Code of Conduct](https://docs.nhcarrigan.com/community/coc/)
- [x] I have read and agree to the [Community Guidelines](https://docs.nhcarrigan.com/community/guide/).
- [x] My contribution complies with the [Contributor Covenant](https://docs.nhcarrigan.com/dev/covenant/).

### Dependencies

- [x] I have pinned the dependencies to a specific patch version.

### Style

- [x] I have run the linter and resolved any errors.
- [x] My pull request uses an appropriate title, matching the conventional commit standards.
- [x] My scope of feat/fix/chore/etc. correctly matches the nature of changes in my pull request.

### Tests

- [ ] My contribution adds new code, and I have added tests to cover it.
- [ ] My contribution modifies existing code, and I have updated the tests to reflect these changes.
- [ ] All new and existing tests pass locally with my changes.
- [ ] Code coverage remains at or above the configured threshold.

### Documentation

_No response_

### Versioning

Major - My pull request introduces a breaking change.

Reviewed-on: #1
Co-authored-by: Naomi Carrigan <commits@nhcarrigan.com>
Co-committed-by: Naomi Carrigan <commits@nhcarrigan.com>
This commit is contained in:
2025-02-10 20:05:06 -08:00
committed by Naomi Carrigan
parent b0647ab963
commit f015cd2911
18 changed files with 4859 additions and 13 deletions

40
src/index.ts Normal file
View File

@ -0,0 +1,40 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { createClient } from "matrix-js-sdk";
import { instantiateServer } from "./server/serve.js";
import type { Logger } from "matrix-js-sdk/lib/logger.js";
const logger: Logger = {
debug: () => {
return null;
},
error: () => {
return null;
},
getChild: () => {
return logger;
},
info: () => {
return null;
},
trace: () => {
return null;
},
warn: () => {
return null;
},
};
const client = createClient({
accessToken: process.env.MATRIX_ACCESS_TOKEN ?? "",
baseUrl: "https://matrix.nhcarrigan.com",
logger: logger,
userId: "@alerts:matrix.nhcarrigan.com",
});
await client.startClient({ initialSyncLimit: 10 });
instantiateServer(client);

11
src/interfaces/error.ts Normal file
View File

@ -0,0 +1,11 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
export interface Error {
application: string;
stack: string;
message: string;
context: string;
}

10
src/interfaces/log.ts Normal file
View File

@ -0,0 +1,10 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
export interface Log {
application: string;
level: string;
message: string;
}

9
src/interfaces/uptime.ts Normal file
View File

@ -0,0 +1,9 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
export interface Uptime {
application: string;
message: string;
}

24
src/modules/auth.ts Normal file
View File

@ -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;
};

View File

@ -0,0 +1,19 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
export const errorSchema = {
schema: {
body: {
properties: {
application: { type: "string" },
context: { type: "string" },
message: { type: "string" },
stack: { type: "string" },
},
type: "object",
},
},
};

18
src/schemas/logSchema.ts Normal file
View File

@ -0,0 +1,18 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
export const logSchema = {
schema: {
body: {
properties: {
application: { type: "string" },
level: { type: "string" },
message: { type: "string" },
},
type: "object",
},
},
};

View File

@ -0,0 +1,17 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
export const uptimeSchema = {
schema: {
body: {
properties: {
application: { type: "string" },
message: { type: "string" },
},
type: "object",
},
},
};

166
src/server/serve.ts Normal file
View File

@ -0,0 +1,166 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
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";
import type { Error } from "../interfaces/error.js";
import type { Log } from "../interfaces/log.js";
import type { Uptime } from "../interfaces/uptime.js";
const html = `<!DOCTYPE html>
<html>
<head>
<title>Rosalia Nightsong</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="A basic web server and Matrix bot that allows us to pipe logs and errors from our applications into a Matrix room." />
<script src="https://cdn.nhcarrigan.com/headers/index.js" async defer></script>
</head>
<body>
<main>
<h1>Rosalia Nightsong</h1>
<section>
<p>A basic web server and Matrix bot that allows us to pipe logs and errors from our applications into a Matrix room.</p>
</section>
<section>
<h2>Links</h2>
<p>
<a href="https://git.nhcarrigan.com/nhcarrigan/rosalia-nightsong">
<i class="fa-solid fa-code"></i> Source Code
</a>
</p>
<p>
<a href="https://docs.nhcarrigan.com/">
<i class="fa-solid fa-book"></i> Documentation
</a>
</p>
<p>
<a href="https://chat.nhcarrigan.com">
<i class="fa-solid fa-circle-info"></i> Support
</a>
</p>
</section>
</main>
</body>
</html>`;
/**
* Starts up the server to receive events.
* @param client - The authenticated Matrix client.
*/
// eslint-disable-next-line max-lines-per-function -- This function is long because it is setting up a server.
export const instantiateServer = (client: MatrixClient): void => {
try {
const server = fastify({
logger: false,
});
server.get("/", (_request, response) => {
response.header("Content-Type", "text/html");
response.send(html);
});
// 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}`,
format: "org.matrix.custom.html",
// eslint-disable-next-line @typescript-eslint/naming-convention -- Requirement of the SDK.
formatted_body: `<strong>${application}</strong> - <em>${level}</em><br>${message}`,
msgtype: MsgType.Text,
});
await response.status(200).send({ success: true });
});
// eslint-disable-next-line @typescript-eslint/naming-convention -- Body must be capitalised for Fastify.
server.post<{ Body: Error }>(
"/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\`\`\``,
format: "org.matrix.custom.html",
// eslint-disable-next-line @typescript-eslint/naming-convention -- Requirement of the SDK.
formatted_body: `<strong>${application}</strong> - <em>Error in ${context}</em><br>${message}<br><code>${stack}</code>`,
msgtype: MsgType.Text,
});
await response.status(200).send({ success: true });
},
);
// eslint-disable-next-line @typescript-eslint/naming-convention -- Body must be capitalised for Fastify.
server.post<{ Body: Uptime }>(
"/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}`,
format: "org.matrix.custom.html",
// eslint-disable-next-line @typescript-eslint/naming-convention -- Requirement of the SDK.
formatted_body: `${message}<br><sub>${application}</sub>`,
msgtype: MsgType.Text,
});
await response.status(200).send({ success: true });
},
);
server.listen({ port: 5003 }, (error) => {
const application = "Alert Server";
if (error) {
const { message, stack } = error;
const context = "Server Startup";
void client.sendMessage(process.env.MATRIX_ROOM_ID ?? "", {
body: `**${application}** - *Error in ${context}*\n${message}\n\`\`\`\n${stack ?? "No stack trace available."}\n\`\`\``,
format: "org.matrix.custom.html",
// eslint-disable-next-line @typescript-eslint/naming-convention -- Requirement of the SDK.
formatted_body: `<strong>${application}</strong> - <em>Error in ${context}</em><br>${message}<br><code>${stack ?? "No stack trace available."}</code>`,
msgtype: MsgType.Text,
});
return;
}
const level = "debug";
const message = `Server listening on port 5003.`;
void client.sendMessage(process.env.MATRIX_ROOM_ID ?? "", {
body: `**${application}** - *${level}*\n${message}`,
format: "org.matrix.custom.html",
// eslint-disable-next-line @typescript-eslint/naming-convention -- Requirement of the SDK.
formatted_body: `<strong>${application}</strong> - <em>${level}</em><br>${message}`,
msgtype: MsgType.Text,
});
});
} catch (error) {
const application = "Alert Server";
const context = "Server Startup";
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Totally being lazy.
const { message, stack } = error as Error;
void client.sendMessage(process.env.MATRIX_ROOM_ID ?? "", {
body: `**${application}** - *Error in ${context}*\n${message}\n\`\`\`\n${stack}\n\`\`\``,
format: "org.matrix.custom.html",
// eslint-disable-next-line @typescript-eslint/naming-convention -- Requirement of the SDK.
formatted_body: `<strong>${application}</strong> - <em>Error in ${context}</em><br>${message}<br><code>${stack}</code>`,
msgtype: MsgType.Text,
});
}
};