Skip to content

Commit

Permalink
chore: reorganize project according with responsibilities
Browse files Browse the repository at this point in the history
  • Loading branch information
ggazzo authored Dec 7, 2024
2 parents 300fcce + 9a4cc82 commit 2648906
Show file tree
Hide file tree
Showing 68 changed files with 356 additions and 131 deletions.
Binary file modified bun.lockb
Binary file not shown.
14 changes: 2 additions & 12 deletions packages/main/src/config.ts → config.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,5 @@
import { type SigningKey, getKeyPair } from "./keys";
import { type EncryptionValidAlgorithm, signText } from "./signJson";

export interface Config {
path: string;
signingKeyPath: string;
port: number;
signingKey: SigningKey[];
name: string;
version: string;
}

import { getKeyPair } from "homeserver";
import type { Config } from "homeserver/src/plugins/config";
const { CONFIG_FOLDER = "." } = process.env;

const getConfig = async (): Promise<Config> => {
Expand Down
19 changes: 18 additions & 1 deletion index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,21 @@
// // /v1/openid/userinfo
// // /v1/hierarchy/{roomID}

import "myapp";
import Elysia from "elysia";
import { app } from "homeserver";
import { fakeEndpoints } from "fake";
import { routerWithMongodb } from "homeserver/src/plugins/mongodb";

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

new Elysia()
.decorate("config", config)
.use(routerWithMongodb(db))
.use(app)
.use(fakeEndpoints)
.listen(config.port, (context) => {
console.log(
`🦊 Elysia is running at http://${context.hostname}:${context.port}`,
);
});
12 changes: 12 additions & 0 deletions mongo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { MongoClient } from "mongodb";

const MONGODB_URI = process.env.MONGODB_URI;
if (!MONGODB_URI) {
throw new Error(
"Please define the MONGODB_URI environment variable inside .env",
);
}

const client = await MongoClient.connect(MONGODB_URI);

export const db = client.db(MONGODB_URI.split("/").pop());
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
"dependencies": {
"@bogeychan/elysia-logger": "^0.1.4",
"@elysiajs/swagger": "^1.1.6",
"elysia": "^1.1.26",
"@hs/homeserver": "workspace:*",
"@hs/fake": "workspace:*",
"mongodb": "^6.11.0",
"node-jsonwebtoken": "^0.0.1",
"tweetnacl": "^1.0.3"
Expand Down
File renamed without changes.
File renamed without changes.
18 changes: 18 additions & 0 deletions packages/fake/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "@hs/fake",
"version": "1.0.50",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "bun run --watch src/index.ts"
},
"dependencies": {
"@hs/endpoints": "workspace:*",
"@hs/homeserver": "workspace:*",
"elysia": "latest"
},
"devDependencies": {
"bun-types": "latest"
},
"main": "./src/index.ts",
"types": "./src/index.ts"
}
1 change: 1 addition & 0 deletions packages/fake/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./room";
43 changes: 29 additions & 14 deletions packages/main/src/routes/fake/room.ts → packages/fake/src/room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ import "@hs/endpoints/src/query";
import "@hs/endpoints/src/server";
import Crypto from "node:crypto";

import { generateId } from "../../authentication";
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";
import { generateId } from "@hs/homeserver/src/authentication";
import { isConfigContext } from "@hs/homeserver/src/plugins/isConfigContext";
import { isMongodbContext } from "@hs/homeserver/src/plugins/isMongodbContext";
import { createRoom } from "@hs/homeserver/src/procedures/createRoom";
import { createSignedEvent } from "@hs/homeserver/src/events/utils/createSignedEvent";
import { signEvent } from "@hs/homeserver/src/signEvent";
import { roomMemberEvent } from "@hs/homeserver/src/events/m.room.member";
import { makeUnsignedRequest } from "@hs/homeserver/src/makeRequest";
import type { EventBase } from "@hs/homeserver/src/events/eventBase";

function createMediaId(length: number) {
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Expand Down Expand Up @@ -159,18 +159,21 @@ export const fakeEndpoints = new Elysia({ prefix: "/fake" })
age: 4, // TODO: Check what this is
invite_room_state: [
{
// @ts-ignore
content: {},
sender: events[0].event.sender,
state_key: "",
type: "m.room.join_rules",
},
{
// @ts-ignore
content: {},
sender: events[0].event.sender,
state_key: "",
type: "m.room.create",
},
{
// @ts-ignore
content: {},
sender: events[0].event.sender,
state_key: events[0].event.sender,
Expand All @@ -180,6 +183,7 @@ export const fakeEndpoints = new Elysia({ prefix: "/fake" })
},
}),
config.signingKey[0],
config.name,
);

