Skip to content

Commit

Permalink
type request server to server
Browse files Browse the repository at this point in the history
  • Loading branch information
ggazzo committed Dec 9, 2024
1 parent 2648906 commit e8248eb
Show file tree
Hide file tree
Showing 6 changed files with 92 additions and 27 deletions.
7 changes: 2 additions & 5 deletions packages/fake/src/room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ export const fakeEndpoints = new Elysia({ prefix: "/fake" })
console.log("invite roomId ->", roomId);
console.log("invite eventId ->", inviteEventId);

const response = await makeUnsignedRequest({
const responseMake = await makeUnsignedRequest({
method: "PUT",
domain: username.split(":").pop() as string,
uri: `/_matrix/federation/v2/invite/${roomId}/${inviteEventId}`,
Expand All @@ -214,8 +214,6 @@ export const fakeEndpoints = new Elysia({ prefix: "/fake" })
signingName: config.name,
});

console.log(response.status);
const responseMake = await response.json();
const responseEventId = generateId(responseMake.event);
console.log("invite response responseEventId ->", responseEventId);
console.log("invite response ->", responseMake);
Expand Down Expand Up @@ -339,7 +337,7 @@ export const fakeEndpoints = new Elysia({ prefix: "/fake" })
};
console.log("payload ->", payload);

const response = await makeUnsignedRequest({
const responseMake = await makeUnsignedRequest({
method: "PUT",
domain: target,
uri: `/_matrix/federation/v1/send/${Date.now()}`,
Expand All @@ -350,7 +348,6 @@ export const fakeEndpoints = new Elysia({ prefix: "/fake" })
signingName: config.name,
});

const responseMake = await response.json();
console.log("response ->", responseMake);

return responseMake;
Expand Down
6 changes: 6 additions & 0 deletions packages/homeserver/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ import { Elysia } from "elysia";
import { BadJSONError, MatrixError } from "./errors";
import federationEndpoints from "./routes/federation";
import { keyV2Endpoints } from "./routes/key/server";
import type {
ElysiaRoutes,
ElysiaRoutesResponsesByEndpoint,
} from "./extractRouteTypings";

export const app = new Elysia({
handler: {
Expand Down Expand Up @@ -38,3 +42,5 @@ export const app = new Elysia({
};
}
});

export type HomeServerRoutes = ElysiaRoutes<typeof app>;
32 changes: 32 additions & 0 deletions packages/homeserver/src/extractRouteTypings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type Elysia from "elysia";

type ExtractElysiaRoutes<T> = T extends Elysia<any, any, any, any, any, infer S>
? S
: never;

type ConcatRoutes<
R extends Record<string, any> = Record<string, any>,
P extends string = "",
K extends keyof R = keyof R,
> = K extends string
? R[K] extends { response: infer G }
? { method: Uppercase<K>; path: `${P}`; response: G }
: K extends `:${string}`
? ConcatRoutes<R[K], `${P}/${string}`, keyof R[K]>
: ConcatRoutes<R[K], `${P}/${K}`, keyof R[K]>
: K;

export type ElysiaRoutes<T extends Elysia<any, any, any, any, any, any>> =
ConcatRoutes<ExtractElysiaRoutes<T>>;

// organize by method
export type ElysiaRoutesResponsesByEndpoint<T extends ElysiaRoutes<any>> =
T extends {
response: infer R;
method: infer M;
path: infer P;
}
? {
[K in T["method"]]: T["response"];
}
: never;
57 changes: 46 additions & 11 deletions packages/homeserver/src/makeRequest.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,45 @@
import type { HomeServerRoutes } from "./app";
import { authorizationHeaders, computeHash } from "./authentication";
import type { SigningKey } from "./keys";

import { signJson } from "./signJson";

export const makeRequest = async ({
type getAllResponsesByMethod<
T extends HomeServerRoutes,
M extends HomeServerRoutes["method"],
> = T extends { method: M } ? T : never;

type getAllResponsesByPath<
T extends HomeServerRoutes,
M extends HomeServerRoutes["method"],
P extends HomeServerRoutes["path"],
> = T extends { method: M; path: P } ? T : never;

export const makeRequest = async <
M extends HomeServerRoutes["method"],
U extends getAllResponsesByMethod<HomeServerRoutes, M>["path"],
R extends getAllResponsesByPath<HomeServerRoutes, M, U>["response"][200],
>({
method,
domain,
uri,
options = {},
signingKey,
signingName,
queryString,
}: {
method: string;
method: M;
domain: string;
uri: string;
uri: U;
options?: Record<string, any>;
signingKey: SigningKey;
signingName: string;
queryString?: string;
}) => {
const url = new URL(`https://${domain}${uri}`);
if (queryString) {
url.search = queryString;
}
const body =
options.body &&
(await signJson(
Expand All @@ -26,7 +48,7 @@ export const makeRequest = async ({
signingName,
));

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

const auth = await authorizationHeaders(
signingName,
Expand All @@ -39,30 +61,39 @@ export const makeRequest = async ({

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

return fetch(`https://${domain}${uri}`, {
const response = await fetch(url.toString(), {
...options,
...(body && { body: JSON.stringify(body) }),
method,
...(queryString && { search: queryString }),
headers: {
Authorization: auth,
},
});

return response.json() as Promise<R>;
};

export const makeUnsignedRequest = async ({
export const makeUnsignedRequest = async <
M extends HomeServerRoutes["method"],
U extends getAllResponsesByMethod<HomeServerRoutes, M>["path"],
R extends getAllResponsesByPath<HomeServerRoutes, M, U>["response"][200],
>({
method,
domain,
uri,
options = {},
signingKey,
signingName,
queryString,
}: {
method: string;
method: M;
domain: string;
uri: string;
uri: U;
options?: Record<string, any>;
signingKey: SigningKey;
signingName: string;
queryString?: string;
}) => {
const auth = await authorizationHeaders(
signingName,
Expand All @@ -73,14 +104,18 @@ export const makeUnsignedRequest = async ({
options.body,
);

console.log("auth ->", auth);

return fetch(`https://${domain}${uri}`, {
const url = new URL(`https://${domain}${uri}`);
if (queryString) {
url.search = queryString;
}
const response = await fetch(url.toString(), {
...options,
...(options.body && { body: JSON.stringify(options.body) }),
method,
headers: {
Authorization: auth,
},
});

return response.json() as Promise<R>;
};
15 changes: 5 additions & 10 deletions packages/homeserver/src/routes/federation/invite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,21 +34,16 @@ export const inviteEndpoint = new Elysia().put(
setTimeout(async () => {
const { event } = body;

const response = await makeRequest({
const responseMake = await makeRequest({
method: "GET",
domain: event.origin,
uri: `/_matrix/federation/v1/make_join/${params.roomId}/${event.state_key}?ver=10`,
uri: `/_matrix/federation/v1/make_join/${params.roomId}/${event.state_key}`,
signingKey: config.signingKey[0],
signingName: config.name,
});

const responseMake = await response.json();
console.log("make_join response ->", responseMake);

if (responseMake.errcode) {
return;
}

// const joinBody = {
// type: 'm.room.member',
// origin: config.name,
Expand All @@ -71,18 +66,18 @@ export const inviteEndpoint = new Elysia().put(

console.log("send_join payload ->", joinBody);

const responseSend = await makeRequest({
const responseBody = await makeRequest({
method: "PUT",
domain: event.origin,
uri: `/_matrix/federation/v2/send_join/${params.roomId}/${event.state_key}?omit_members=false`,
uri: `/_matrix/federation/v2/send_join/${params.roomId}/${event.state_key}`,
options: {
body: joinBody,
},
signingKey: config.signingKey[0],
signingName: config.name,
queryString: "omit_members=false",
});

const responseBody = await responseSend.json();
console.log("send_join response ->", { responseBody });

if (responseBody.event) {
Expand Down
2 changes: 1 addition & 1 deletion packages/homeserver/src/routes/federation/makeJoin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { makeJoinEventBuilder } from "../../procedures/makeJoin";
// "method":"GET",
// "url":"http://rc1:443/_matrix/federation/v1/make_join/%21kwkcWPpOXEJvlcollu%3Arc1/%40admin%3Ahs1?ver=1&ver=2&ver=3&ver=4&ver=5&ver=6&ver=7&ver=8&ver=9&ver=10&ver=11&ver=org.matrix.msc3757.10&ver=org.matrix.msc3757.11",

export const makeJoinEndpoint = new Elysia().get(
export const makeJoinEndpoint = new Elysia().get("", console.log).get(
"/make_join/:roomId/:userId",
async ({ params, query, ...context }) => {
if (!isMongodbContext(context)) {
Expand Down

0 comments on commit e8248eb

Please sign in to comment.