Skip to content

Commit

Permalink
chore: inject config/mongodb via plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
ggazzo authored Dec 7, 2024
2 parents 6e8bc1f + ad4994a commit 1c33425
Show file tree
Hide file tree
Showing 22 changed files with 244 additions and 84 deletions.
2 changes: 0 additions & 2 deletions packages/main/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { logger } from "@bogeychan/elysia-logger";
import { Elysia } from "elysia";
import { config } from "./config";

import { BadJSONError, MatrixError } from "./errors";
import { fakeEndpoints } from "./routes/fake/room";
import federationEndpoints from "./routes/federation";
import { keyV2Endpoints } from "./routes/key/server";

export const app = new Elysia({
name: config.name,
handler: {
standardHostname: false,
},
Expand Down
6 changes: 1 addition & 5 deletions packages/main/src/authentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,7 @@ import crypto from "node:crypto";
import { toUnpaddedBase64 } from "./binaryData";
import type { SigningKey } from "./keys";
import { pruneEventDict } from "./pruneEventDict";
import {
type EncryptionValidAlgorithm,
encodeCanonicalJson,
signJson,
} from "./signJson";
import { encodeCanonicalJson, signJson } from "./signJson";
import type { EventBase } from "./events/eventBase";

export async function authorizationHeaders<T extends object>(
Expand Down
4 changes: 2 additions & 2 deletions packages/main/src/events/utils/createSignedEvent.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ describe("makeSignedEvent", () => {
sender: "@admin:hs1",
ts: 1733069433734,
});
const signed = await signEvent(event, signature);
const signed = await signEvent(event, signature, "hs1");
const id = generateId(signed);

const makeSignedEvent = createSignedEvent(signature);
const makeSignedEvent = createSignedEvent(signature, "hs1");
const result = await createRoomCreateEvent(makeSignedEvent)({
roomId: "!uTqsSSWabZzthsSCNf:hs1",
sender: "@admin:hs1",
Expand Down
9 changes: 7 additions & 2 deletions packages/main/src/events/utils/createSignedEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,15 @@ import { generateId } from "../../authentication";
import type { SigningKey } from "../../keys";
import { signEvent } from "../../signEvent";

export const createSignedEvent = (signature: SigningKey) => {
export const createSignedEvent = (
signature: SigningKey,
signingName: string,
) => {
return <F extends (...args: any) => any>(fn: F) => {
return async (...args: Parameters<F>): Promise<ReturnType<F>> => {
return signEvent(await fn(...args), signature) as Promise<ReturnType<F>>;
return signEvent(await fn(...args), signature, signingName) as Promise<
ReturnType<F>
>;
};
};
};
Expand Down
4 changes: 4 additions & 0 deletions packages/main/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@ import "@hs/endpoints/src/query";
import "@hs/endpoints/src/server";
import { app } from "./app";
import { config } from "./config";
import { routerWithConfig } from "./plugins/config";
import { routerWithMongodb } from "./plugins/mongodb";

console.log(config);

app
.use(swagger())
.use(routerWithMongodb)
.use(routerWithConfig)
.get("/", () => "")
.onError(async ({ error, request }) => {
if (!request.body) {
Expand Down
6 changes: 5 additions & 1 deletion packages/main/src/makeRequest.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import { authorizationHeaders, computeHash } from "./authentication";
import { config } from "./config";
import type { Config } from "./config";
import { signJson } from "./signJson";

export const makeRequest = async ({
method,
domain,
uri,
options = {},
config,
}: {
method: string;
domain: string;
uri: string;
options?: Record<string, any>;
config: Config;
}) => {
const signingKey = config.signingKey[0];

Expand Down Expand Up @@ -51,11 +53,13 @@ export const makeUnsignedRequest = async ({
domain,
uri,
options = {},
config,
}: {
method: string;
domain: string;
uri: string;
options?: Record<string, any>;
config: Config;
}) => {
const signingKey = config.signingKey[0];

Expand Down
8 changes: 8 additions & 0 deletions packages/main/src/plugins/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import Elysia from "elysia";
import type { InferContext } from "elysia";

import { config } from "../config";

export const routerWithConfig = new Elysia().decorate("config", config);

export type Context = InferContext<typeof routerWithConfig>;
5 changes: 5 additions & 0 deletions packages/main/src/plugins/isConfigContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import type { Context } from "./config";

export const isConfigContext = <T extends object>(
context: T,
): context is T & Context => "config" in context;
5 changes: 5 additions & 0 deletions packages/main/src/plugins/isMongodbContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import type { Context } from "./mongodb";

export const isMongodbContext = <T extends object>(
context: T,
): context is T & Context => "mongo" in context;
8 changes: 8 additions & 0 deletions packages/main/src/plugins/mongodb.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import Elysia from "elysia";
import type { InferContext } from "elysia";

import * as mongodb from "../mongodb";

export const routerWithMongodb = new Elysia().decorate("mongo", mongodb);

export type Context = InferContext<typeof routerWithMongodb>;
2 changes: 1 addition & 1 deletion packages/main/src/procedures/createRoom.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ test("createRoom", async () => {
"ed25519 a_XRhW YjbSyfqQeGto+OFswt+XwtJUUooHXH5w+czSgawN63U",
);

const makeSignedEvent = createSignedEvent(signature);
const makeSignedEvent = createSignedEvent(signature, "hs1");

const { roomId, events } = await createRoom(
"@sender:hs1",
Expand Down
48 changes: 37 additions & 11 deletions packages/main/src/routes/fake/room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@ import { Elysia, t } from "elysia";
import "@hs/endpoints/src/query";
import "@hs/endpoints/src/server";
import Crypto from "node:crypto";

import { generateId } from "../../authentication";
import { config } from "../../config";
import { roomMemberEvent } from "../../events/m.room.member";
import { makeUnsignedRequest } from "../../makeRequest";
import { signEvent } from "../../signEvent";
import type { EventBase } from "../../events/eventBase";
import { createSignedEvent } from "../../events/utils/createSignedEvent";
import { createRoom } from "../../procedures/createRoom";
import { isConfigContext } from "../../plugins/isConfigContext";
import { isMongodbContext } from "../../plugins/isMongodbContext";

function createMediaId(length: number) {
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Expand All @@ -25,7 +27,18 @@ function createMediaId(length: number) {
export const fakeEndpoints = new Elysia({ prefix: "/fake" })
.post(
"/createRoom",
async ({ body, error }) => {
async ({ body, error, ...context }) => {
if (!isConfigContext(context)) {
throw new Error("No config context");
}
if (!isMongodbContext(context)) {
throw new Error("No mongodb context");
}
const {
config,
mongo: { eventsCollection },
} = context;

const { username, sender } = body;

if (sender.split(":").pop() !== config.name) {
Expand All @@ -35,16 +48,14 @@ export const fakeEndpoints = new Elysia({ prefix: "/fake" })
const { roomId, events } = await createRoom(
sender,
username,
createSignedEvent(config.signingKey[0]),
createSignedEvent(config.signingKey[0], config.name),
`!${createMediaId(18)}:${config.name}`,
);

if (events.length === 0) {
return error(500, "Error creating room");
}

const { eventsCollection } = await import("../../mongodb");

await eventsCollection.insertMany(events);

return {
Expand Down Expand Up @@ -75,16 +86,25 @@ export const fakeEndpoints = new Elysia({ prefix: "/fake" })
)
.post(
"/inviteUserToRoom",
async ({ body, error }) => {
async ({ body, error, ...context }) => {
if (!isConfigContext(context)) {
throw new Error("No config context");
}
if (!isMongodbContext(context)) {
throw new Error("No mongodb context");
}
const {
config,
mongo: { eventsCollection },
} = context;

const { username, sender } = body;
let { roomId } = body;

if (!username.includes(":") || !username.includes("@")) {
return error(400, "Invalid username");
}

const { eventsCollection } = await import("../../mongodb");

// Create room if no roomId to facilitate tests
if (sender && !roomId) {
if (sender.split(":").pop() !== config.name) {
Expand All @@ -94,7 +114,7 @@ export const fakeEndpoints = new Elysia({ prefix: "/fake" })
const { roomId: newRoomId, events } = await createRoom(
sender,
username,
createSignedEvent(config.signingKey[0]),
createSignedEvent(config.signingKey[0], config.name),
`!${createMediaId(18)}:${config.name}`,
);
roomId = newRoomId;
Expand Down Expand Up @@ -186,6 +206,7 @@ export const fakeEndpoints = new Elysia({ prefix: "/fake" })
options: {
body: payload,
},
config,
});

console.log(response.status);
Expand All @@ -212,7 +233,7 @@ export const fakeEndpoints = new Elysia({ prefix: "/fake" })
examples: [
{
username: "@admin:hs1",
roomId: `!uTqsSSWabZzthsSCNf:${config.name}`,
roomId: "!uTqsSSWabZzthsSCNf:homeserver",
},
],
},
Expand All @@ -225,7 +246,12 @@ export const fakeEndpoints = new Elysia({ prefix: "/fake" })
)
.post(
"/sendMessage",
async ({ body, error }) => {
async ({ body, error, ...context }) => {
if (!isConfigContext(context)) {
throw new Error("No config context");
}
const { config } = context;

const { sender, roomId, msg, target } = body;

const { eventsCollection } = await import("../../mongodb");
Expand Down
11 changes: 8 additions & 3 deletions packages/main/src/routes/federation/getMissingEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,24 @@ import { Elysia, t } from "elysia";

import "@hs/endpoints/src/query";
import "@hs/endpoints/src/server";
import { isMongodbContext } from "../../plugins/isMongodbContext";

//POST http://rc1:443/_matrix/federation/v1/get_missing_events/%21EiexWZWYPDXWLzPRCq%3Arc1

export const getMissingEvents = new Elysia().post(
"/get_missing_events/:roomId",
async ({ params, body }) => {
async ({ params, body, ...context }) => {
if (!isMongodbContext(context)) {
throw new Error("No mongodb context");
}
const {
mongo: { eventsCollection },
} = context;
const roomId = decodeURIComponent(params.roomId);

console.log("get_missing_events ->", { roomId });
console.log("get_missing_events ->", { body });

const { eventsCollection } = await import("../../mongodb");

console.log({
_id: { $in: [...body.earliest_events, ...body.latest_events] },
"event.room_id": roomId,
Expand Down
2 changes: 2 additions & 0 deletions packages/main/src/routes/federation/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,5 @@ const federationV2Endpoints = new Elysia({
export default new Elysia()
.use(federationV1Endpoints)
.use(federationV2Endpoints);

// export default new Elysia();
18 changes: 15 additions & 3 deletions packages/main/src/routes/federation/invite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,27 @@ import { Elysia, t } from "elysia";

import "@hs/endpoints/src/query";
import "@hs/endpoints/src/server";
import { config } from "../../config";
import { InviteEventDTO } from "../../dto";
import { StrippedStateDTO } from "../../dto";
import { ErrorDTO } from "../../dto";
import { makeRequest } from "../../makeRequest";
import { generateId } from "../../authentication";
import { isMongodbContext } from "../../plugins/isMongodbContext";
import { isConfigContext } from "../../plugins/isConfigContext";

export const inviteEndpoint = new Elysia().put(
"/invite/:roomId/:eventId",
async ({ params, body }) => {
const { eventsCollection } = await import("../../mongodb");
async ({ params, body, ...context }) => {
if (!isMongodbContext(context)) {
throw new Error("No mongodb context");
}
if (!isConfigContext(context)) {
throw new Error("No config context");
}
const {
config,
mongo: { eventsCollection },
} = context;

console.log("invite received ->", { params, body });

Expand All @@ -28,6 +38,7 @@ export const inviteEndpoint = new Elysia().put(
method: "GET",
domain: event.origin,
uri: `/_matrix/federation/v1/make_join/${params.roomId}/${event.state_key}?ver=10`,
config,
});

const responseMake = await response.json();
Expand Down Expand Up @@ -66,6 +77,7 @@ export const inviteEndpoint = new Elysia().put(
options: {
body: joinBody,
},
config,
});

const responseBody = await responseSend.json();
Expand Down
Loading

0 comments on commit 1c33425

Please sign in to comment.