const inviteEventId = generateId(inviteEvent);
Expand All @@ -206,7 +210,8 @@ export const fakeEndpoints = new Elysia({ prefix: "/fake" })
options: {
body: payload,
},
config,
signingKey: config.signingKey[0],
signingName: config.name,
});

console.log(response.status);
Expand Down Expand Up @@ -250,12 +255,16 @@ export const fakeEndpoints = new Elysia({ prefix: "/fake" })
if (!isConfigContext(context)) {
throw new Error("No config context");
}
const { config } = context;
if (!isMongodbContext(context)) {
throw new Error("No mongodb context");
}
const {
config,
mongo: { eventsCollection },
} = context;

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

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

const create = await eventsCollection.findOne({
"event.room_id": roomId,
"event.type": "m.room.create",
Expand Down Expand Up @@ -311,7 +320,11 @@ export const fakeEndpoints = new Elysia({ prefix: "/fake" })
sender,
};

const signedEvent = await signEvent(event, config.signingKey[0]);
const signedEvent = await signEvent(
event,
config.signingKey[0],
config.name,
);
const eventId = generateId(signedEvent);

await eventsCollection.insertOne({
Expand All @@ -333,6 +346,8 @@ export const fakeEndpoints = new Elysia({ prefix: "/fake" })
options: {
body: payload,
},
signingKey: config.signingKey[0],
signingName: config.name,
});

const responseMake = await response.json();
Expand Down
File renamed without changes.
44 changes: 44 additions & 0 deletions packages/homeserver/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local

# vercel
.vercel

**/*.trace
**/*.zip
**/*.tar.gz
**/*.tgz
**/*.log
package-lock.json
**/*.bun

*.key
19 changes: 19 additions & 0 deletions packages/homeserver/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Elysia with Bun runtime

## Getting Started

To get started with this template, simply paste this command into your terminal:

```bash
bun create elysia ./elysia-example
```

## Development

To start the development server run:

```bash
bun run dev
```

Open http://localhost:3000/ with your browser to see the result.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "myapp",
"name": "@hs/homeserver",
"version": "1.0.50",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
Expand All @@ -12,5 +12,6 @@
"devDependencies": {
"bun-types": "latest"
},
"module": "src/index.js"
"main": "./src/index.ts",
"types": "./src/index.ts"
}
File renamed without changes.
2 changes: 0 additions & 2 deletions packages/main/src/app.ts → packages/homeserver/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { logger } from "@bogeychan/elysia-logger";
import { Elysia } from "elysia";

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

Expand Down Expand Up @@ -31,7 +30,6 @@ export const app = new Elysia({
)
.use(keyV2Endpoints)
.use(federationEndpoints)
.use(fakeEndpoints)
.onError(async ({ code }) => {
if (code === "NOT_FOUND") {
return {
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
14 changes: 3 additions & 11 deletions packages/main/src/index.ts → packages/homeserver/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,11 @@ import swagger from "@elysiajs/swagger";
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);
import { getKeyPair } from "./keys";

app
.use(swagger())
.use(routerWithMongodb)
.use(routerWithConfig)
.get("/", () => "")
.onError(async ({ error, request }) => {
if (!request.body) {
Expand All @@ -25,9 +20,6 @@ app
console.log("body ->", body);

return error;
})
.listen(config.port, () => {
console.log(
`🦊 Elysia is running at http://${app.server?.hostname}:${app.server?.port}`,
);
});

export { app, getKeyPair };
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,34 +1,35 @@
import { authorizationHeaders, computeHash } from "./authentication";
import type { Config } from "./config";
import type { SigningKey } from "./keys";

import { signJson } from "./signJson";

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

const body =
options.body &&
(await signJson(
computeHash({ ...options.body, signatures: {} }),
config.signingKey[0],
config.name,
signingKey,
signingName,
));

console.log("body ->", method, domain, uri, body);

const auth = await authorizationHeaders(
config.name,
signingName,
signingKey,
domain,
method,
Expand All @@ -53,18 +54,18 @@ export const makeUnsignedRequest = async ({
domain,
uri,
options = {},
config,
signingKey,
signingName,
}: {
method: string;
domain: string;
uri: string;
options?: Record<string, any>;
config: Config;
signingKey: SigningKey;
signingName: string;
}) => {
const signingKey = config.signingKey[0];

const auth = await authorizationHeaders(
config.name,
signingName,
signingKey,
domain,
method,
Expand Down
Loading

0 comments on commit 2648906

Please sign in to comment.