diff --git a/bun.lockb b/bun.lockb index 77344a6d..8a094a19 100755 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/packages/main/src/config.ts b/config.ts similarity index 75% rename from packages/main/src/config.ts rename to config.ts index bfb3323a..ac3f2bb1 100644 --- a/packages/main/src/config.ts +++ b/config.ts @@ -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 => { diff --git a/index.ts b/index.ts index 19f96b0c..90ee88b3 100644 --- a/index.ts +++ b/index.ts @@ -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}`, + ); + }); diff --git a/mongo.ts b/mongo.ts new file mode 100644 index 00000000..e3d6233f --- /dev/null +++ b/mongo.ts @@ -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()); diff --git a/package.json b/package.json index 237360c5..294f1d96 100644 --- a/package.json +++ b/package.json @@ -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" diff --git a/packages/main/.gitignore b/packages/fake/.gitignore similarity index 100% rename from packages/main/.gitignore rename to packages/fake/.gitignore diff --git a/packages/main/README.md b/packages/fake/README.md similarity index 100% rename from packages/main/README.md rename to packages/fake/README.md diff --git a/packages/fake/package.json b/packages/fake/package.json new file mode 100644 index 00000000..ff54990f --- /dev/null +++ b/packages/fake/package.json @@ -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" +} diff --git a/packages/fake/src/index.ts b/packages/fake/src/index.ts new file mode 100644 index 00000000..fb317351 --- /dev/null +++ b/packages/fake/src/index.ts @@ -0,0 +1 @@ +export * from "./room"; diff --git a/packages/main/src/routes/fake/room.ts b/packages/fake/src/room.ts similarity index 87% rename from packages/main/src/routes/fake/room.ts rename to packages/fake/src/room.ts index 8d7c113b..bc9feffb 100644 --- a/packages/main/src/routes/fake/room.ts +++ b/packages/fake/src/room.ts @@ -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"; @@ -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, @@ -180,6 +183,7 @@ export const fakeEndpoints = new Elysia({ prefix: "/fake" }) }, }), config.signingKey[0], + config.name, ); const inviteEventId = generateId(inviteEvent); @@ -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); @@ -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", @@ -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({ @@ -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(); diff --git a/packages/main/tsconfig.json b/packages/fake/tsconfig.json similarity index 100% rename from packages/main/tsconfig.json rename to packages/fake/tsconfig.json diff --git a/packages/homeserver/.gitignore b/packages/homeserver/.gitignore new file mode 100644 index 00000000..df0219a5 --- /dev/null +++ b/packages/homeserver/.gitignore @@ -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 \ No newline at end of file diff --git a/packages/homeserver/README.md b/packages/homeserver/README.md new file mode 100644 index 00000000..bebf0610 --- /dev/null +++ b/packages/homeserver/README.md @@ -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. diff --git a/packages/main/package.json b/packages/homeserver/package.json similarity index 76% rename from packages/main/package.json rename to packages/homeserver/package.json index 6578d10f..b823830e 100644 --- a/packages/main/package.json +++ b/packages/homeserver/package.json @@ -1,5 +1,5 @@ { - "name": "myapp", + "name": "@hs/homeserver", "version": "1.0.50", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", @@ -12,5 +12,6 @@ "devDependencies": { "bun-types": "latest" }, - "module": "src/index.js" + "main": "./src/index.ts", + "types": "./src/index.ts" } diff --git a/packages/main/src/app.spec.ts b/packages/homeserver/src/app.spec.ts similarity index 100% rename from packages/main/src/app.spec.ts rename to packages/homeserver/src/app.spec.ts diff --git a/packages/main/src/app.ts b/packages/homeserver/src/app.ts similarity index 92% rename from packages/main/src/app.ts rename to packages/homeserver/src/app.ts index 325e00e0..c904b329 100644 --- a/packages/main/src/app.ts +++ b/packages/homeserver/src/app.ts @@ -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"; @@ -31,7 +30,6 @@ export const app = new Elysia({ ) .use(keyV2Endpoints) .use(federationEndpoints) - .use(fakeEndpoints) .onError(async ({ code }) => { if (code === "NOT_FOUND") { return { diff --git a/packages/main/src/authentication.spec.ts b/packages/homeserver/src/authentication.spec.ts similarity index 100% rename from packages/main/src/authentication.spec.ts rename to packages/homeserver/src/authentication.spec.ts diff --git a/packages/main/src/authentication.ts b/packages/homeserver/src/authentication.ts similarity index 100% rename from packages/main/src/authentication.ts rename to packages/homeserver/src/authentication.ts diff --git a/packages/main/src/binaryData.ts b/packages/homeserver/src/binaryData.ts similarity index 100% rename from packages/main/src/binaryData.ts rename to packages/homeserver/src/binaryData.ts diff --git a/packages/main/src/cache.ts b/packages/homeserver/src/cache.ts similarity index 100% rename from packages/main/src/cache.ts rename to packages/homeserver/src/cache.ts diff --git a/packages/main/src/dto.ts b/packages/homeserver/src/dto.ts similarity index 100% rename from packages/main/src/dto.ts rename to packages/homeserver/src/dto.ts diff --git a/packages/main/src/errors.ts b/packages/homeserver/src/errors.ts similarity index 100% rename from packages/main/src/errors.ts rename to packages/homeserver/src/errors.ts diff --git a/packages/main/src/events/eventBase.spec.ts b/packages/homeserver/src/events/eventBase.spec.ts similarity index 100% rename from packages/main/src/events/eventBase.spec.ts rename to packages/homeserver/src/events/eventBase.spec.ts diff --git a/packages/main/src/events/eventBase.ts b/packages/homeserver/src/events/eventBase.ts similarity index 100% rename from packages/main/src/events/eventBase.ts rename to packages/homeserver/src/events/eventBase.ts diff --git a/packages/main/src/events/m.room.create.spec.ts b/packages/homeserver/src/events/m.room.create.spec.ts similarity index 100% rename from packages/main/src/events/m.room.create.spec.ts rename to packages/homeserver/src/events/m.room.create.spec.ts diff --git a/packages/main/src/events/m.room.create.ts b/packages/homeserver/src/events/m.room.create.ts similarity index 100% rename from packages/main/src/events/m.room.create.ts rename to packages/homeserver/src/events/m.room.create.ts diff --git a/packages/main/src/events/m.room.guest_access.spec.ts b/packages/homeserver/src/events/m.room.guest_access.spec.ts similarity index 100% rename from packages/main/src/events/m.room.guest_access.spec.ts rename to packages/homeserver/src/events/m.room.guest_access.spec.ts diff --git a/packages/main/src/events/m.room.guest_access.ts b/packages/homeserver/src/events/m.room.guest_access.ts similarity index 100% rename from packages/main/src/events/m.room.guest_access.ts rename to packages/homeserver/src/events/m.room.guest_access.ts diff --git a/packages/main/src/events/m.room.history_visibility.spec.ts b/packages/homeserver/src/events/m.room.history_visibility.spec.ts similarity index 100% rename from packages/main/src/events/m.room.history_visibility.spec.ts rename to packages/homeserver/src/events/m.room.history_visibility.spec.ts diff --git a/packages/main/src/events/m.room.history_visibility.ts b/packages/homeserver/src/events/m.room.history_visibility.ts similarity index 100% rename from packages/main/src/events/m.room.history_visibility.ts rename to packages/homeserver/src/events/m.room.history_visibility.ts diff --git a/packages/main/src/events/m.room.join_rules.spec.ts b/packages/homeserver/src/events/m.room.join_rules.spec.ts similarity index 100% rename from packages/main/src/events/m.room.join_rules.spec.ts rename to packages/homeserver/src/events/m.room.join_rules.spec.ts diff --git a/packages/main/src/events/m.room.join_rules.ts b/packages/homeserver/src/events/m.room.join_rules.ts similarity index 100% rename from packages/main/src/events/m.room.join_rules.ts rename to packages/homeserver/src/events/m.room.join_rules.ts diff --git a/packages/main/src/events/m.room.member-invite.spec.ts b/packages/homeserver/src/events/m.room.member-invite.spec.ts similarity index 100% rename from packages/main/src/events/m.room.member-invite.spec.ts rename to packages/homeserver/src/events/m.room.member-invite.spec.ts diff --git a/packages/main/src/events/m.room.member.spec.ts b/packages/homeserver/src/events/m.room.member.spec.ts similarity index 100% rename from packages/main/src/events/m.room.member.spec.ts rename to packages/homeserver/src/events/m.room.member.spec.ts diff --git a/packages/main/src/events/m.room.member.ts b/packages/homeserver/src/events/m.room.member.ts similarity index 100% rename from packages/main/src/events/m.room.member.ts rename to packages/homeserver/src/events/m.room.member.ts diff --git a/packages/main/src/events/m.room.power_levels.spec.ts b/packages/homeserver/src/events/m.room.power_levels.spec.ts similarity index 100% rename from packages/main/src/events/m.room.power_levels.spec.ts rename to packages/homeserver/src/events/m.room.power_levels.spec.ts diff --git a/packages/main/src/events/m.room.power_levels.ts b/packages/homeserver/src/events/m.room.power_levels.ts similarity index 100% rename from packages/main/src/events/m.room.power_levels.ts rename to packages/homeserver/src/events/m.room.power_levels.ts diff --git a/packages/main/src/events/utils/createSignedEvent.spec.ts b/packages/homeserver/src/events/utils/createSignedEvent.spec.ts similarity index 100% rename from packages/main/src/events/utils/createSignedEvent.spec.ts rename to packages/homeserver/src/events/utils/createSignedEvent.spec.ts diff --git a/packages/main/src/events/utils/createSignedEvent.ts b/packages/homeserver/src/events/utils/createSignedEvent.ts similarity index 100% rename from packages/main/src/events/utils/createSignedEvent.ts rename to packages/homeserver/src/events/utils/createSignedEvent.ts diff --git a/packages/main/src/index.ts b/packages/homeserver/src/index.ts similarity index 61% rename from packages/main/src/index.ts rename to packages/homeserver/src/index.ts index d1a5ecf3..eef83309 100644 --- a/packages/main/src/index.ts +++ b/packages/homeserver/src/index.ts @@ -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) { @@ -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 }; diff --git a/packages/main/src/keys.ts b/packages/homeserver/src/keys.ts similarity index 100% rename from packages/main/src/keys.ts rename to packages/homeserver/src/keys.ts diff --git a/packages/main/src/makeRequest.ts b/packages/homeserver/src/makeRequest.ts similarity index 83% rename from packages/main/src/makeRequest.ts rename to packages/homeserver/src/makeRequest.ts index a8f03618..670f0d2b 100644 --- a/packages/main/src/makeRequest.ts +++ b/packages/homeserver/src/makeRequest.ts @@ -1,5 +1,6 @@ import { authorizationHeaders, computeHash } from "./authentication"; -import type { Config } from "./config"; +import type { SigningKey } from "./keys"; + import { signJson } from "./signJson"; export const makeRequest = async ({ @@ -7,28 +8,28 @@ export const makeRequest = async ({ domain, uri, options = {}, - config, + signingKey, + signingName, }: { method: string; domain: string; uri: string; options?: Record; - 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, @@ -53,18 +54,18 @@ export const makeUnsignedRequest = async ({ domain, uri, options = {}, - config, + signingKey, + signingName, }: { method: string; domain: string; uri: string; options?: Record; - config: Config; + signingKey: SigningKey; + signingName: string; }) => { - const signingKey = config.signingKey[0]; - const auth = await authorizationHeaders( - config.name, + signingName, signingKey, domain, method, diff --git a/packages/main/src/plugins/config.ts b/packages/homeserver/src/plugins/config.ts similarity index 50% rename from packages/main/src/plugins/config.ts rename to packages/homeserver/src/plugins/config.ts index b0195508..7922e778 100644 --- a/packages/main/src/plugins/config.ts +++ b/packages/homeserver/src/plugins/config.ts @@ -1,8 +1,16 @@ import Elysia from "elysia"; import type { InferContext } from "elysia"; +import type { SigningKey } from "../keys"; -import { config } from "../config"; +export interface Config { + path: string; + signingKeyPath: string; + port: number; + signingKey: SigningKey[]; + name: string; + version: string; +} -export const routerWithConfig = new Elysia().decorate("config", config); +export const routerWithConfig = new Elysia().decorate("config", {} as Config); export type Context = InferContext; diff --git a/packages/main/src/plugins/isConfigContext.ts b/packages/homeserver/src/plugins/isConfigContext.ts similarity index 100% rename from packages/main/src/plugins/isConfigContext.ts rename to packages/homeserver/src/plugins/isConfigContext.ts diff --git a/packages/main/src/plugins/isMongodbContext.ts b/packages/homeserver/src/plugins/isMongodbContext.ts similarity index 100% rename from packages/main/src/plugins/isMongodbContext.ts rename to packages/homeserver/src/plugins/isMongodbContext.ts diff --git a/packages/homeserver/src/plugins/mongodb.ts b/packages/homeserver/src/plugins/mongodb.ts new file mode 100644 index 00000000..656cd3fe --- /dev/null +++ b/packages/homeserver/src/plugins/mongodb.ts @@ -0,0 +1,70 @@ +import Elysia from "elysia"; +import type { InferContext } from "elysia"; +import { type Db, MongoClient } from "mongodb"; + +import { NotFoundError } from "elysia"; +import type { EventBase } from "../events/eventBase"; + +export const routerWithMongodb = (db: Db) => + new Elysia().decorate( + "mongo", + (() => { + const eventsCollection = db.collection("events"); + + const getLastEvent = async (roomId: string) => { + const events = await eventsCollection + .find({ "event.room_id": roomId }, { sort: { "event.depth": -1 } }) + .toArray(); + + if (events.length === 0) { + throw new NotFoundError(`No events found for room ${roomId}`); + } + + return events[0]; + }; + + const getAuthEvents = async (roomId: string) => { + return eventsCollection + .find( + { + "event.room_id": roomId, + $or: [ + { + "event.type": { + $in: [ + "m.room.create", + "m.room.power_levels", + "m.room.join_rules", + ], + }, + }, + { + // Lots of room members, when including the join ones it fails the auth check + "event.type": "m.room.member", + "event.content.membership": "invite", + }, + ], + }, + { + projection: { + _id: 1, + }, + }, + ) + .toArray(); + }; + + return { + eventsCollection, + getLastEvent, + getAuthEvents, + }; + })(), + ); + +export type Context = InferContext>; + +export type EventStore = { + _id: string; + event: EventBase; +}; diff --git a/packages/main/src/procedures/createRoom.spec.ts b/packages/homeserver/src/procedures/createRoom.spec.ts similarity index 100% rename from packages/main/src/procedures/createRoom.spec.ts rename to packages/homeserver/src/procedures/createRoom.spec.ts diff --git a/packages/main/src/procedures/createRoom.ts b/packages/homeserver/src/procedures/createRoom.ts similarity index 100% rename from packages/main/src/procedures/createRoom.ts rename to packages/homeserver/src/procedures/createRoom.ts diff --git a/packages/main/src/procedures/makeJoin.ts b/packages/homeserver/src/procedures/makeJoin.ts similarity index 100% rename from packages/main/src/procedures/makeJoin.ts rename to packages/homeserver/src/procedures/makeJoin.ts diff --git a/packages/main/src/pruneEventDict.spec.ts b/packages/homeserver/src/pruneEventDict.spec.ts similarity index 100% rename from packages/main/src/pruneEventDict.spec.ts rename to packages/homeserver/src/pruneEventDict.spec.ts diff --git a/packages/main/src/pruneEventDict.ts b/packages/homeserver/src/pruneEventDict.ts similarity index 100% rename from packages/main/src/pruneEventDict.ts rename to packages/homeserver/src/pruneEventDict.ts diff --git a/packages/main/src/routes/federation/getMissingEvents.ts b/packages/homeserver/src/routes/federation/getMissingEvents.ts similarity index 100% rename from packages/main/src/routes/federation/getMissingEvents.ts rename to packages/homeserver/src/routes/federation/getMissingEvents.ts diff --git a/packages/main/src/routes/federation/index.ts b/packages/homeserver/src/routes/federation/index.ts similarity index 100% rename from packages/main/src/routes/federation/index.ts rename to packages/homeserver/src/routes/federation/index.ts diff --git a/packages/main/src/routes/federation/invite.ts b/packages/homeserver/src/routes/federation/invite.ts similarity index 98% rename from packages/main/src/routes/federation/invite.ts rename to packages/homeserver/src/routes/federation/invite.ts index 9577d3f8..806b31bc 100644 --- a/packages/main/src/routes/federation/invite.ts +++ b/packages/homeserver/src/routes/federation/invite.ts @@ -38,7 +38,8 @@ 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, + signingKey: config.signingKey[0], + signingName: config.name, }); const responseMake = await response.json(); @@ -77,7 +78,8 @@ export const inviteEndpoint = new Elysia().put( options: { body: joinBody, }, - config, + signingKey: config.signingKey[0], + signingName: config.name, }); const responseBody = await responseSend.json(); diff --git a/packages/main/src/routes/federation/makeJoin.ts b/packages/homeserver/src/routes/federation/makeJoin.ts similarity index 100% rename from packages/main/src/routes/federation/makeJoin.ts rename to packages/homeserver/src/routes/federation/makeJoin.ts diff --git a/packages/main/src/routes/federation/query.spec.ts b/packages/homeserver/src/routes/federation/query.spec.ts similarity index 100% rename from packages/main/src/routes/federation/query.spec.ts rename to packages/homeserver/src/routes/federation/query.spec.ts diff --git a/packages/main/src/routes/federation/query.ts b/packages/homeserver/src/routes/federation/query.ts similarity index 100% rename from packages/main/src/routes/federation/query.ts rename to packages/homeserver/src/routes/federation/query.ts diff --git a/packages/main/src/routes/federation/sendJoin.ts b/packages/homeserver/src/routes/federation/sendJoin.ts similarity index 100% rename from packages/main/src/routes/federation/sendJoin.ts rename to packages/homeserver/src/routes/federation/sendJoin.ts diff --git a/packages/main/src/routes/federation/users.ts b/packages/homeserver/src/routes/federation/users.ts similarity index 100% rename from packages/main/src/routes/federation/users.ts rename to packages/homeserver/src/routes/federation/users.ts diff --git a/packages/main/src/routes/federation/version.ts b/packages/homeserver/src/routes/federation/version.ts similarity index 100% rename from packages/main/src/routes/federation/version.ts rename to packages/homeserver/src/routes/federation/version.ts diff --git a/packages/main/src/routes/key/server.spec.ts b/packages/homeserver/src/routes/key/server.spec.ts similarity index 98% rename from packages/main/src/routes/key/server.spec.ts rename to packages/homeserver/src/routes/key/server.spec.ts index f27398b7..0d865152 100644 --- a/packages/main/src/routes/key/server.spec.ts +++ b/packages/homeserver/src/routes/key/server.spec.ts @@ -2,7 +2,7 @@ import { expect, it } from "bun:test"; import nacl from "tweetnacl"; import { app } from "../../app"; import { fromBinaryData, toBinaryData } from "../../binaryData"; -import type { Config } from "../../config"; +import type { Config } from "../../../../../config"; import { EncryptionValidAlgorithm } from "../../signJson"; import Elysia from "elysia"; import { generateKeyPairsFromString } from "../../keys"; diff --git a/packages/main/src/routes/key/server.ts b/packages/homeserver/src/routes/key/server.ts similarity index 100% rename from packages/main/src/routes/key/server.ts rename to packages/homeserver/src/routes/key/server.ts diff --git a/packages/main/src/signEvent.ts b/packages/homeserver/src/signEvent.ts similarity index 100% rename from packages/main/src/signEvent.ts rename to packages/homeserver/src/signEvent.ts diff --git a/packages/main/src/signJson.spec.ts b/packages/homeserver/src/signJson.spec.ts similarity index 100% rename from packages/main/src/signJson.spec.ts rename to packages/homeserver/src/signJson.spec.ts diff --git a/packages/main/src/signJson.ts b/packages/homeserver/src/signJson.ts similarity index 100% rename from packages/main/src/signJson.ts rename to packages/homeserver/src/signJson.ts diff --git a/packages/homeserver/tsconfig.json b/packages/homeserver/tsconfig.json new file mode 100644 index 00000000..4b712b47 --- /dev/null +++ b/packages/homeserver/tsconfig.json @@ -0,0 +1,105 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + "composite": true /* Enable constraints that allow a TypeScript project to be used with project references. */, + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "ES2021" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "ES2022" /* Specify what module code is generated. */, + // "rootDir": "./", /* Specify the root folder within your source files. */ + "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */, + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + "types": [ + "bun-types" + ] /* Specify type package names to be included without being referenced in a source file. */, + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + "declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */, + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + "sourceMap": true /* Create source map files for emitted JavaScript files. */, + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + // "outDir": "./", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, + + /* Type Checking */ + "strict": true /* Enable all strict type-checking options. */, + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + "useUnknownInCatchVariables": true /* Default catch clause variables as 'unknown' instead of 'any'. */, + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + "noUnusedParameters": true /* Raise an error when a function parameter isn't read. */, + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + "noImplicitReturns": false /* Enable error reporting for codepaths that do not explicitly return in a function. */, + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + "allowUnusedLabels": false /* Disable error reporting for unused labels. */, + "allowUnreachableCode": false /* Disable error reporting for unreachable code. */, + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + } +} diff --git a/packages/main/src/mongodb.ts b/packages/main/src/mongodb.ts deleted file mode 100644 index 230095a3..00000000 --- a/packages/main/src/mongodb.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { MongoClient } from "mongodb"; -import type { EventBase } from "./events/eventBase"; -import { NotFoundError } from "elysia"; - -const MONGODB_URI = process.env.MONGODB_URI; -if (!MONGODB_URI) { - throw new Error( - "Please define the MONGODB_URI environment variable inside .env", - ); -} -const client: MongoClient = await MongoClient.connect(MONGODB_URI); - -const db = client.db(MONGODB_URI.split("/").pop()); - -export type EventStore = { - _id: string; - event: EventBase; -}; - -const eventsCollection = db.collection("events"); - -export const getLastEvent = async (roomId: string) => { - const events = await eventsCollection - .find({ "event.room_id": roomId }, { sort: { "event.depth": -1 } }) - .toArray(); - - if (events.length === 0) { - throw new NotFoundError(`No events found for room ${roomId}`); - } - - return events[0]; -}; - -export const getAuthEvents = async (roomId: string) => { - return eventsCollection - .find( - { - "event.room_id": roomId, - $or: [ - { - "event.type": { - $in: [ - "m.room.create", - "m.room.power_levels", - "m.room.join_rules", - ], - }, - }, - { - // Lots of room members, when including the join ones it fails the auth check - "event.type": "m.room.member", - "event.content.membership": "invite", - }, - ], - }, - { - projection: { - _id: 1, - }, - }, - ) - .toArray(); -}; diff --git a/packages/main/src/plugins/mongodb.ts b/packages/main/src/plugins/mongodb.ts deleted file mode 100644 index f9080753..00000000 --- a/packages/main/src/plugins/mongodb.ts +++ /dev/null @@ -1,8 +0,0 @@ -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;