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:
Naomi Carrigan 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

38
.gitea/workflows/ci.yml Normal file
View File

@ -0,0 +1,38 @@
name: Node.js CI
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
lint:
name: Lint and Test
steps:
- name: Checkout Source Files
uses: actions/checkout@v4
- name: Use Node.js v22
uses: actions/setup-node@v4
with:
node-version: 22
- name: Setup pnpm
uses: pnpm/action-setup@v2
with:
version: 9
- name: Install Dependencies
run: pnpm install
- name: Lint Source Files
run: pnpm run lint
- name: Verify Build
run: pnpm run build
- name: Run Tests
run: pnpm run test

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
node_modules
prod
coverage

6
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,6 @@
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"eslint.validate": ["typescript"]
}

View File

@ -1,20 +1,10 @@
# New Repository Template
# Rosalia Nightsong
This template contains all of our basic files for a new GitHub repository. There is also a handy workflow that will create an issue on a new repository made from this template, with a checklist for the steps we usually take in setting up a new repository.
If you're starting a Node.JS project with TypeScript, we have a [specific template](https://github.com/naomi-lgbt/nodejs-typescript-template) for that purpose.
## Readme
Delete all of the above text (including this line), and uncomment the below text to use our standard readme template.
<!-- # Project Name
Project Description
This is a basic webserver and Matrix bot that allows us to pipe application logs and errors to our Matrix server.
## Live Version
This page is currently deployed. [View the live website.]
This page is currently deployed. [View the live website.](https://alerts.nhcarrigan.com)
## Feedback and Bugs

5
eslint.config.js Normal file
View File

@ -0,0 +1,5 @@
import NaomisConfig from "@nhcarrigan/eslint-config";
export default [
...NaomisConfig
]

27
package.json Normal file
View File

@ -0,0 +1,27 @@
{
"name": "alert-server",
"version": "0.0.0",
"description": "A web server that sends alerts to our Matrix room.",
"main": "index.js",
"type": "module",
"scripts": {
"build": "rm -rf prod && tsc",
"lint": "eslint src --max-warnings 0",
"start": "op run --env-file=prod.env --no-masking -- node prod/index.js",
"test": "echo \"Error: no test specified\" && exit 0"
},
"keywords": [],
"author": "Naomi Carrigan",
"license": "See license in LICENSE.md",
"devDependencies": {
"@nhcarrigan/eslint-config": "5.1.0",
"@nhcarrigan/typescript-config": "4.0.0",
"@types/node": "22.13.1",
"eslint": "9.20.0",
"typescript": "5.7.3"
},
"dependencies": {
"fastify": "5.2.1",
"matrix-js-sdk": "36.1.0"
}
}

4452
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

3
prod.env Normal file
View File

@ -0,0 +1,3 @@
MATRIX_ACCESS_TOKEN="op://Environment Variables - Naomi/Alert Server/matrix_access_token"
MATRIX_ROOM_ID="op://Environment Variables - Naomi/Alert Server/matrix_room_id"
API_AUTH="op://Environment Variables - Naomi/Alert Server/api_auth"

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,
});
}
};

8
tsconfig.json Normal file
View File

@ -0,0 +1,8 @@
{
"extends": "@nhcarrigan/typescript-config",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./prod"
},
"exclude": ["test/**/*.ts", "vitest.config.ts"]
}