feat: complete Ancestor quote bot with production-ready Docker support

This commit is contained in:
unfunny
2026-09-13 14:14:38 -04:00
parent f2016da05a
commit fe7351a7dc
1145 changed files with 30890 additions and 97684 deletions

View File

@@ -1,5 +1,17 @@
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.FetchHttpApi = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _utils = require("../utils");
var _method = require("./method");
var _errors = require("./errors");
var _interface = require("./interface");
var _utils2 = require("./utils");
var _logger = require("../logger");
/*
Copyright 2022 The Matrix.org Foundation C.I.C.
@@ -20,24 +32,15 @@ limitations under the License.
* This is an internal module. See {@link MatrixHttpApi} for the public class.
*/
import { checkObjectHasKeys, deepCopy, encodeParams } from "../utils.js";
import { Method } from "./method.js";
import { ConnectionError, MatrixError, TokenRefreshError } from "./errors.js";
import { HttpApiEvent } from "./interface.js";
import { anySignal, parseErrorResponse, timeoutSignal } from "./utils.js";
import { TokenRefresher, TokenRefreshOutcome } from "./refresh.js";
export class FetchHttpApi {
class FetchHttpApi {
constructor(eventEmitter, opts) {
_defineProperty(this, "abortController", new AbortController());
_defineProperty(this, "tokenRefresher", void 0);
var _opts$useAuthorizatio;
this.eventEmitter = eventEmitter;
this.opts = opts;
checkObjectHasKeys(opts, ["baseUrl", "prefix"]);
if (!opts.onlyData) {
throw new Error("Constructing FetchHttpApi without `onlyData=true` is no longer supported.");
}
opts.useAuthorizationHeader = opts.useAuthorizationHeader ?? true;
this.tokenRefresher = new TokenRefresher(opts);
(0, _defineProperty2.default)(this, "abortController", new AbortController());
(0, _utils.checkObjectHasKeys)(opts, ["baseUrl", "prefix"]);
opts.onlyData = !!opts.onlyData;
opts.useAuthorizationHeader = (_opts$useAuthorizatio = opts.useAuthorizationHeader) !== null && _opts$useAuthorizatio !== void 0 ? _opts$useAuthorizatio : true;
}
abort() {
this.abortController.abort();
@@ -47,7 +50,7 @@ export class FetchHttpApi {
if (this.opts.fetchFn) {
return this.opts.fetchFn(resource, options);
}
return globalThis.fetch(resource, options);
return global.fetch(resource, options);
}
/**
@@ -63,7 +66,7 @@ export class FetchHttpApi {
}
let queryParams = undefined;
let body = undefined;
if (method === Method.Get) {
if (method === _method.Method.Get) {
queryParams = params;
} else {
body = params;
@@ -90,65 +93,50 @@ export class FetchHttpApi {
*
* @param body - The HTTP JSON body.
*
* @param paramOpts - additional options.
* When `paramOpts.doNotAttemptTokenRefresh` is true, token refresh will not be attempted
* when an expired token is encountered. Used to only attempt token refresh once.
* @param opts - additional options. If a number is specified,
* this is treated as `opts.localTimeoutMs`.
*
* @returns The parsed response.
* @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.
* @returns Promise which resolves to
* ```
* {
* data: {Object},
* headers: {Object},
* code: {Number},
* }
* ```
* If `onlyData` is set, this will resolve to the `data` object only.
* @returns Rejects with an error if a problem occurred.
* This includes network problems and Matrix-specific error JSON.
*/
authedRequest(method, path, queryParams = {}, body, paramOpts = {}) {
return this.doAuthedRequest(1, method, path, queryParams, body, paramOpts);
}
// Wrapper around public method authedRequest to allow for tracking retry attempt counts
async doAuthedRequest(attempt, method, path, queryParams, body, paramOpts = {}) {
// avoid mutating paramOpts so they can be used on retry
const opts = deepCopy(paramOpts);
// we have to manually copy the abortSignal over as it is not a plain object
opts.abortSignal = paramOpts.abortSignal;
// Take a snapshot of the current token state before we start the request so we can reference it if we error
const requestSnapshot = await this.tokenRefresher.prepareForRequest();
if (requestSnapshot.accessToken) {
authedRequest(method, path, queryParams, body, opts = {}) {
if (!queryParams) queryParams = {};
if (this.opts.accessToken) {
if (this.opts.useAuthorizationHeader) {
if (!opts.headers) {
opts.headers = {};
}
if (!opts.headers.Authorization) {
opts.headers.Authorization = `Bearer ${requestSnapshot.accessToken}`;
opts.headers.Authorization = "Bearer " + this.opts.accessToken;
}
if (queryParams.access_token) {
delete queryParams.access_token;
}
} else if (!queryParams.access_token) {
queryParams.access_token = requestSnapshot.accessToken;
queryParams.access_token = this.opts.accessToken;
}
}
try {
const response = await this.request(method, path, queryParams, body, opts);
return response;
} catch (error) {
if (!(error instanceof MatrixError)) {
throw error;
const requestPromise = this.request(method, path, queryParams, body, opts);
requestPromise.catch(err => {
if (err.errcode == "M_UNKNOWN_TOKEN" && !(opts !== null && opts !== void 0 && opts.inhibitLogoutEmit)) {
this.eventEmitter.emit(_interface.HttpApiEvent.SessionLoggedOut, err);
} else if (err.errcode == "M_CONSENT_NOT_GIVEN") {
this.eventEmitter.emit(_interface.HttpApiEvent.NoConsent, err.message, err.data.consent_uri);
}
if (error.errcode === "M_UNKNOWN_TOKEN") {
const outcome = await this.tokenRefresher.handleUnknownToken(requestSnapshot, attempt);
if (outcome === TokenRefreshOutcome.Success) {
// if we got a new token retry the request
return this.doAuthedRequest(attempt + 1, method, path, queryParams, body, paramOpts);
}
if (outcome === TokenRefreshOutcome.Failure) {
throw new TokenRefreshError(error);
}
if (!opts?.inhibitLogoutEmit) {
this.eventEmitter.emit(HttpApiEvent.SessionLoggedOut, error);
}
} else if (error.errcode == "M_CONSENT_NOT_GIVEN") {
this.eventEmitter.emit(HttpApiEvent.NoConsent, error.message, error.data.consent_uri);
}
throw error;
}
});
// return the original promise, otherwise tests break due to it having to
// go around the event loop one more time to process the result of the request
return requestPromise;
}
/**
@@ -164,11 +152,21 @@ export class FetchHttpApi {
*
* @param opts - additional options
*
* @returns The parsed response.
* @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.
* @returns Promise which resolves to
* ```
* {
* data: {Object},
* headers: {Object},
* code: {Number},
* }
* ```
* If `onlyData</code> is set, this will resolve to the <code>data`
* object only.
* @returns Rejects with an error if a problem
* occurred. This includes network problems and Matrix-specific error JSON.
*/
request(method, path, queryParams, body, opts) {
const fullUri = this.getUrl(path, queryParams, opts?.prefix, opts?.baseUrl);
const fullUri = this.getUrl(path, queryParams, opts === null || opts === void 0 ? void 0 : opts.prefix, opts === null || opts === void 0 ? void 0 : opts.baseUrl);
return this.requestOtherUrl(method, fullUri, body, opts);
}
@@ -181,55 +179,46 @@ export class FetchHttpApi {
*
* @param opts - additional options
*
* @returns The parsed response.
* @throws Error if a problem occurred. This includes network problems and Matrix-specific error JSON.
* @returns Promise which resolves to data unless `onlyData` is specified as false,
* where the resolved value will be a fetch Response object.
* @returns Rejects with an error if a problem
* occurred. This includes network problems and Matrix-specific error JSON.
*/
async requestOtherUrl(method, url, body, opts = {}) {
if (opts.json !== undefined && opts.rawResponseBody !== undefined) {
throw new Error("Invalid call to `FetchHttpApi` sets both `opts.json` and `opts.rawResponseBody`");
}
var _opts$json, _body$constructor, _opts$localTimeoutMs, _opts$keepAlive;
const urlForLogs = this.sanitizeUrlForLogs(url);
this.opts.logger?.debug(`FetchHttpApi: --> ${method} ${urlForLogs}`);
_logger.logger.debug(`FetchHttpApi: --> ${method} ${urlForLogs}`);
const headers = Object.assign({}, opts.headers || {});
const jsonResponse = !opts.rawResponseBody && opts.json !== false;
if (jsonResponse) {
const json = (_opts$json = opts.json) !== null && _opts$json !== void 0 ? _opts$json : true;
// We can't use getPrototypeOf here as objects made in other contexts e.g. over postMessage won't have same ref
const jsonBody = json && (body === null || body === void 0 || (_body$constructor = body.constructor) === null || _body$constructor === void 0 ? void 0 : _body$constructor.name) === Object.name;
if (json) {
if (jsonBody && !headers["Content-Type"]) {
headers["Content-Type"] = "application/json";
}
if (!headers["Accept"]) {
headers["Accept"] = "application/json";
}
}
const timeout = opts.localTimeoutMs ?? this.opts.localTimeoutMs;
const keepAlive = opts.keepAlive ?? false;
const timeout = (_opts$localTimeoutMs = opts.localTimeoutMs) !== null && _opts$localTimeoutMs !== void 0 ? _opts$localTimeoutMs : this.opts.localTimeoutMs;
const keepAlive = (_opts$keepAlive = opts.keepAlive) !== null && _opts$keepAlive !== void 0 ? _opts$keepAlive : false;
const signals = [this.abortController.signal];
if (timeout !== undefined) {
signals.push(timeoutSignal(timeout));
signals.push((0, _utils2.timeoutSignal)(timeout));
}
if (opts.abortSignal) {
signals.push(opts.abortSignal);
}
// If the body is an object, encode it as JSON and set the `Content-Type` header,
// unless that has been explicitly inhibited by setting `opts.json: false`.
// We can't use getPrototypeOf here as objects made in other contexts e.g. over postMessage won't have same ref
let data;
if (opts.json !== false && body?.constructor?.name === Object.name) {
if (jsonBody) {
data = JSON.stringify(body);
if (!headers["Content-Type"]) {
headers["Content-Type"] = "application/json";
}
} else {
data = body;
}
const {
signal,
cleanup
} = anySignal(signals);
// Set cache mode based on presence of Authorization header.
// Browsers/proxies do not cache responses to requests with Authorization headers.
// So specifying "no-cache" is redundant, and actually prevents caching
// of preflight requests in CORS scenarios. As such, we only set "no-cache"
// when there is no Authorization header.
const cacheMode = "Authorization" in headers ? undefined : "no-cache";
} = (0, _utils2.anySignal)(signals);
let res;
const start = Date.now();
try {
@@ -242,32 +231,29 @@ export class FetchHttpApi {
redirect: "follow",
referrer: "",
referrerPolicy: "no-referrer",
cache: cacheMode,
cache: "no-cache",
credentials: "omit",
// we send credentials via headers
keepalive: keepAlive,
priority: opts.priority
});
this.opts.logger?.debug(`FetchHttpApi: <-- ${method} ${urlForLogs} [${Date.now() - start}ms ${res.status}]`);
_logger.logger.debug(`FetchHttpApi: <-- ${method} ${urlForLogs} [${Date.now() - start}ms ${res.status}]`);
} catch (e) {
this.opts.logger?.debug(`FetchHttpApi: <-- ${method} ${urlForLogs} [${Date.now() - start}ms ${e}]`);
_logger.logger.debug(`FetchHttpApi: <-- ${method} ${urlForLogs} [${Date.now() - start}ms ${e}]`);
if (e.name === "AbortError") {
throw e;
}
throw new ConnectionError("fetch failed", e);
throw new _errors.ConnectionError("fetch failed", e);
} finally {
cleanup();
}
if (!res.ok) {
throw parseErrorResponse(res, await res.text());
throw (0, _utils2.parseErrorResponse)(res, await res.text());
}
if (opts.rawResponseBody) {
return await res.blob();
} else if (jsonResponse) {
return await res.json();
} else {
return await res.text();
if (this.opts.onlyData) {
return json ? res.json() : res.text();
}
return res;
}
sanitizeUrlForLogs(url) {
try {
@@ -285,7 +271,7 @@ export class FetchHttpApi {
const sanitizedQsString = sanitizedQs.toString();
const sanitizedQsUrlPiece = sanitizedQsString ? `?${sanitizedQsString}` : "";
return asUrl.origin + asUrl.pathname + sanitizedQsUrlPiece;
} catch {
} catch (error) {
// defensive coding for malformed url
return "??";
}
@@ -299,15 +285,14 @@ export class FetchHttpApi {
* @returns URL
*/
getUrl(path, queryParams, prefix, baseUrl) {
const baseUrlWithFallback = baseUrl ?? this.opts.baseUrl;
const baseUrlWithFallback = baseUrl !== null && baseUrl !== void 0 ? baseUrl : this.opts.baseUrl;
const baseUrlWithoutTrailingSlash = baseUrlWithFallback.endsWith("/") ? baseUrlWithFallback.slice(0, -1) : baseUrlWithFallback;
const url = new URL(baseUrlWithoutTrailingSlash + (prefix ?? this.opts.prefix) + path);
// If there are any params, encode and append them to the URL.
if (this.opts.extraParams || queryParams) {
const mergedParams = _objectSpread(_objectSpread({}, this.opts.extraParams), queryParams);
encodeParams(mergedParams, url.searchParams);
const url = new URL(baseUrlWithoutTrailingSlash + (prefix !== null && prefix !== void 0 ? prefix : this.opts.prefix) + path);
if (queryParams) {
(0, _utils.encodeParams)(queryParams, url.searchParams);
}
return url;
}
}
exports.FetchHttpApi = FetchHttpApi;
//# sourceMappingURL=fetch.js.map