This repository has been archived on 2022-08-19. You can view files and clone it, but cannot push or open issues or pull requests.
hydrogen-web/src/matrix/net/HomeServerApi.ts

294 lines
13 KiB
TypeScript
Raw Normal View History

2020-08-05 22:08:55 +05:30
/*
Copyright 2020 Bruno Windels <bruno@windels.cloud>
Copyright 2020 The Matrix.org Foundation C.I.C.
2020-08-05 22:08:55 +05:30
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
2021-11-21 21:12:28 +05:30
import {encodeQueryParams, encodeBody} from "./common";
2021-11-21 21:28:16 +05:30
import {HomeServerRequest} from "./HomeServerRequest";
2021-11-24 21:05:01 +05:30
import type {IHomeServerRequest} from "./HomeServerRequest";
import type {Reconnector} from "./Reconnector";
2021-12-01 11:42:24 +05:30
import type {EncodedBody} from "./common";
2021-11-23 19:37:25 +05:30
import type {IRequestOptions, RequestFunction} from "../../platform/types/types";
2021-12-03 11:48:01 +05:30
import type {ILogItem} from "../../logging/types";
type RequestMethod = "POST" | "GET" | "PUT";
2020-11-11 15:15:23 +05:30
2021-10-26 22:17:46 +05:30
const CS_R0_PREFIX = "/_matrix/client/r0";
2021-10-27 18:38:53 +05:30
const DEHYDRATION_PREFIX = "/_matrix/client/unstable/org.matrix.msc2697.v2";
2021-10-26 22:17:46 +05:30
type Options = {
2021-11-24 13:05:13 +05:30
homeserver: string;
accessToken: string;
request: RequestFunction;
reconnector: Reconnector;
};
export class HomeServerApi {
private readonly _homeserver: string;
private readonly _accessToken: string;
private readonly _requestFn: RequestFunction;
private readonly _reconnector: Reconnector;
2021-12-01 11:21:58 +05:30
constructor({homeserver, accessToken, request, reconnector}: Options) {
2019-03-09 00:33:47 +05:30
// store these both in a closure somehow so it's harder to get at in case of XSS?
// one could change the homeserver as well so the token gets sent there, so both must be protected from read/write
this._homeserver = homeserver;
2019-06-27 02:01:36 +05:30
this._accessToken = accessToken;
2019-12-23 18:58:27 +05:30
this._requestFn = request;
2020-04-05 18:41:15 +05:30
this._reconnector = reconnector;
2019-06-27 02:01:36 +05:30
}
2018-12-21 19:05:24 +05:30
2021-11-23 19:31:13 +05:30
private _url(csPath: string, prefix: string = CS_R0_PREFIX): string {
2021-10-26 22:17:46 +05:30
return this._homeserver + prefix + csPath;
2019-06-27 02:01:36 +05:30
}
2018-12-21 19:05:24 +05:30
2021-11-24 21:05:01 +05:30
private _baseRequest(method: RequestMethod, url: string, queryParams?: Record<string, any>, body?: Record<string, any>, options?: IRequestOptions, accessToken?: string): IHomeServerRequest {
const queryString = encodeQueryParams(queryParams);
2020-03-31 03:26:03 +05:30
url = `${url}?${queryString}`;
2021-12-03 11:48:01 +05:30
let log: ILogItem | undefined;
2021-02-12 23:05:33 +05:30
if (options?.log) {
const parent = options?.log;
log = parent.child({
2021-02-17 23:15:12 +05:30
t: "network",
2021-02-12 23:05:33 +05:30
url,
method,
}, parent.level.Info);
}
2021-12-01 11:42:24 +05:30
let encodedBody: EncodedBody["body"];
const headers: Map<string, string | number> = new Map();
if (accessToken) {
headers.set("Authorization", `Bearer ${accessToken}`);
2019-06-27 02:01:36 +05:30
}
headers.set("Accept", "application/json");
2019-06-27 02:01:36 +05:30
if (body) {
2020-11-11 15:15:23 +05:30
const encoded = encodeBody(body);
headers.set("Content-Type", encoded.mimeType);
encodedBody = encoded.body;
2019-06-27 02:01:36 +05:30
}
2021-02-12 23:05:33 +05:30
2019-12-23 18:58:27 +05:30
const requestResult = this._requestFn(url, {
2019-06-27 02:01:36 +05:30
method,
headers,
2020-11-11 15:15:23 +05:30
body: encodedBody,
timeout: options?.timeout,
2020-11-16 15:15:46 +05:30
uploadProgress: options?.uploadProgress,
2020-11-11 15:15:23 +05:30
format: "json" // response format
2019-06-27 02:01:36 +05:30
});
2020-04-05 18:41:15 +05:30
const hsRequest = new HomeServerRequest(method, url, requestResult, log);
2020-04-05 18:41:15 +05:30
if (this._reconnector) {
hsRequest.response().catch(err => {
// Some endpoints such as /sync legitimately time-out
// (which is also reported as a ConnectionError) and will re-attempt,
// but spinning up the reconnector in this case is ok,
// as all code ran on session and sync start should be reentrant
if (err.name === "ConnectionError") {
2020-04-05 18:41:15 +05:30
this._reconnector.onRequestFailed(this);
}
});
}
return hsRequest;
2019-06-27 02:01:36 +05:30
}
2019-02-05 03:56:24 +05:30
2021-11-24 21:05:01 +05:30
private _unauthedRequest(method: RequestMethod, url: string, queryParams?: Record<string, any>, body?: Record<string, any>, options?: IRequestOptions): IHomeServerRequest {
return this._baseRequest(method, url, queryParams, body, options);
}
2021-11-24 21:05:01 +05:30
private _authedRequest(method: RequestMethod, url: string, queryParams?: Record<string, any>, body?: Record<string, any>, options?: IRequestOptions): IHomeServerRequest {
return this._baseRequest(method, url, queryParams, body, options, this._accessToken);
}
2021-11-24 21:05:01 +05:30
private _post(csPath: string, queryParams: Record<string, any>, body: Record<string, any>, options?: IRequestOptions): IHomeServerRequest {
2021-10-26 22:17:46 +05:30
return this._authedRequest("POST", this._url(csPath, options?.prefix || CS_R0_PREFIX), queryParams, body, options);
2019-06-27 02:01:36 +05:30
}
2019-02-05 03:56:24 +05:30
2021-11-24 21:05:01 +05:30
private _put(csPath: string, queryParams: Record<string, any>, body?: Record<string, any>, options?: IRequestOptions): IHomeServerRequest {
2021-10-26 22:17:46 +05:30
return this._authedRequest("PUT", this._url(csPath, options?.prefix || CS_R0_PREFIX), queryParams, body, options);
2019-07-27 01:33:57 +05:30
}
2021-11-24 21:05:01 +05:30
private _get(csPath: string, queryParams?: Record<string, any>, body?: Record<string, any>, options?: IRequestOptions): IHomeServerRequest {
2021-10-26 22:17:46 +05:30
return this._authedRequest("GET", this._url(csPath, options?.prefix || CS_R0_PREFIX), queryParams, body, options);
2019-06-27 02:01:36 +05:30
}
2018-12-21 19:05:24 +05:30
2021-11-24 21:05:01 +05:30
sync(since: string, filter: string, timeout: number, options?: IRequestOptions): IHomeServerRequest {
return this._get("/sync", {since, timeout, filter}, undefined, options);
2019-06-27 02:01:36 +05:30
}
2019-02-05 03:56:24 +05:30
2021-12-07 12:18:51 +05:30
context(roomId: string, eventId: string, limit: number, filter: string): IHomeServerRequest {
return this._get(`/rooms/${encodeURIComponent(roomId)}/context/${encodeURIComponent(eventId)}`, {filter, limit});
2021-12-06 11:36:45 +05:30
}
2019-03-09 05:11:06 +05:30
// params is from, dir and optionally to, limit, filter.
2021-11-24 21:05:01 +05:30
messages(roomId: string, params: Record<string, any>, options?: IRequestOptions): IHomeServerRequest {
return this._get(`/rooms/${encodeURIComponent(roomId)}/messages`, params, undefined, options);
2019-03-09 05:11:06 +05:30
}
2020-08-19 19:41:33 +05:30
// params is at, membership and not_membership
2021-11-24 21:05:01 +05:30
members(roomId: string, params: Record<string, any>, options?: IRequestOptions): IHomeServerRequest {
return this._get(`/rooms/${encodeURIComponent(roomId)}/members`, params, undefined, options);
2020-08-19 19:41:33 +05:30
}
2021-11-24 21:05:01 +05:30
send(roomId: string, eventType: string, txnId: string, content: Record<string, any>, options?: IRequestOptions): IHomeServerRequest {
2020-04-05 18:41:15 +05:30
return this._put(`/rooms/${encodeURIComponent(roomId)}/send/${encodeURIComponent(eventType)}/${encodeURIComponent(txnId)}`, {}, content, options);
2019-07-27 01:33:57 +05:30
}
2021-11-24 21:05:01 +05:30
redact(roomId: string, eventId: string, txnId: string, content: Record<string, any>, options?: IRequestOptions): IHomeServerRequest {
return this._put(`/rooms/${encodeURIComponent(roomId)}/redact/${encodeURIComponent(eventId)}/${encodeURIComponent(txnId)}`, {}, content, options);
}
2021-11-24 21:05:01 +05:30
receipt(roomId: string, receiptType: string, eventId: string, options?: IRequestOptions): IHomeServerRequest {
return this._post(`/rooms/${encodeURIComponent(roomId)}/receipt/${encodeURIComponent(receiptType)}/${encodeURIComponent(eventId)}`,
{}, {}, options);
}
2021-11-24 21:05:01 +05:30
state(roomId: string, eventType: string, stateKey: string, options?: IRequestOptions): IHomeServerRequest {
return this._get(`/rooms/${encodeURIComponent(roomId)}/state/${encodeURIComponent(eventType)}/${encodeURIComponent(stateKey)}`, {}, undefined, options);
}
2021-11-24 21:05:01 +05:30
getLoginFlows(): IHomeServerRequest {
return this._unauthedRequest("GET", this._url("/login"));
}
2021-11-24 21:05:01 +05:30
passwordLogin(username: string, password: string, initialDeviceDisplayName: string, options?: IRequestOptions): IHomeServerRequest {
return this._unauthedRequest("POST", this._url("/login"), undefined, {
2019-02-05 03:56:24 +05:30
"type": "m.login.password",
"identifier": {
"type": "m.id.user",
"user": username
},
"password": password,
"initial_device_display_name": initialDeviceDisplayName
2020-04-05 18:41:15 +05:30
}, options);
2019-06-27 02:01:36 +05:30
}
2019-10-12 23:54:09 +05:30
2021-11-24 21:05:01 +05:30
tokenLogin(loginToken: string, txnId: string, initialDeviceDisplayName: string, options?: IRequestOptions): IHomeServerRequest {
return this._unauthedRequest("POST", this._url("/login"), undefined, {
"type": "m.login.token",
"identifier": {
"type": "m.id.user",
},
"token": loginToken,
"txn_id": txnId,
"initial_device_display_name": initialDeviceDisplayName
}, options);
}
2021-11-24 21:05:01 +05:30
createFilter(userId: string, filter: Record<string, any>, options?: IRequestOptions): IHomeServerRequest {
return this._post(`/user/${encodeURIComponent(userId)}/filter`, {}, filter, options);
2019-10-12 23:54:09 +05:30
}
2020-03-31 03:26:03 +05:30
2021-11-24 21:05:01 +05:30
versions(options?: IRequestOptions): IHomeServerRequest {
return this._unauthedRequest("GET", `${this._homeserver}/_matrix/client/versions`, undefined, undefined, options);
2020-03-31 03:26:03 +05:30
}
2020-05-09 23:32:08 +05:30
2021-11-24 21:05:01 +05:30
uploadKeys(dehydratedDeviceId: string, payload: Record<string, any>, options?: IRequestOptions): IHomeServerRequest {
2021-10-26 22:17:46 +05:30
let path = "/keys/upload";
if (dehydratedDeviceId) {
path = path + `/${encodeURIComponent(dehydratedDeviceId)}`;
}
return this._post(path, {}, payload, options);
2020-08-27 22:43:24 +05:30
}
2021-11-24 21:05:01 +05:30
queryKeys(queryRequest: Record<string, any>, options?: IRequestOptions): IHomeServerRequest {
return this._post("/keys/query", {}, queryRequest, options);
2020-08-31 17:54:09 +05:30
}
2021-11-24 21:05:01 +05:30
claimKeys(payload: Record<string, any>, options?: IRequestOptions): IHomeServerRequest {
return this._post("/keys/claim", {}, payload, options);
2020-09-03 19:03:23 +05:30
}
2021-11-24 21:05:01 +05:30
sendToDevice(type: string, payload: Record<string, any>, txnId: string, options?: IRequestOptions): IHomeServerRequest {
return this._put(`/sendToDevice/${encodeURIComponent(type)}/${encodeURIComponent(txnId)}`, {}, payload, options);
2020-09-03 19:06:17 +05:30
}
2020-09-17 17:49:57 +05:30
2021-11-24 21:05:01 +05:30
roomKeysVersion(version?: string, options?: IRequestOptions): IHomeServerRequest {
2020-09-17 21:27:12 +05:30
let versionPart = "";
if (version) {
versionPart = `/${encodeURIComponent(version)}`;
2020-09-17 17:49:57 +05:30
}
return this._get(`/room_keys/version${versionPart}`, undefined, undefined, options);
2020-09-17 17:49:57 +05:30
}
2021-11-24 21:05:01 +05:30
roomKeyForRoomAndSession(version: string, roomId: string, sessionId: string, options?: IRequestOptions): IHomeServerRequest {
return this._get(`/room_keys/keys/${encodeURIComponent(roomId)}/${encodeURIComponent(sessionId)}`, {version}, undefined, options);
2020-09-17 17:49:57 +05:30
}
2021-11-24 21:05:01 +05:30
uploadAttachment(blob: Blob, filename: string, options?: IRequestOptions): IHomeServerRequest {
return this._authedRequest("POST", `${this._homeserver}/_matrix/media/r0/upload`, {filename}, blob, options);
}
2021-11-24 21:05:01 +05:30
setPusher(pusher: Record<string, any>, options?: IRequestOptions): IHomeServerRequest {
return this._post("/pushers/set", {}, pusher, options);
}
2021-11-24 21:05:01 +05:30
getPushers(options?: IRequestOptions): IHomeServerRequest {
return this._get("/pushers", undefined, undefined, options);
}
2021-11-24 21:05:01 +05:30
join(roomId: string, options?: IRequestOptions): IHomeServerRequest {
return this._post(`/rooms/${encodeURIComponent(roomId)}/join`, {}, {}, options);
}
2021-11-24 21:05:01 +05:30
joinIdOrAlias(roomIdOrAlias: string, options?: IRequestOptions): IHomeServerRequest {
return this._post(`/join/${encodeURIComponent(roomIdOrAlias)}`, {}, {}, options);
2021-05-18 14:35:31 +05:30
}
2021-11-24 21:05:01 +05:30
leave(roomId: string, options?: IRequestOptions): IHomeServerRequest {
return this._post(`/rooms/${encodeURIComponent(roomId)}/leave`, {}, {}, options);
}
2021-05-12 19:08:54 +05:30
2021-11-24 21:05:01 +05:30
forget(roomId: string, options?: IRequestOptions): IHomeServerRequest {
return this._post(`/rooms/${encodeURIComponent(roomId)}/forget`, {}, {}, options);
2021-05-12 19:08:54 +05:30
}
2021-10-26 16:19:31 +05:30
2021-11-24 21:05:01 +05:30
logout(options?: IRequestOptions): IHomeServerRequest {
return this._post(`/logout`, {}, {}, options);
2021-10-26 16:19:31 +05:30
}
2021-10-26 22:17:46 +05:30
2021-11-24 21:05:01 +05:30
getDehydratedDevice(options: IRequestOptions): IHomeServerRequest {
2021-10-26 22:17:46 +05:30
options.prefix = DEHYDRATION_PREFIX;
return this._get(`/dehydrated_device`, undefined, undefined, options);
2021-10-26 22:17:46 +05:30
}
2021-11-24 21:05:01 +05:30
createDehydratedDevice(payload: Record<string, any>, options: IRequestOptions): IHomeServerRequest {
2021-10-26 22:17:46 +05:30
options.prefix = DEHYDRATION_PREFIX;
return this._put(`/dehydrated_device`, {}, payload, options);
2021-10-26 22:17:46 +05:30
}
2021-11-24 21:05:01 +05:30
claimDehydratedDevice(deviceId: string, options: IRequestOptions): IHomeServerRequest {
2021-10-26 22:17:46 +05:30
options.prefix = DEHYDRATION_PREFIX;
return this._post(`/dehydrated_device/claim`, {}, {device_id: deviceId}, options);
2021-10-26 22:17:46 +05:30
}
2019-03-08 16:56:59 +05:30
}
2020-04-23 00:17:31 +05:30
import {Request as MockRequest} from "../../mocks/Request.js";
2020-04-23 00:17:31 +05:30
export function tests() {
2020-04-23 00:17:31 +05:30
return {
"superficial happy path for GET": async assert => {
// @ts-ignore
2020-04-23 00:17:31 +05:30
const hsApi = new HomeServerApi({
request: () => new MockRequest().respond(200, 42),
homeserver: "https://hs.tld",
2020-04-23 00:17:31 +05:30
});
2021-11-23 19:31:13 +05:30
// @ts-ignore
2021-11-24 12:59:10 +05:30
const result = await hsApi._get("foo").response();
2020-04-23 00:17:31 +05:30
assert.strictEqual(result, 42);
}
}
}